@rpamis/comet 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (464) hide show
  1. package/README.md +372 -332
  2. package/assets/manifest.json +1 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +113 -97
  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 +170 -157
  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 +272 -153
  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 +311 -296
  13. package/assets/skills/comet/scripts/comet-state.mjs +221 -207
  14. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
  15. package/assets/skills/comet-archive/SKILL.md +13 -9
  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 +51 -7
  23. package/assets/skills/comet-native/reference/clarification.md +5 -5
  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 +257 -169
  28. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +238 -153
  29. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +241 -124
  30. package/assets/skills/comet-native/scripts/comet-native-init.mjs +189 -108
  31. package/assets/skills/comet-native/scripts/comet-native-new.mjs +220 -139
  32. package/assets/skills/comet-native/scripts/comet-native-next.mjs +245 -160
  33. package/assets/skills/comet-native/scripts/comet-native-root.mjs +210 -129
  34. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +284 -196
  35. package/assets/skills/comet-native/scripts/comet-native-select.mjs +212 -128
  36. package/assets/skills/comet-native/scripts/comet-native-show.mjs +207 -126
  37. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +203 -118
  38. package/assets/skills/comet-native/scripts/comet-native-status.mjs +208 -124
  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 +13 -9
  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 +51 -7
  50. package/assets/skills-zh/comet-native/reference/clarification.md +5 -5
  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/cli/index.js +1 -0
  60. package/dist/app/cli/index.js.map +1 -1
  61. package/dist/app/commands/daemon-server.d.ts.map +1 -1
  62. package/dist/app/commands/daemon-server.js +13 -2
  63. package/dist/app/commands/daemon-server.js.map +1 -1
  64. package/dist/app/commands/doctor.d.ts.map +1 -1
  65. package/dist/app/commands/doctor.js +17 -10
  66. package/dist/app/commands/doctor.js.map +1 -1
  67. package/dist/app/commands/i18n.d.ts +1 -1
  68. package/dist/app/commands/i18n.d.ts.map +1 -1
  69. package/dist/app/commands/i18n.js +4 -0
  70. package/dist/app/commands/i18n.js.map +1 -1
  71. package/dist/app/commands/project-knowledge.d.ts +2 -0
  72. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  73. package/dist/app/commands/project-knowledge.js +64 -7
  74. package/dist/app/commands/project-knowledge.js.map +1 -1
  75. package/dist/app/commands/uninstall.d.ts +1 -0
  76. package/dist/app/commands/uninstall.d.ts.map +1 -1
  77. package/dist/app/commands/uninstall.js +65 -10
  78. package/dist/app/commands/uninstall.js.map +1 -1
  79. package/dist/domains/agent-learning/coordinator.d.ts +8 -1
  80. package/dist/domains/agent-learning/coordinator.d.ts.map +1 -1
  81. package/dist/domains/agent-learning/coordinator.js +58 -0
  82. package/dist/domains/agent-learning/coordinator.js.map +1 -1
  83. package/dist/domains/agent-learning/experience-journal.d.ts +21 -1
  84. package/dist/domains/agent-learning/experience-journal.d.ts.map +1 -1
  85. package/dist/domains/agent-learning/experience-journal.js +190 -11
  86. package/dist/domains/agent-learning/experience-journal.js.map +1 -1
  87. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  88. package/dist/domains/bundle/bundle-platform.js +6 -1
  89. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  90. package/dist/domains/comet-classic/classic-archive-entry.d.ts +1 -1
  91. package/dist/domains/comet-classic/classic-archive-entry.d.ts.map +1 -1
  92. package/dist/domains/comet-classic/classic-archive-entry.js +5 -2
  93. package/dist/domains/comet-classic/classic-archive-entry.js.map +1 -1
  94. package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
  95. package/dist/domains/comet-classic/classic-archive.js +5 -1
  96. package/dist/domains/comet-classic/classic-archive.js.map +1 -1
  97. package/dist/domains/comet-classic/classic-branch-binding.d.ts.map +1 -1
  98. package/dist/domains/comet-classic/classic-branch-binding.js +5 -4
  99. package/dist/domains/comet-classic/classic-branch-binding.js.map +1 -1
  100. package/dist/domains/comet-classic/classic-check-entry.d.ts +1 -1
  101. package/dist/domains/comet-classic/classic-check-entry.d.ts.map +1 -1
  102. package/dist/domains/comet-classic/classic-check-entry.js +5 -2
  103. package/dist/domains/comet-classic/classic-check-entry.js.map +1 -1
  104. package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
  105. package/dist/domains/comet-classic/classic-check-snapshot.js +68 -26
  106. package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
  107. package/dist/domains/comet-classic/classic-design-readiness.d.ts +1 -1
  108. package/dist/domains/comet-classic/classic-guard-entry.d.ts +1 -1
  109. package/dist/domains/comet-classic/classic-guard-entry.d.ts.map +1 -1
  110. package/dist/domains/comet-classic/classic-guard-entry.js +5 -2
  111. package/dist/domains/comet-classic/classic-guard-entry.js.map +1 -1
  112. package/dist/domains/comet-classic/classic-handoff-entry.d.ts +1 -1
  113. package/dist/domains/comet-classic/classic-handoff-entry.d.ts.map +1 -1
  114. package/dist/domains/comet-classic/classic-handoff-entry.js +5 -2
  115. package/dist/domains/comet-classic/classic-handoff-entry.js.map +1 -1
  116. package/dist/domains/comet-classic/classic-progress.d.ts +60 -2
  117. package/dist/domains/comet-classic/classic-progress.d.ts.map +1 -1
  118. package/dist/domains/comet-classic/classic-progress.js +199 -22
  119. package/dist/domains/comet-classic/classic-progress.js.map +1 -1
  120. package/dist/domains/comet-classic/classic-recovery.d.ts +20 -1
  121. package/dist/domains/comet-classic/classic-recovery.d.ts.map +1 -1
  122. package/dist/domains/comet-classic/classic-resume-probe.d.ts.map +1 -1
  123. package/dist/domains/comet-classic/classic-resume-probe.js +3 -2
  124. package/dist/domains/comet-classic/classic-resume-probe.js.map +1 -1
  125. package/dist/domains/comet-classic/classic-script-entry.d.ts +3 -1
  126. package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
  127. package/dist/domains/comet-classic/classic-script-entry.js +34 -3
  128. package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
  129. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  130. package/dist/domains/comet-classic/classic-state-command.js +3 -2
  131. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  132. package/dist/domains/comet-classic/classic-state-entry.d.ts +1 -1
  133. package/dist/domains/comet-classic/classic-state-entry.d.ts.map +1 -1
  134. package/dist/domains/comet-classic/classic-state-entry.js +5 -2
  135. package/dist/domains/comet-classic/classic-state-entry.js.map +1 -1
  136. package/dist/domains/comet-classic/classic-store.d.ts.map +1 -1
  137. package/dist/domains/comet-classic/classic-store.js +67 -1
  138. package/dist/domains/comet-classic/classic-store.js.map +1 -1
  139. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  140. package/dist/domains/comet-entry/resume-probe.js +3 -2
  141. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  142. package/dist/domains/comet-native/native-acceptance.d.ts +5 -1
  143. package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
  144. package/dist/domains/comet-native/native-acceptance.js +13 -2
  145. package/dist/domains/comet-native/native-acceptance.js.map +1 -1
  146. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  147. package/dist/domains/comet-native/native-archive-command.js +167 -37
  148. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  149. package/dist/domains/comet-native/native-artifact-language.d.ts +10 -1
  150. package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
  151. package/dist/domains/comet-native/native-artifact-language.js +65 -12
  152. package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
  153. package/dist/domains/comet-native/native-artifacts.d.ts +10 -1
  154. package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
  155. package/dist/domains/comet-native/native-artifacts.js +130 -21
  156. package/dist/domains/comet-native/native-artifacts.js.map +1 -1
  157. package/dist/domains/comet-native/native-builder-acceptance-review.d.ts +16 -0
  158. package/dist/domains/comet-native/native-builder-acceptance-review.d.ts.map +1 -0
  159. package/dist/domains/comet-native/native-builder-acceptance-review.js +65 -0
  160. package/dist/domains/comet-native/native-builder-acceptance-review.js.map +1 -0
  161. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  162. package/dist/domains/comet-native/native-cli-help.js +8 -4
  163. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  164. package/dist/domains/comet-native/native-cli-shared.d.ts +4 -2
  165. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  166. package/dist/domains/comet-native/native-cli-shared.js +37 -9
  167. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  168. package/dist/domains/comet-native/native-cli.d.ts +4 -1
  169. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  170. package/dist/domains/comet-native/native-cli.js +9 -5
  171. package/dist/domains/comet-native/native-cli.js.map +1 -1
  172. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  173. package/dist/domains/comet-native/native-doctor-command.js +144 -3
  174. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  175. package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -1
  176. package/dist/domains/comet-native/native-git-provenance.js +3 -2
  177. package/dist/domains/comet-native/native-git-provenance.js.map +1 -1
  178. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  179. package/dist/domains/comet-native/native-hook-guard.js +57 -26
  180. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  181. package/dist/domains/comet-native/native-local-execution.d.ts +1 -0
  182. package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -1
  183. package/dist/domains/comet-native/native-local-execution.js +7 -0
  184. package/dist/domains/comet-native/native-local-execution.js.map +1 -1
  185. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  186. package/dist/domains/comet-native/native-lock.js +12 -0
  187. package/dist/domains/comet-native/native-lock.js.map +1 -1
  188. package/dist/domains/comet-native/native-loop-runtime.d.ts +2 -0
  189. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  190. package/dist/domains/comet-native/native-loop-runtime.js +6 -0
  191. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  192. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  193. package/dist/domains/comet-native/native-next-command.js +57 -28
  194. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  195. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
  196. package/dist/domains/comet-native/native-output-language.js +7 -0
  197. package/dist/domains/comet-native/native-output-language.js.map +1 -1
  198. package/dist/domains/comet-native/native-portable-acceptance.d.ts +2 -0
  199. package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -1
  200. package/dist/domains/comet-native/native-portable-acceptance.js +11 -1
  201. package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -1
  202. package/dist/domains/comet-native/native-portable-archive.d.ts +1 -0
  203. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
  204. package/dist/domains/comet-native/native-portable-archive.js +3 -0
  205. package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
  206. package/dist/domains/comet-native/native-portable-checks.d.ts +14 -4
  207. package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
  208. package/dist/domains/comet-native/native-portable-checks.js +159 -60
  209. package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
  210. package/dist/domains/comet-native/native-portable-continuation.d.ts +2 -1
  211. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  212. package/dist/domains/comet-native/native-portable-continuation.js +121 -39
  213. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  214. package/dist/domains/comet-native/native-portable-requirements.d.ts +1 -0
  215. package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
  216. package/dist/domains/comet-native/native-portable-requirements.js +68 -18
  217. package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
  218. package/dist/domains/comet-native/native-portable-shape-coordination.d.ts.map +1 -1
  219. package/dist/domains/comet-native/native-portable-shape-coordination.js +18 -5
  220. package/dist/domains/comet-native/native-portable-shape-coordination.js.map +1 -1
  221. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  222. package/dist/domains/comet-native/native-portable-state.js +12 -3
  223. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  224. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
  225. package/dist/domains/comet-native/native-portable-status.js +10 -4
  226. package/dist/domains/comet-native/native-portable-status.js.map +1 -1
  227. package/dist/domains/comet-native/native-portable-types.d.ts +2 -1
  228. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  229. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  230. package/dist/domains/comet-native/native-portable-verification.d.ts +3 -0
  231. package/dist/domains/comet-native/native-portable-verification.d.ts.map +1 -1
  232. package/dist/domains/comet-native/native-portable-verification.js +28 -35
  233. package/dist/domains/comet-native/native-portable-verification.js.map +1 -1
  234. package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts +2 -0
  235. package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts.map +1 -1
  236. package/dist/domains/comet-native/native-portable-verifier-coordination.js +9 -0
  237. package/dist/domains/comet-native/native-portable-verifier-coordination.js.map +1 -1
  238. package/dist/domains/comet-native/native-runner-input-artifacts.d.ts +9 -0
  239. package/dist/domains/comet-native/native-runner-input-artifacts.d.ts.map +1 -0
  240. package/dist/domains/comet-native/native-runner-input-artifacts.js +102 -0
  241. package/dist/domains/comet-native/native-runner-input-artifacts.js.map +1 -0
  242. package/dist/domains/comet-native/native-runner-input.d.ts +90 -64
  243. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  244. package/dist/domains/comet-native/native-runner-input.js +107 -22
  245. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  246. package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
  247. package/dist/domains/comet-native/native-script-entry.js +9 -3
  248. package/dist/domains/comet-native/native-script-entry.js.map +1 -1
  249. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  250. package/dist/domains/comet-native/native-snapshot.js +7 -2
  251. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  252. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  253. package/dist/domains/comet-native/native-verification-receipt-runtime.js +5 -4
  254. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  255. package/dist/domains/comet-native/native-workspace-finish.d.ts +26 -0
  256. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
  257. package/dist/domains/comet-native/native-workspace-finish.js +520 -15
  258. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
  259. package/dist/domains/comet-plugin/integration.d.ts +1 -0
  260. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  261. package/dist/domains/comet-plugin/integration.js +20 -10
  262. package/dist/domains/comet-plugin/integration.js.map +1 -1
  263. package/dist/domains/comet-plugin/plugin-runtime.d.ts +8 -2
  264. package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
  265. package/dist/domains/comet-plugin/plugin-runtime.js +18 -4
  266. package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
  267. package/dist/domains/dashboard/project-directory.d.ts +4 -0
  268. package/dist/domains/dashboard/project-directory.d.ts.map +1 -1
  269. package/dist/domains/dashboard/project-directory.js +30 -2
  270. package/dist/domains/dashboard/project-directory.js.map +1 -1
  271. package/dist/domains/dashboard/server.d.ts.map +1 -1
  272. package/dist/domains/dashboard/server.js +28 -3
  273. package/dist/domains/dashboard/server.js.map +1 -1
  274. package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-qlcciI25.js → abnfDiagram-VCTEODGH-m9_t3fwH.js} +1 -1
  275. package/dist/domains/dashboard/web/assets/{arc-KVm4k9kp.js → arc-CDiwRrMg.js} +1 -1
  276. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-ypJOsR2Y.js +1 -0
  277. package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-C366RdBK.js → architectureDiagram-5GKGNRK7-Xwj-hlQB.js} +1 -1
  278. package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-DAuTc2OO.js → blockDiagram-I7D4REHJ-Cme6qNK_.js} +1 -1
  279. package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-CFB0RZmL.js → c4Diagram-7LVT6UL2-Cxs1dU7y.js} +1 -1
  280. package/dist/domains/dashboard/web/assets/channel-BFTjR7Ng.js +1 -0
  281. package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-DTV6lyGQ.js → chunk-4HAMMTFA-DBQykIWE.js} +1 -1
  282. package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-DgJm4cEX.js → chunk-75Z2AOVW-Dh-E6TAx.js} +1 -1
  283. package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-NAtcgGZr.js → chunk-DU6HZSFF-W3lPaoVP.js} +2 -2
  284. package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-BcFXHZMJ.js → chunk-F27PBJKO-dzf1fpYi.js} +1 -1
  285. package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-wNemar9b.js → chunk-GMAD6QVW-CeuSGVHV.js} +1 -1
  286. package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-BiVCDO9d.js → chunk-GVQU2GXP-BrGrIBgk.js} +1 -1
  287. package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-D9GDj4b6.js → chunk-IMKFNOWR-DXiTC1Xo.js} +1 -1
  288. package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-DkPl5vac.js → chunk-L3NEJ4N5-DnyD3Ocj.js} +1 -1
  289. package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-RbbxGqtJ.js → chunk-OSK3NFVY-6vxhPm51.js} +1 -1
  290. package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-B9_X57eT.js → chunk-P2QGCYS3-DChNsVqO.js} +1 -1
  291. package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DE4bOH0D.js → chunk-POPQ4Y6H-RBgha6dE.js} +1 -1
  292. package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Bo-W1iA1.js → chunk-PWAF6VOD-CayoKmnh.js} +1 -1
  293. package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BhLxs4rZ.js → chunk-SHT3W25Y-sOkLJZoB.js} +1 -1
  294. package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-BCXfn8uF.js → chunk-SVP7TREG-j0QRwmsq.js} +1 -1
  295. package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-DqSBgE5L.js → chunk-TICWLB2K-D7Re_d_T.js} +1 -1
  296. package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-Dbkt1xEZ.js → chunk-XXDRQBXY-BFV70fKF.js} +1 -1
  297. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-gDSLbV2K.js +1 -0
  298. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-gDSLbV2K.js +1 -0
  299. package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-DrwNpMyX.js → cose-bilkent-JH36ORCC-k7gqx2Br.js} +1 -1
  300. package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-BbDlivxs.js → cynefin-OW5HDTMX-CWI6FZT8.js} +1 -1
  301. package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DmLmRN42.js → cynefinDiagram-5FMLGOSQ-D-O3RrOu.js} +1 -1
  302. package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-Cgm5DNgI.js → dagre-GXQ25YYZ-BR1jxWfn.js} +1 -1
  303. package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-Bnht1X2m.js → diagram-S7CK7UJ4-B6gXFYBj.js} +1 -1
  304. package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-LELTI4PR.js → diagram-UQ7AKVKN-BBW6aRk8.js} +1 -1
  305. package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-Do0fZuNG.js → diagram-VSXAHHWV-BC0CZeyH.js} +1 -1
  306. package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-B0rZTUwt.js → diagram-VX7I27RA-BmwBIkwS.js} +1 -1
  307. package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-wn8xCc_j.js → diagram-Z3DM3KII-DTZgX9SF.js} +1 -1
  308. package/dist/domains/dashboard/web/assets/{dist-CYwDKy2m.js → dist-brXLwleg.js} +1 -1
  309. package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CMDOpP2T.js → ebnfDiagram-PWID7BFC-CsMXo0C6.js} +1 -1
  310. package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-C2d43bdq.js → erDiagram-RLTQ6QDP-DQ9ewX94.js} +1 -1
  311. package/dist/domains/dashboard/web/assets/{es-BzaOcXwu.js → es-CgcAhzLf.js} +1 -1
  312. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-Ll12Q19y.js +1 -0
  313. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Bf2-9XUn.js +1 -0
  314. package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-hTH7TzhY.js → ganttDiagram-EL5Y4UJY-DIFkXe6G.js} +1 -1
  315. package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-C3CCywb-.js → gitGraph-4MIJSDKK-BHY8ZnpE.js} +1 -1
  316. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-DW6jDckj.js → gitGraphDiagram-WWUBYQGX-cBn9dMzs.js} +1 -1
  317. package/dist/domains/dashboard/web/assets/{index-CTZPz_mx.js → index-C_6nf1Fw.js} +3 -3
  318. package/dist/domains/dashboard/web/assets/{index-CWNqBYyI.css → index-Gaxnq6Jd.css} +1 -1
  319. package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-Bg3eKis8.js → info-A6RAGUB7-DtUaS9jN.js} +1 -1
  320. package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-7zk6ytVJ.js → infoDiagram-27XIBGKW-CIl0e_EN.js} +1 -1
  321. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CGDCTmCQ.js → ishikawaDiagram-5VMMS53U-DAdtPZ_c.js} +1 -1
  322. package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-C8_L_e8a.js → journeyDiagram-3NMN7TZE-CBokRgde.js} +1 -1
  323. package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-D5x6qTgM.js → kanban-definition-UXKFOSKX-DrqCYJ-7.js} +1 -1
  324. package/dist/domains/dashboard/web/assets/katex-D29apahB.js +257 -0
  325. package/dist/domains/dashboard/web/assets/{line-DC93oja4.js → line-BDlVqlh4.js} +1 -1
  326. package/dist/domains/dashboard/web/assets/{linear-81TNubkB.js → linear-DTAzui9x.js} +1 -1
  327. package/dist/domains/dashboard/web/assets/{mermaid-parser.core-D60d8uy9.js → mermaid-parser.core-CFw-xbYY.js} +3 -3
  328. package/dist/domains/dashboard/web/assets/{mermaid.core-l4Wgjz2Q.js → mermaid.core-Ck7fB8UD.js} +4 -4
  329. package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-Dfqu1201.js → mindmap-definition-YA3MSWOX-C7kb9KL9.js} +1 -1
  330. package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CsFZBhTs.js → packet-AYTQ26CC-P8Mtt0tp.js} +1 -1
  331. package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-myFMaA7n.js → pegDiagram-XKGWAZYB-DUDD9qv5.js} +1 -1
  332. package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-FMuCTNSk.js → pie-WAS4IAKB-dEmLxiDR.js} +1 -1
  333. package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-CSR4B4Z1.js → pieDiagram-E7YTZNPT-BUssAcqk.js} +1 -1
  334. package/dist/domains/dashboard/web/assets/purify.es-Bvo9QlJ8.js +3 -0
  335. package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-BiE4kEeP.js → quadrantDiagram-AXDQQJYC-BzaAWdQL.js} +1 -1
  336. package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-BZ-n7JtG.js → radar-RG4KPBEZ-mqtvaz9w.js} +1 -1
  337. package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CWVtRfHu.js → railroad-74A4TZTK-7tTnGpoz.js} +1 -1
  338. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CpJvyBJM.js +1 -0
  339. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-BJ5g77l6.js +1 -0
  340. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-BslCK-Gr.js +1 -0
  341. package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-CBj7v1de.js → railroadDiagram-O6MQD6OU-DM1AKXm0.js} +1 -1
  342. package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-DSDgb54n.js → requirementDiagram-BXWQKSXE--H5KiPSc.js} +1 -1
  343. package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-1-oXLUAP.js → sankeyDiagram-P5KCCOFB-JweUq_u2.js} +1 -1
  344. package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DAF4nGs_.js → sequenceDiagram-WJ2MYXX4-pxb1iTGb.js} +1 -1
  345. package/dist/domains/dashboard/web/assets/{src-CTWLVUqE.js → src-joFOxopw.js} +1 -1
  346. package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-DzENBaJT.js → stateDiagram-D77RDMKH-CDu5crd8.js} +1 -1
  347. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-wV5AqWaM.js +1 -0
  348. package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-CnxFUZJc.js → swimlanes-42K2YHIH-ioSqowJ4.js} +1 -1
  349. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DOPLn-V5.js +8 -0
  350. package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-KtvPzpZM.js → timeline-definition-24CTP7MA-2YXSYkS3.js} +1 -1
  351. package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bdu3P9iY.js → treeView-Q6P3EWNA-DEGims38.js} +1 -1
  352. package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-DFnn23JR.js → treemap-WGGIJYW6-CJvBhTlR.js} +1 -1
  353. package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-BjpviP26.js → vennDiagram-4TSXK5OY-CHdNWhBK.js} +1 -1
  354. package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-CEo4a-j4.js → wardley-WFR3VGLG-CVO9PCjo.js} +1 -1
  355. package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-Bf54n6im.js → wardleyDiagram-VM6X3IG4-RToPmij6.js} +1 -1
  356. package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-CU-hI0Cm.js → xychartDiagram-S5SC5T6Z-DaWHnpHE.js} +1 -1
  357. package/dist/domains/dashboard/web/index.html +2 -2
  358. package/dist/domains/project-knowledge/host-review.d.ts +15 -2
  359. package/dist/domains/project-knowledge/host-review.d.ts.map +1 -1
  360. package/dist/domains/project-knowledge/host-review.js +65 -25
  361. package/dist/domains/project-knowledge/host-review.js.map +1 -1
  362. package/dist/domains/project-knowledge/index.d.ts +1 -0
  363. package/dist/domains/project-knowledge/index.d.ts.map +1 -1
  364. package/dist/domains/project-knowledge/index.js +1 -0
  365. package/dist/domains/project-knowledge/index.js.map +1 -1
  366. package/dist/domains/project-knowledge/learning.d.ts +2 -1
  367. package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
  368. package/dist/domains/project-knowledge/learning.js +6 -0
  369. package/dist/domains/project-knowledge/learning.js.map +1 -1
  370. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  371. package/dist/domains/project-knowledge/plugin.js +3 -1
  372. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  373. package/dist/domains/skill/dsh-adapter.d.ts +5 -1
  374. package/dist/domains/skill/dsh-adapter.d.ts.map +1 -1
  375. package/dist/domains/skill/dsh-adapter.js +222 -87
  376. package/dist/domains/skill/dsh-adapter.js.map +1 -1
  377. package/dist/domains/skill/platform-inspect.d.ts +1 -0
  378. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  379. package/dist/domains/skill/platform-inspect.js +8 -4
  380. package/dist/domains/skill/platform-inspect.js.map +1 -1
  381. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  382. package/dist/domains/skill/platform-install.js +7 -7
  383. package/dist/domains/skill/platform-install.js.map +1 -1
  384. package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -1
  385. package/dist/domains/workflow-contract/hook-target-scope.js +2 -1
  386. package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -1
  387. package/dist/platform/fs/file-system.d.ts +2 -0
  388. package/dist/platform/fs/file-system.d.ts.map +1 -1
  389. package/dist/platform/fs/file-system.js +11 -0
  390. package/dist/platform/fs/file-system.js.map +1 -1
  391. package/dist/platform/install/dsh-profiles.d.ts +3 -0
  392. package/dist/platform/install/dsh-profiles.d.ts.map +1 -0
  393. package/dist/platform/install/dsh-profiles.js +40 -0
  394. package/dist/platform/install/dsh-profiles.js.map +1 -0
  395. package/dist/platform/install/platforms.d.ts.map +1 -1
  396. package/dist/platform/install/platforms.js +1 -0
  397. package/dist/platform/install/platforms.js.map +1 -1
  398. package/dist/platform/install/project-registry.d.ts +7 -1
  399. package/dist/platform/install/project-registry.d.ts.map +1 -1
  400. package/dist/platform/install/project-registry.js +49 -5
  401. package/dist/platform/install/project-registry.js.map +1 -1
  402. package/dist/platform/paths/git-worktree-cache.d.ts +3 -0
  403. package/dist/platform/paths/git-worktree-cache.d.ts.map +1 -0
  404. package/dist/platform/paths/git-worktree-cache.js +109 -0
  405. package/dist/platform/paths/git-worktree-cache.js.map +1 -0
  406. package/dist/platform/paths/git-worktree.d.ts +6 -0
  407. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  408. package/dist/platform/paths/git-worktree.js +191 -30
  409. package/dist/platform/paths/git-worktree.js.map +1 -1
  410. package/dist/platform/paths/project-worktree-root.d.ts +3 -0
  411. package/dist/platform/paths/project-worktree-root.d.ts.map +1 -0
  412. package/dist/platform/paths/project-worktree-root.js +14 -0
  413. package/dist/platform/paths/project-worktree-root.js.map +1 -0
  414. package/dist/platform/process/comet-daemon.d.ts +3 -0
  415. package/dist/platform/process/comet-daemon.d.ts.map +1 -1
  416. package/dist/platform/process/comet-daemon.js +8 -6
  417. package/dist/platform/process/comet-daemon.js.map +1 -1
  418. package/dist/platform/process/external-command.d.ts +3 -0
  419. package/dist/platform/process/external-command.d.ts.map +1 -1
  420. package/dist/platform/process/external-command.js +69 -2
  421. package/dist/platform/process/external-command.js.map +1 -1
  422. package/dist/platform/process/git.d.ts.map +1 -1
  423. package/dist/platform/process/git.js +3 -4
  424. package/dist/platform/process/git.js.map +1 -1
  425. package/dist/platform/process/hook-adapter.d.ts +2 -0
  426. package/dist/platform/process/hook-adapter.d.ts.map +1 -1
  427. package/dist/platform/process/hook-adapter.js +45 -3
  428. package/dist/platform/process/hook-adapter.js.map +1 -1
  429. package/dist/platform/process/hook-read-cache.d.ts +2 -0
  430. package/dist/platform/process/hook-read-cache.d.ts.map +1 -1
  431. package/dist/platform/process/hook-read-cache.js +25 -13
  432. package/dist/platform/process/hook-read-cache.js.map +1 -1
  433. package/dist/platform/process/process-identity.d.ts.map +1 -1
  434. package/dist/platform/process/process-identity.js +18 -51
  435. package/dist/platform/process/process-identity.js.map +1 -1
  436. package/dist/platform/process/runtime-metrics.d.ts +10 -1
  437. package/dist/platform/process/runtime-metrics.d.ts.map +1 -1
  438. package/dist/platform/process/runtime-metrics.js +37 -2
  439. package/dist/platform/process/runtime-metrics.js.map +1 -1
  440. package/dist/platform/process/windows-process-broker.d.ts +1 -0
  441. package/dist/platform/process/windows-process-broker.d.ts.map +1 -1
  442. package/dist/platform/process/windows-process-broker.js +70 -11
  443. package/dist/platform/process/windows-process-broker.js.map +1 -1
  444. package/dist/platform/process/windows-process-identity.d.ts +6 -0
  445. package/dist/platform/process/windows-process-identity.d.ts.map +1 -0
  446. package/dist/platform/process/windows-process-identity.js +190 -0
  447. package/dist/platform/process/windows-process-identity.js.map +1 -0
  448. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +11 -3
  449. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +11 -3
  450. package/eval/local/tests/scaffold/test_task_resolution.py +6 -2
  451. package/package.json +14 -8
  452. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-QeljAKq2.js +0 -1
  453. package/dist/domains/dashboard/web/assets/channel-_AqwP0KA.js +0 -1
  454. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-CRo4aB_7.js +0 -1
  455. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-CRo4aB_7.js +0 -1
  456. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-KYANo3DQ.js +0 -1
  457. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-CSROlLuj.js +0 -1
  458. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +0 -257
  459. package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +0 -3
  460. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CkHwwI2i.js +0 -1
  461. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-8xzEHL6v.js +0 -1
  462. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-nSHBw0tH.js +0 -1
  463. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-CNw52Fkn.js +0 -1
  464. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-6TRvbqqI.js +0 -8
@@ -1,199 +1,283 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var fS=Object.create;var _l=Object.defineProperty;var pS=Object.getOwnPropertyDescriptor;var hS=Object.getOwnPropertyNames;var mS=Object.getPrototypeOf,vS=Object.prototype.hasOwnProperty;var xo=(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 I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},gS=(e,t)=>{for(var r in t)_l(e,r,{get:t[r],enumerable:!0})},wS=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of hS(t))!vS.call(e,n)&&n!==r&&_l(e,n,{get:()=>t[n],enumerable:!(i=pS(t,n))||i.enumerable});return e};var Gt=(e,t,r)=>(r=e!=null?fS(mS(e)):{},wS(t||!e||!e.__esModule?_l(r,"default",{value:e,enumerable:!0}):r,e));import{createHash as bS}from"crypto";function ut(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function kS(e,t){t.has(e)&&ut("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)||ut("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&ut("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ut("symbol properties are not supported"),`[${e.map(i=>Il(i,t)).join(",")}]`}finally{t.delete(e)}}function SS(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&ut("only plain objects are supported"),t.has(e)&&ut("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ut("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))&&ut("accessor properties are not supported"),`${JSON.stringify(o)}:${Il(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Il(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)||ut("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?kS(e,t):SS(e,t);case"bigint":case"function":case"symbol":case"undefined":return ut(`${typeof e} values are not supported`)}return ut("unsupported value type")}function Tn(e){return Il(e,new Set)}function T(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 bS("sha256").update(`${e}
5
- ${Tn(t)}`).digest("hex")}var ce=I(()=>{"use strict"});var W=P(be=>{"use strict";var jl=Symbol.for("yaml.alias"),Sh=Symbol.for("yaml.document"),Po=Symbol.for("yaml.map"),Eh=Symbol.for("yaml.pair"),Tl=Symbol.for("yaml.scalar"),Ro=Symbol.for("yaml.seq"),Kt=Symbol.for("yaml.node.type"),ES=e=>!!e&&typeof e=="object"&&e[Kt]===jl,xS=e=>!!e&&typeof e=="object"&&e[Kt]===Sh,CS=e=>!!e&&typeof e=="object"&&e[Kt]===Po,PS=e=>!!e&&typeof e=="object"&&e[Kt]===Eh,xh=e=>!!e&&typeof e=="object"&&e[Kt]===Tl,RS=e=>!!e&&typeof e=="object"&&e[Kt]===Ro;function Ch(e){if(e&&typeof e=="object")switch(e[Kt]){case Po:case Ro:return!0}return!1}function _S(e){if(e&&typeof e=="object")switch(e[Kt]){case jl:case Po:case Tl:case Ro:return!0}return!1}var AS=e=>(xh(e)||Ch(e))&&!!e.anchor;be.ALIAS=jl;be.DOC=Sh;be.MAP=Po;be.NODE_TYPE=Kt;be.PAIR=Eh;be.SCALAR=Tl;be.SEQ=Ro;be.hasAnchor=AS;be.isAlias=ES;be.isCollection=Ch;be.isDocument=xS;be.isMap=CS;be.isNode=_S;be.isPair=PS;be.isScalar=xh;be.isSeq=RS});var $n=P($l=>{"use strict";var ge=W(),De=Symbol("break visit"),Ph=Symbol("skip children"),_t=Symbol("remove node");function _o(e,t){let r=Rh(t);ge.isDocument(e)?Ii(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):Ii(null,e,r,Object.freeze([]))}_o.BREAK=De;_o.SKIP=Ph;_o.REMOVE=_t;function Ii(e,t,r,i){let n=_h(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Ah(e,i,n),Ii(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Ii(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===De)return De;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=Ii("key",t.key,r,i);if(a===De)return De;a===_t&&(t.key=null);let o=Ii("value",t.value,r,i);if(o===De)return De;o===_t&&(t.value=null)}}return n}async function Ao(e,t){let r=Rh(t);ge.isDocument(e)?await ji(null,e.contents,r,Object.freeze([e]))===_t&&(e.contents=null):await ji(null,e,r,Object.freeze([]))}Ao.BREAK=De;Ao.SKIP=Ph;Ao.REMOVE=_t;async function ji(e,t,r,i){let n=await _h(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Ah(e,i,n),ji(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ji(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===De)return De;o===_t&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=await ji("key",t.key,r,i);if(a===De)return De;a===_t&&(t.key=null);let o=await ji("value",t.value,r,i);if(o===De)return De;o===_t&&(t.value=null)}}return n}function Rh(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 _h(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ge.isMap(t))return r.Map?.(e,t,i);if(ge.isSeq(t))return r.Seq?.(e,t,i);if(ge.isPair(t))return r.Pair?.(e,t,i);if(ge.isScalar(t))return r.Scalar?.(e,t,i);if(ge.isAlias(t))return r.Alias?.(e,t,i)}function Ah(e,t,r){let i=t[t.length-1];if(ge.isCollection(i))i.items[e]=r;else if(ge.isPair(i))e==="key"?i.key=r:i.value=r;else if(ge.isDocument(i))i.contents=r;else{let n=ge.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}$l.visit=_o;$l.visitAsync=Ao});var Ol=P(jh=>{"use strict";var Ih=W(),IS=$n(),jS={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},TS=e=>e.replace(/[!,[\]{}]/g,t=>jS[t]),On=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+TS(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&&Ih.isNode(t.contents)){let a={};IS.visit(t.contents,(o,s)=>{Ih.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
- `)}};On.defaultYaml={explicit:!1,version:"1.2"};On.defaultTags={"!!":"tag:yaml.org,2002:"};jh.Directives=On});var Io=P(Hn=>{"use strict";var Th=W(),$S=$n();function OS(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 $h(e){let t=new Set;return $S.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Oh(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function HS(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=$h(e));let o=Oh(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Th.isScalar(o.node)||Th.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}}Hn.anchorIsValid=OS;Hn.anchorNames=$h;Hn.createNodeAnchors=HS;Hn.findNewAnchor=Oh});var Hl=P(Hh=>{"use strict";function Dn(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=Dn(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=Dn(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=Dn(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=Dn(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Hh.applyReviver=Dn});var mr=P(qh=>{"use strict";var DS=W();function Dh(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Dh(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!DS.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}qh.toJS=Dh});var jo=P(Lh=>{"use strict";var qS=Hl(),Fh=W(),FS=mr(),Dl=class{constructor(t){Object.defineProperty(this,Fh.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(!Fh.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=FS.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?qS.applyReviver(a,{"":s},"",s):s}};Lh.NodeBase=Dl});var qn=P(Bh=>{"use strict";var LS=Io(),BS=$n(),Ti=W(),VS=jo(),MS=mr(),ql=class extends VS.NodeBase{constructor(t){super(Ti.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=[],BS.visit(t,{Node:(a,o)=>{(Ti.isAlias(o)||Ti.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(MS.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=To(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(LS.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 To(e,t,r){if(Ti.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Ti.isCollection(t)){let i=0;for(let n of t.items){let a=To(e,n,r);a>i&&(i=a)}return i}else if(Ti.isPair(t)){let i=To(e,t.key,r),n=To(e,t.value,r);return Math.max(i,n)}return 1}Bh.Alias=ql});var ue=P(Fl=>{"use strict";var WS=W(),zS=jo(),JS=mr(),GS=e=>!e||typeof e!="function"&&typeof e!="object",vr=class extends zS.NodeBase{constructor(t){super(WS.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:JS.toJS(this.value,t,r)}toString(){return String(this.value)}};vr.BLOCK_FOLDED="BLOCK_FOLDED";vr.BLOCK_LITERAL="BLOCK_LITERAL";vr.PLAIN="PLAIN";vr.QUOTE_DOUBLE="QUOTE_DOUBLE";vr.QUOTE_SINGLE="QUOTE_SINGLE";Fl.Scalar=vr;Fl.isScalarValue=GS});var Fn=P(Mh=>{"use strict";var US=qn(),ei=W(),Vh=ue(),KS="tag:yaml.org,2002:";function YS(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 XS(e,t,r){if(ei.isDocument(e)&&(e=e.contents),ei.isNode(e))return e;if(ei.isPair(e)){let d=r.schema[ei.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new US.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=KS+t.slice(2));let l=YS(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Vh.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[ei.MAP]:Symbol.iterator in Object(e)?o[ei.SEQ]:o[ei.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Vh.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Mh.createNode=XS});var Oo=P($o=>{"use strict";var QS=Fn(),At=W(),ZS=jo();function Ll(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 QS.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 Wh=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Bl=class extends ZS.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=>At.isNode(i)||At.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Wh(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(At.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ll(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(At.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&&At.isScalar(a)?a.value:a:At.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!At.isPair(r))return!1;let i=r.value;return i==null||t&&At.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 At.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(At.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ll(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};$o.Collection=Bl;$o.collectionFromPath=Ll;$o.isEmptyPath=Wh});var Ln=P(Ho=>{"use strict";var eE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Vl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var tE=(e,t,r)=>e.endsWith(`
7
- `)?Vl(r,t):r.includes(`
4
+ var KE=Object.create;var Nu=Object.defineProperty;var YE=Object.getOwnPropertyDescriptor;var XE=Object.getOwnPropertyNames;var QE=Object.getPrototypeOf,ZE=Object.prototype.hasOwnProperty;var os=(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 I=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ex=(e,t)=>{for(var r in t)Nu(e,r,{get:t[r],enumerable:!0})},tx=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of XE(t))!ZE.call(e,n)&&n!==r&&Nu(e,n,{get:()=>t[n],enumerable:!(i=YE(t,n))||i.enumerable});return e};var ir=(e,t,r)=>(r=e!=null?KE(QE(e)):{},tx(t||!e||!e.__esModule?Nu(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as rx}from"node:async_hooks";import{performance as ss}from"node:perf_hooks";function cs(e=0){ix+=1,nx+=e;let t=ax.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Zn(e){let t=ss.now();try{return e()}finally{cs(ss.now()-t)}}async function bu(e){let t=ss.now();try{return await e()}finally{cs(ss.now()-t)}}var ix,nx,ax,Ji=I(()=>{"use strict";ix=0,nx=0,ax=new rx});import{existsSync as ox}from"node:fs";import ea from"node:path";function Am(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function cx(e){let t=(Am(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function lx(e,t,r){let n=ea.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Am(t,"PATH")??"").split(ea.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=ea.win32.extname(e)?[e]:cx(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?ea.join(s,c):ea.resolve(r,c)))}function ls(e,t,r){return lx(e,t,r).find(i=>ox(i))??e}function ku(e){if(e.some(t=>sx.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var sx,EL,ta=I(()=>{"use strict";sx=/[&|<>()^%"!\r\n]/u,EL=["$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 ux,execFileSync as RL}from"node:child_process";import Im from"node:path";async function Er(e,t,r={}){let i=r.timeoutMs??dx,n=r.maxBufferBytes??px;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Im.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?ls(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&ku(t);let l=()=>new Promise((u,d)=>{let p=!1,f=ux(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(g,b,k)=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),g?d(new ra(e,t,k.trim(),{cause:g,timedOut:fx(g)})):u(b))}),m=g=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),f.kill("SIGKILL"),f.stdin?.destroy(),f.stdout?.destroy(),f.stderr?.destroy(),f.unref(),d(new ra(e,t,"",{timedOut:g})))},h=()=>m(!1),v=setTimeout(()=>m(!0),i);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),f.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Im.win32.basename(e))?bu(l):l()}function fx(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var dx,px,ra,Ui=I(()=>{"use strict";Ji();ta();dx=6e4,px=8*1024*1024;ra=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{createHash as wx}from"crypto";function wt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function yx(e,t){t.has(e)&&wt("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)||wt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&wt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&wt("symbol properties are not supported"),`[${e.map(i=>Su(i,t)).join(",")}]`}finally{t.delete(e)}}function Nx(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&wt("only plain objects are supported"),t.has(e)&&wt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&wt("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))&&wt("accessor properties are not supported"),`${JSON.stringify(o)}:${Su(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Su(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)||wt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?yx(e,t):Nx(e,t);case"bigint":case"function":case"symbol":case"undefined":return wt(`${typeof e} values are not supported`)}return wt("unsupported value type")}function oa(e){return Su(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 wx("sha256").update(`${e}
5
+ ${oa(t)}`).digest("hex")}var de=I(()=>{"use strict"});var z=R(Ee=>{"use strict";var Eu=Symbol.for("yaml.alias"),Hm=Symbol.for("yaml.document"),ds=Symbol.for("yaml.map"),Dm=Symbol.for("yaml.pair"),xu=Symbol.for("yaml.scalar"),ps=Symbol.for("yaml.seq"),ar=Symbol.for("yaml.node.type"),bx=e=>!!e&&typeof e=="object"&&e[ar]===Eu,kx=e=>!!e&&typeof e=="object"&&e[ar]===Hm,Sx=e=>!!e&&typeof e=="object"&&e[ar]===ds,Ex=e=>!!e&&typeof e=="object"&&e[ar]===Dm,Bm=e=>!!e&&typeof e=="object"&&e[ar]===xu,xx=e=>!!e&&typeof e=="object"&&e[ar]===ps;function Fm(e){if(e&&typeof e=="object")switch(e[ar]){case ds:case ps:return!0}return!1}function Cx(e){if(e&&typeof e=="object")switch(e[ar]){case Eu:case ds:case xu:case ps:return!0}return!1}var Rx=e=>(Bm(e)||Fm(e))&&!!e.anchor;Ee.ALIAS=Eu;Ee.DOC=Hm;Ee.MAP=ds;Ee.NODE_TYPE=ar;Ee.PAIR=Dm;Ee.SCALAR=xu;Ee.SEQ=ps;Ee.hasAnchor=Rx;Ee.isAlias=bx;Ee.isCollection=Fm;Ee.isDocument=kx;Ee.isMap=Sx;Ee.isNode=Cx;Ee.isPair=Ex;Ee.isScalar=Bm;Ee.isSeq=xx});var sa=R(Cu=>{"use strict";var ye=z(),qe=Symbol("break visit"),Lm=Symbol("skip children"),Ht=Symbol("remove node");function fs(e,t){let r=qm(t);ye.isDocument(e)?Ki(null,e.contents,r,Object.freeze([e]))===Ht&&(e.contents=null):Ki(null,e,r,Object.freeze([]))}fs.BREAK=qe;fs.SKIP=Lm;fs.REMOVE=Ht;function Ki(e,t,r,i){let n=Mm(e,t,r,i);if(ye.isNode(n)||ye.isPair(n))return Vm(e,i,n),Ki(e,n,r,i);if(typeof n!="symbol"){if(ye.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Ki(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===qe)return qe;o===Ht&&(t.items.splice(a,1),a-=1)}}}else if(ye.isPair(t)){i=Object.freeze(i.concat(t));let a=Ki("key",t.key,r,i);if(a===qe)return qe;a===Ht&&(t.key=null);let o=Ki("value",t.value,r,i);if(o===qe)return qe;o===Ht&&(t.value=null)}}return n}async function hs(e,t){let r=qm(t);ye.isDocument(e)?await Yi(null,e.contents,r,Object.freeze([e]))===Ht&&(e.contents=null):await Yi(null,e,r,Object.freeze([]))}hs.BREAK=qe;hs.SKIP=Lm;hs.REMOVE=Ht;async function Yi(e,t,r,i){let n=await Mm(e,t,r,i);if(ye.isNode(n)||ye.isPair(n))return Vm(e,i,n),Yi(e,n,r,i);if(typeof n!="symbol"){if(ye.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Yi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===qe)return qe;o===Ht&&(t.items.splice(a,1),a-=1)}}}else if(ye.isPair(t)){i=Object.freeze(i.concat(t));let a=await Yi("key",t.key,r,i);if(a===qe)return qe;a===Ht&&(t.key=null);let o=await Yi("value",t.value,r,i);if(o===qe)return qe;o===Ht&&(t.value=null)}}return n}function qm(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 Mm(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ye.isMap(t))return r.Map?.(e,t,i);if(ye.isSeq(t))return r.Seq?.(e,t,i);if(ye.isPair(t))return r.Pair?.(e,t,i);if(ye.isScalar(t))return r.Scalar?.(e,t,i);if(ye.isAlias(t))return r.Alias?.(e,t,i)}function Vm(e,t,r){let i=t[t.length-1];if(ye.isCollection(i))i.items[e]=r;else if(ye.isPair(i))e==="key"?i.key=r:i.value=r;else if(ye.isDocument(i))i.contents=r;else{let n=ye.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Cu.visit=fs;Cu.visitAsync=hs});var Ru=R(zm=>{"use strict";var Wm=z(),Px=sa(),_x={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ax=e=>e.replace(/[!,[\]{}]/g,t=>_x[t]),ca=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+Ax(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&&Wm.isNode(t.contents)){let a={};Px.visit(t.contents,(o,s)=>{Wm.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
+ `)}};ca.defaultYaml={explicit:!1,version:"1.2"};ca.defaultTags={"!!":"tag:yaml.org,2002:"};zm.Directives=ca});var ms=R(la=>{"use strict";var Gm=z(),Ix=sa();function Tx(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 Jm(e){let t=new Set;return Ix.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Um(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function jx(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Jm(e));let o=Um(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Gm.isScalar(o.node)||Gm.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}}la.anchorIsValid=Tx;la.anchorNames=Jm;la.createNodeAnchors=jx;la.findNewAnchor=Um});var Pu=R(Km=>{"use strict";function ua(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=ua(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=ua(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=ua(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=ua(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Km.applyReviver=ua});var Rr=R(Xm=>{"use strict";var $x=z();function Ym(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Ym(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!$x.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}Xm.toJS=Ym});var vs=R(Zm=>{"use strict";var Ox=Pu(),Qm=z(),Hx=Rr(),_u=class{constructor(t){Object.defineProperty(this,Qm.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(!Qm.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=Hx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Ox.applyReviver(a,{"":s},"",s):s}};Zm.NodeBase=_u});var da=R(ev=>{"use strict";var Dx=ms(),Bx=sa(),Xi=z(),Fx=vs(),Lx=Rr(),Au=class extends Fx.NodeBase{constructor(t){super(Xi.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=[],Bx.visit(t,{Node:(a,o)=>{(Xi.isAlias(o)||Xi.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Lx.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=gs(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Dx.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 gs(e,t,r){if(Xi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Xi.isCollection(t)){let i=0;for(let n of t.items){let a=gs(e,n,r);a>i&&(i=a)}return i}else if(Xi.isPair(t)){let i=gs(e,t.key,r),n=gs(e,t.value,r);return Math.max(i,n)}return 1}ev.Alias=Au});var pe=R(Iu=>{"use strict";var qx=z(),Mx=vs(),Vx=Rr(),Wx=e=>!e||typeof e!="function"&&typeof e!="object",Pr=class extends Mx.NodeBase{constructor(t){super(qx.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Vx.toJS(this.value,t,r)}toString(){return String(this.value)}};Pr.BLOCK_FOLDED="BLOCK_FOLDED";Pr.BLOCK_LITERAL="BLOCK_LITERAL";Pr.PLAIN="PLAIN";Pr.QUOTE_DOUBLE="QUOTE_DOUBLE";Pr.QUOTE_SINGLE="QUOTE_SINGLE";Iu.Scalar=Pr;Iu.isScalarValue=Wx});var pa=R(rv=>{"use strict";var zx=da(),fi=z(),tv=pe(),Gx="tag:yaml.org,2002:";function Jx(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 Ux(e,t,r){if(fi.isDocument(e)&&(e=e.contents),fi.isNode(e))return e;if(fi.isPair(e)){let d=r.schema[fi.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new zx.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Gx+t.slice(2));let l=Jx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new tv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[fi.MAP]:Symbol.iterator in Object(e)?o[fi.SEQ]:o[fi.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new tv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}rv.createNode=Ux});var ys=R(ws=>{"use strict";var Kx=pa(),Dt=z(),Yx=vs();function Tu(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 Kx.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 iv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ju=class extends Yx.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=>Dt.isNode(i)||Dt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(iv(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Dt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Tu(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(Dt.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&&Dt.isScalar(a)?a.value:a:Dt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Dt.isPair(r))return!1;let i=r.value;return i==null||t&&Dt.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 Dt.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(Dt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Tu(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};ws.Collection=ju;ws.collectionFromPath=Tu;ws.isEmptyPath=iv});var fa=R(Ns=>{"use strict";var Xx=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function $u(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Qx=(e,t,r)=>e.endsWith(`
7
+ `)?$u(r,t):r.includes(`
8
8
  `)?`
9
- `+Vl(r,t):(e.endsWith(" ")?"":" ")+r;Ho.indentComment=Vl;Ho.lineComment=tE;Ho.stringifyComment=eE});var Jh=P(Bn=>{"use strict";var rE="flow",Ml="block",Do="quoted";function iE(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let f,p,m=!1,h=-1,v=-1,g=-1;r===Ml&&(h=zh(e,h,t.length),h!==-1&&(d=h+c));for(let S;S=e[h+=1];){if(r===Do&&S==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(S===`
10
- `)r===Ml&&(h=zh(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
11
- `&&p!==" "){let N=e[h+1];N&&N!==" "&&N!==`
12
- `&&N!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===Do){for(;p===" "||p===" ";)p=S,S=e[h+=1],m=!0;let N=h>g+1?h-2:v-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,f=void 0}else m=!0}p=S}if(m&&s&&s(),l.length===0)return e;o&&o();let b=e.slice(0,l[0]);for(let S=0;S<l.length;++S){let N=l[S],x=l[S+1]||e.length;N===0?b=`
13
- ${t}${e.slice(0,x)}`:(r===Do&&u[N]&&(b+=`${e[N]}\\`),b+=`
14
- ${t}${e.slice(N+1,x)}`)}return b}function zh(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}Bn.FOLD_BLOCK=Ml;Bn.FOLD_FLOW=rE;Bn.FOLD_QUOTED=Do;Bn.foldFlowLines=iE});var Mn=P(Gh=>{"use strict";var dt=ue(),gr=Jh(),Fo=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Lo=e=>/^(%|---|\.\.\.)/m.test(e);function nE(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 Vn(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Lo(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
9
+ `+$u(r,t):(e.endsWith(" ")?"":" ")+r;Ns.indentComment=$u;Ns.lineComment=Qx;Ns.stringifyComment=Xx});var av=R(ha=>{"use strict";var Zx="flow",Ou="block",bs="quoted";function eC(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,f,m=!1,h=-1,v=-1,g=-1;r===Ou&&(h=nv(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===bs&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(k===`
10
+ `)r===Ou&&(h=nv(e,h,t.length)),d=h+t.length+c,p=void 0;else{if(k===" "&&f&&f!==" "&&f!==`
11
+ `&&f!==" "){let N=e[h+1];N&&N!==" "&&N!==`
12
+ `&&N!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===bs){for(;f===" "||f===" ";)f=k,k=e[h+=1],m=!0;let N=h>g+1?h-2:v-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,p=void 0}else m=!0}f=k}if(m&&s&&s(),l.length===0)return e;o&&o();let b=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let N=l[k],x=l[k+1]||e.length;N===0?b=`
13
+ ${t}${e.slice(0,x)}`:(r===bs&&u[N]&&(b+=`${e[N]}\\`),b+=`
14
+ ${t}${e.slice(N+1,x)}`)}return b}function nv(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}ha.FOLD_BLOCK=Ou;ha.FOLD_FLOW=Zx;ha.FOLD_QUOTED=bs;ha.foldFlowLines=eC});var va=R(ov=>{"use strict";var yt=pe(),_r=av(),Ss=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Es=e=>/^(%|---|\.\.\.)/m.test(e);function tC(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 ma(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Es(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
17
17
 
18
18
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
19
- `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:gr.foldFlowLines(o,a,gr.FOLD_QUOTED,Fo(t,!1))}function Wl(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
20
- `)||/[ \t]\n|\n[ \t]/.test(e))return Vn(e,t);let r=t.indent||(Lo(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
21
- ${r}`)+"'";return t.implicitKey?i:gr.foldFlowLines(i,r,gr.FOLD_FLOW,Fo(t,!1))}function $i(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Vn;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Wl:a&&!n?i=Vn:i=r?Wl:Vn}return i(e,t)}var zl;try{zl=new RegExp(`(^|(?<!
19
+ `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:_r.foldFlowLines(o,a,_r.FOLD_QUOTED,Ss(t,!1))}function Hu(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
20
+ `)||/[ \t]\n|\n[ \t]/.test(e))return ma(e,t);let r=t.indent||(Es(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
21
+ ${r}`)+"'";return t.implicitKey?i:_r.foldFlowLines(i,r,_r.FOLD_FLOW,Ss(t,!1))}function Qi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=ma;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Hu:a&&!n?i=ma:i=r?Hu:ma}return i(e,t)}var Du;try{Du=new RegExp(`(^|(?<!
22
22
  ))
23
23
  +(?!
24
- |$)`,"g")}catch{zl=/\n+(?!\n|$)/g}function qo({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return $i(r,i);let l=i.indent||(i.forceBlockIndent||Lo(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===dt.Scalar.BLOCK_FOLDED?!1:t===dt.Scalar.BLOCK_LITERAL?!0:!nE(r,c,l.length);if(!r)return u?`|
24
+ |$)`,"g")}catch{Du=/\n+(?!\n|$)/g}function ks({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Qi(r,i);let l=i.indent||(i.forceBlockIndent||Es(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===yt.Scalar.BLOCK_FOLDED?!1:t===yt.Scalar.BLOCK_LITERAL?!0:!tC(r,c,l.length);if(!r)return u?`|
25
25
  `:`>
26
- `;let d,f;for(f=r.length;f>0;--f){let x=r[f-1];if(x!==`
27
- `&&x!==" "&&x!==" ")break}let p=r.substring(f),m=p.indexOf(`
28
- `);m===-1?d="-":r===p||m!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
29
- `&&(p=p.slice(0,-1)),p=p.replace(zl,`$&${l}`));let h=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
26
+ `;let d,p;for(p=r.length;p>0;--p){let x=r[p-1];if(x!==`
27
+ `&&x!==" "&&x!==" ")break}let f=r.substring(p),m=f.indexOf(`
28
+ `);m===-1?d="-":r===f||m!==f.length-1?(d="+",a&&a()):d="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
29
+ `&&(f=f.slice(0,-1)),f=f.replace(Du,`$&${l}`));let h=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
30
30
  `)g=v;else break}let b=r.substring(0,g<v?g+1:v);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let x=r.replace(/\n+/g,`
31
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,k=Fo(i,!0);o!=="folded"&&t!==dt.Scalar.BLOCK_FOLDED&&(k.onOverflow=()=>{w=!0});let E=gr.foldFlowLines(`${b}${x}${p}`,l,gr.FOLD_BLOCK,k);if(!w)return`>${N}
31
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,S=Ss(i,!0);o!=="folded"&&t!==yt.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{w=!0});let E=_r.foldFlowLines(`${b}${x}${f}`,l,_r.FOLD_BLOCK,S);if(!w)return`>${N}
32
32
  ${l}${E}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
33
- ${l}${b}${r}${p}`}function aE(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
34
- `)||u&&/[[\]{},]/.test(a))return $i(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
35
- `)?$i(a,t):qo(e,t,r,i);if(!s&&!u&&n!==dt.Scalar.PLAIN&&a.includes(`
36
- `))return qo(e,t,r,i);if(Lo(a)){if(c==="")return t.forceBlockIndent=!0,qo(e,t,r,i);if(s&&c===l)return $i(a,t)}let d=a.replace(/\n+/g,`$&
37
- ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(f)||p?.some(f))return $i(a,t)}return s?d:gr.foldFlowLines(d,c,gr.FOLD_FLOW,Fo(t,!1))}function oE(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!==dt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=dt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case dt.Scalar.BLOCK_FOLDED:case dt.Scalar.BLOCK_LITERAL:return n||a?$i(o.value,t):qo(o,t,r,i);case dt.Scalar.QUOTE_DOUBLE:return Vn(o.value,t);case dt.Scalar.QUOTE_SINGLE:return Wl(o.value,t);case dt.Scalar.PLAIN:return aE(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Gh.stringifyString=oE});var Wn=P(Jl=>{"use strict";var sE=Io(),wr=W(),cE=Ln(),lE=Mn();function uE(e,t){let r=Object.assign({blockQuote:!0,commentString:cE.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 dE(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(wr.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 fE(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(wr.isScalar(e)||wr.isCollection(e))&&e.anchor;a&&sE.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 pE(e,t,r,i){if(wr.isPair(e))return e.toString(t,r,i);if(wr.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=wr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=dE(t.doc.schema.tags,a));let o=fE(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):wr.isScalar(a)?lE.stringifyString(a,t,r,i):a.toString(t,r,i);return o?wr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
- ${t.indent}${s}`:s}Jl.createStringifyContext=uE;Jl.stringify=pE});var Xh=P(Yh=>{"use strict";var Yt=W(),Uh=ue(),Kh=Wn(),zn=Ln();function hE({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=Yt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Yt.isCollection(e)||!Yt.isNode(e)&&typeof e=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||Yt.isCollection(e)||(Yt.isScalar(e)?e.type===Uh.Scalar.BLOCK_FOLDED||e.type===Uh.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,v=Kh.stringify(e,r,()=>m=!0,()=>h=!0);if(!p&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,f&&!m?v+=zn.lineComment(v,r.indent,l(f)):h&&n&&n(),v;m&&(f=null),p?(f&&(v+=zn.lineComment(v,r.indent,l(f))),v=`? ${v}
39
- ${s}:`):(v=`${v}:`,f&&(v+=zn.lineComment(v,r.indent,l(f))));let g,b,S;Yt.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,S=t.comment):(g=!1,b=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&Yt.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&Yt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,x=Kh.stringify(t,r,()=>N=!0,()=>h=!0),w=" ";if(f||g||b){if(w=g?`
40
- `:"",b){let k=l(b);w+=`
41
- ${zn.indentComment(k,r.indent)}`}x===""&&!r.inFlow?w===`
42
- `&&S&&(w=`
33
+ ${l}${b}${r}${f}`}function rC(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
34
+ `)||u&&/[[\]{},]/.test(a))return Qi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
35
+ `)?Qi(a,t):ks(e,t,r,i);if(!s&&!u&&n!==yt.Scalar.PLAIN&&a.includes(`
36
+ `))return ks(e,t,r,i);if(Es(a)){if(c==="")return t.forceBlockIndent=!0,ks(e,t,r,i);if(s&&c===l)return Qi(a,t)}let d=a.replace(/\n+/g,`$&
37
+ ${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=t.doc.schema;if(m.some(p)||f?.some(p))return Qi(a,t)}return s?d:_r.foldFlowLines(d,c,_r.FOLD_FLOW,Ss(t,!1))}function iC(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!==yt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=yt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case yt.Scalar.BLOCK_FOLDED:case yt.Scalar.BLOCK_LITERAL:return n||a?Qi(o.value,t):ks(o,t,r,i);case yt.Scalar.QUOTE_DOUBLE:return ma(o.value,t);case yt.Scalar.QUOTE_SINGLE:return Hu(o.value,t);case yt.Scalar.PLAIN:return rC(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,p=n&&u||d;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}ov.stringifyString=iC});var ga=R(Bu=>{"use strict";var nC=ms(),Ar=z(),aC=fa(),oC=va();function sC(e,t){let r=Object.assign({blockQuote:!0,commentString:aC.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 cC(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(Ar.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 lC(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Ar.isScalar(e)||Ar.isCollection(e))&&e.anchor;a&&nC.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 uC(e,t,r,i){if(Ar.isPair(e))return e.toString(t,r,i);if(Ar.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=Ar.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=cC(t.doc.schema.tags,a));let o=lC(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):Ar.isScalar(a)?oC.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Ar.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
+ ${t.indent}${s}`:s}Bu.createStringifyContext=sC;Bu.stringify=uC});var uv=R(lv=>{"use strict";var or=z(),sv=pe(),cv=ga(),wa=fa();function dC({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,p=or.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(or.isCollection(e)||!or.isNode(e)&&typeof e=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let f=!d&&(!e||p&&t==null&&!r.inFlow||or.isCollection(e)||(or.isScalar(e)?e.type===sv.Scalar.BLOCK_FOLDED||e.type===sv.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(d||!a),indent:s+c});let m=!1,h=!1,v=cv.stringify(e,r,()=>m=!0,()=>h=!0);if(!f&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!d||t==null&&f)return v=`? ${v}`,p&&!m?v+=wa.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=wa.lineComment(v,r.indent,l(p))),v=`? ${v}
39
+ ${s}:`):(v=`${v}:`,p&&(v+=wa.lineComment(v,r.indent,l(p))));let g,b,k;or.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,k=t.comment):(g=!1,b=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!f&&!p&&or.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&or.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,x=cv.stringify(t,r,()=>N=!0,()=>h=!0),w=" ";if(p||g||b){if(w=g?`
40
+ `:"",b){let S=l(b);w+=`
41
+ ${wa.indentComment(S,r.indent)}`}x===""&&!r.inFlow?w===`
42
+ `&&k&&(w=`
43
43
 
44
44
  `):w+=`
45
- ${r.indent}`}else if(!p&&Yt.isCollection(t)){let k=x[0],E=x.indexOf(`
46
- `),y=E!==-1,C=r.inFlow??t.flow??t.items.length===0;if(y||!C){let O=!1;if(y&&(k==="&"||k==="!")){let j=x.indexOf(" ");k==="&"&&j!==-1&&j<E&&x[j+1]==="!"&&(j=x.indexOf(" ",j+1)),(j===-1||E<j)&&(O=!0)}O||(w=`
45
+ ${r.indent}`}else if(!f&&or.isCollection(t)){let S=x[0],E=x.indexOf(`
46
+ `),y=E!==-1,C=r.inFlow??t.flow??t.items.length===0;if(y||!C){let O=!1;if(y&&(S==="&"||S==="!")){let T=x.indexOf(" ");S==="&"&&T!==-1&&T<E&&x[T+1]==="!"&&(T=x.indexOf(" ",T+1)),(T===-1||E<T)&&(O=!0)}O||(w=`
47
47
  ${r.indent}`)}}else(x===""||x[0]===`
48
- `)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():S&&!N?v+=zn.lineComment(v,r.indent,l(S)):h&&n&&n(),v}Yh.stringifyPair=hE});var Ul=P(Gl=>{"use strict";var Qh=xo("process");function mE(e,...t){e==="debug"&&console.log(...t)}function vE(e,t){(e==="debug"||e==="warn")&&(typeof Qh.emitWarning=="function"?Qh.emitWarning(t):console.warn(t))}Gl.debug=mE;Gl.warn=vE});var zo=P(Wo=>{"use strict";var Mo=W(),Zh=ue(),Bo="<<",Vo={identify:e=>e===Bo||typeof e=="symbol"&&e.description===Bo,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Zh.Scalar(Symbol(Bo)),{addToJSMap:em}),stringify:()=>Bo},gE=(e,t)=>(Vo.identify(t)||Mo.isScalar(t)&&(!t.type||t.type===Zh.Scalar.PLAIN)&&Vo.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Vo.tag&&r.default);function em(e,t,r){let i=tm(e,r);if(Mo.isSeq(i))for(let n of i.items)Kl(e,t,n);else if(Array.isArray(i))for(let n of i)Kl(e,t,n);else Kl(e,t,i)}function Kl(e,t,r){let i=tm(e,r);if(!Mo.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 tm(e,t){return e&&Mo.isAlias(t)?t.resolve(e.doc,e):t}Wo.addMergeToJSMap=em;Wo.isMergeKey=gE;Wo.merge=Vo});var Xl=P(nm=>{"use strict";var wE=Ul(),rm=zo(),yE=Wn(),im=W(),Yl=mr();function NE(e,t,{key:r,value:i}){if(im.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(rm.isMergeKey(e,r))rm.addMergeToJSMap(e,t,i);else{let n=Yl.toJS(r,"",e);if(t instanceof Map)t.set(n,Yl.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=bE(r,n,e),o=Yl.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 bE(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(im.isNode(e)&&r?.doc){let i=yE.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)+'..."'),wE.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)}nm.addPairToJSMap=NE});var yr=P(Ql=>{"use strict";var am=Fn(),kE=Xh(),SE=Xl(),Jo=W();function EE(e,t,r){let i=am.createNode(e,void 0,r),n=am.createNode(t,void 0,r);return new Go(i,n)}var Go=class e{constructor(t,r=null){Object.defineProperty(this,Jo.NODE_TYPE,{value:Jo.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return Jo.isNode(r)&&(r=r.clone(t)),Jo.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return SE.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?kE.stringifyPair(this,t,r,i):JSON.stringify(this)}};Ql.Pair=Go;Ql.createPair=EE});var Zl=P(sm=>{"use strict";var ti=W(),om=Wn(),Uo=Ln();function xE(e,t,r){return(t.inFlow??e.flow?PE:CE)(e,t,r)}function CE({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(ti.isNode(h))!d&&h.spaceBefore&&f.push(""),Ko(r,f,h.commentBefore,d),h.comment&&(v=h.comment);else if(ti.isPair(h)){let b=ti.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&f.push(""),Ko(r,f,b.commentBefore,d))}d=!1;let g=om.stringify(h,u,()=>v=null,()=>d=!0);v&&(g+=Uo.lineComment(g,a,l(v))),d&&v&&(d=!1),f.push(i+g)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
48
+ `)&&(w="");return v+=w+x,r.inFlow?N&&i&&i():k&&!N?v+=wa.lineComment(v,r.indent,l(k)):h&&n&&n(),v}lv.stringifyPair=dC});var Lu=R(Fu=>{"use strict";var dv=os("process");function pC(e,...t){e==="debug"&&console.log(...t)}function fC(e,t){(e==="debug"||e==="warn")&&(typeof dv.emitWarning=="function"?dv.emitWarning(t):console.warn(t))}Fu.debug=pC;Fu.warn=fC});var _s=R(Ps=>{"use strict";var Rs=z(),pv=pe(),xs="<<",Cs={identify:e=>e===xs||typeof e=="symbol"&&e.description===xs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new pv.Scalar(Symbol(xs)),{addToJSMap:fv}),stringify:()=>xs},hC=(e,t)=>(Cs.identify(t)||Rs.isScalar(t)&&(!t.type||t.type===pv.Scalar.PLAIN)&&Cs.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Cs.tag&&r.default);function fv(e,t,r){let i=hv(e,r);if(Rs.isSeq(i))for(let n of i.items)qu(e,t,n);else if(Array.isArray(i))for(let n of i)qu(e,t,n);else qu(e,t,i)}function qu(e,t,r){let i=hv(e,r);if(!Rs.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 hv(e,t){return e&&Rs.isAlias(t)?t.resolve(e.doc,e):t}Ps.addMergeToJSMap=fv;Ps.isMergeKey=hC;Ps.merge=Cs});var Vu=R(gv=>{"use strict";var mC=Lu(),mv=_s(),vC=ga(),vv=z(),Mu=Rr();function gC(e,t,{key:r,value:i}){if(vv.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(mv.isMergeKey(e,r))mv.addMergeToJSMap(e,t,i);else{let n=Mu.toJS(r,"",e);if(t instanceof Map)t.set(n,Mu.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=wC(r,n,e),o=Mu.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 wC(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(vv.isNode(e)&&r?.doc){let i=vC.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)+'..."'),mC.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)}gv.addPairToJSMap=gC});var Ir=R(Wu=>{"use strict";var wv=pa(),yC=uv(),NC=Vu(),As=z();function bC(e,t,r){let i=wv.createNode(e,void 0,r),n=wv.createNode(t,void 0,r);return new Is(i,n)}var Is=class e{constructor(t,r=null){Object.defineProperty(this,As.NODE_TYPE,{value:As.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return As.isNode(r)&&(r=r.clone(t)),As.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return NC.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?yC.stringifyPair(this,t,r,i):JSON.stringify(this)}};Wu.Pair=Is;Wu.createPair=bC});var zu=R(Nv=>{"use strict";var hi=z(),yv=ga(),Ts=fa();function kC(e,t,r){return(t.inFlow??e.flow?EC:SC)(e,t,r)}function SC({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,p=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(hi.isNode(h))!d&&h.spaceBefore&&p.push(""),js(r,p,h.commentBefore,d),h.comment&&(v=h.comment);else if(hi.isPair(h)){let b=hi.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&p.push(""),js(r,p,b.commentBefore,d))}d=!1;let g=yv.stringify(h,u,()=>v=null,()=>d=!0);v&&(g+=Ts.lineComment(g,a,l(v))),d&&v&&(d=!1),p.push(i+g)}let f;if(p.length===0)f=n.start+n.end;else{f=p[0];for(let m=1;m<p.length;++m){let h=p[m];f+=h?`
49
49
  ${c}${h}`:`
50
- `}}return e?(p+=`
51
- `+Uo.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function PE({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(ti.isNode(h))h.spaceBefore&&d.push(""),Ko(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(ti.isPair(h)){let b=ti.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),Ko(t,d,b.commentBefore,!1),b.comment&&(l=!0));let S=ti.isNode(h.value)?h.value:null;S?(S.comment&&(v=S.comment),S.commentBefore&&(l=!0)):h.value==null&&b?.comment&&(v=b.comment)}v&&(l=!0);let g=om.stringify(h,c,()=>v=null);l||(l=d.length>u||g.includes(`
52
- `)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,S)=>b+S.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=Uo.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:f,end:p}=r;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?`
50
+ `}}return e?(f+=`
51
+ `+Ts.indentComment(l(e),c),s&&s()):d&&o&&o(),f}function EC({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(hi.isNode(h))h.spaceBefore&&d.push(""),js(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(hi.isPair(h)){let b=hi.isNode(h.key)?h.key:null;b&&(b.spaceBefore&&d.push(""),js(t,d,b.commentBefore,!1),b.comment&&(l=!0));let k=hi.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&b?.comment&&(v=b.comment)}v&&(l=!0);let g=yv.stringify(h,c,()=>v=null);l||(l=d.length>u||g.includes(`
52
+ `)),m<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((b,k)=>b+k.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=Ts.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:p,end:f}=r;if(d.length===0)return p+f;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=p;for(let h of d)m+=h?`
53
53
  ${a}${n}${h}`:`
54
54
  `;return`${m}
55
- ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Ko({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Uo.indentComment(t(i),e);r.push(a.trimStart())}}sm.stringifyCollection=xE});var br=P(tu=>{"use strict";var RE=Zl(),_E=Xl(),AE=Oo(),Nr=W(),Yo=yr(),IE=ue();function Jn(e,t){let r=Nr.isScalar(t)?t.value:t;for(let i of e)if(Nr.isPair(i)&&(i.key===t||i.key===r||Nr.isScalar(i.key)&&i.key.value===r))return i}var eu=class extends AE.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Nr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Yo.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Nr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Yo.Pair(t,t?.value):i=new Yo.Pair(t.key,t.value);let n=Jn(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Nr.isScalar(n.value)&&IE.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=Jn(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Jn(this.items,t)?.value;return(!r&&Nr.isScalar(n)?n.value:n)??void 0}has(t){return!!Jn(this.items,t)}set(t,r){this.add(new Yo.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)_E.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Nr.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})),RE.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};tu.YAMLMap=eu;tu.findPair=Jn});var Oi=P(lm=>{"use strict";var jE=W(),cm=br(),TE={collection:"map",default:!0,nodeClass:cm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return jE.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>cm.YAMLMap.from(e,t,r)};lm.map=TE});var kr=P(um=>{"use strict";var $E=Fn(),OE=Zl(),HE=Oo(),Qo=W(),DE=ue(),qE=mr(),ru=class extends HE.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Qo.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Xo(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Xo(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Qo.isScalar(n)?n.value:n}has(t){let r=Xo(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Xo(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Qo.isScalar(n)&&DE.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(qE.toJS(a,String(n++),r));return i}toString(t,r,i){return t?OE.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push($E.createNode(s,void 0,i))}}return a}};function Xo(e){let t=Qo.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}um.YAMLSeq=ru});var Hi=P(fm=>{"use strict";var FE=W(),dm=kr(),LE={collection:"seq",default:!0,nodeClass:dm.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return FE.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>dm.YAMLSeq.from(e,t,r)};fm.seq=LE});var Gn=P(pm=>{"use strict";var BE=Mn(),VE={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),BE.stringifyString(e,t,r,i)}};pm.string=VE});var Zo=P(vm=>{"use strict";var hm=ue(),mm={identify:e=>e==null,createNode:()=>new hm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new hm.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&mm.test.test(e)?e:t.options.nullStr};vm.nullTag=mm});var iu=P(wm=>{"use strict";var ME=ue(),gm={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new ME.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&gm.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};wm.boolTag=gm});var Di=P(ym=>{"use strict";function WE({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}ym.stringifyNumber=WE});var au=P(es=>{"use strict";var zE=ue(),nu=Di(),JE={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:nu.stringifyNumber},GE={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():nu.stringifyNumber(e)}},UE={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 zE.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:nu.stringifyNumber};es.float=UE;es.floatExp=GE;es.floatNaN=JE});var su=P(rs=>{"use strict";var Nm=Di(),ts=e=>typeof e=="bigint"||Number.isInteger(e),ou=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function bm(e,t,r){let{value:i}=e;return ts(i)&&i>=0?r+i.toString(t):Nm.stringifyNumber(e)}var KE={identify:e=>ts(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>ou(e,2,8,r),stringify:e=>bm(e,8,"0o")},YE={identify:ts,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>ou(e,0,10,r),stringify:Nm.stringifyNumber},XE={identify:e=>ts(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>ou(e,2,16,r),stringify:e=>bm(e,16,"0x")};rs.int=YE;rs.intHex=XE;rs.intOct=KE});var Sm=P(km=>{"use strict";var QE=Oi(),ZE=Zo(),ex=Hi(),tx=Gn(),rx=iu(),cu=au(),lu=su(),ix=[QE.map,ex.seq,tx.string,ZE.nullTag,rx.boolTag,lu.intOct,lu.int,lu.intHex,cu.floatNaN,cu.floatExp,cu.float];km.schema=ix});var Cm=P(xm=>{"use strict";var nx=ue(),ax=Oi(),ox=Hi();function Em(e){return typeof e=="bigint"||Number.isInteger(e)}var is=({value:e})=>JSON.stringify(e),sx=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:is},{identify:e=>e==null,createNode:()=>new nx.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:is},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:is},{identify:Em,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})=>Em(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:is}],cx={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},lx=[ax.map,ox.seq].concat(sx,cx);xm.schema=lx});var du=P(Pm=>{"use strict";var Un=xo("buffer"),uu=ue(),ux=Mn(),dx={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Un.Buffer=="function")return Un.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 Un.Buffer=="function")s=o instanceof Un.Buffer?o.toString("base64"):Un.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=uu.Scalar.BLOCK_LITERAL),t!==uu.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===uu.Scalar.BLOCK_LITERAL?`
56
- `:" ")}return ux.stringifyString({comment:e,type:t,value:s},i,n,a)}};Pm.binary=dx});var os=P(as=>{"use strict";var ns=W(),fu=yr(),fx=ue(),px=kr();function Rm(e,t){if(ns.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!ns.isPair(i)){if(ns.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new fu.Pair(new fx.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
55
+ ${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function js({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Ts.indentComment(t(i),e);r.push(a.trimStart())}}Nv.stringifyCollection=kC});var jr=R(Ju=>{"use strict";var xC=zu(),CC=Vu(),RC=ys(),Tr=z(),$s=Ir(),PC=pe();function ya(e,t){let r=Tr.isScalar(t)?t.value:t;for(let i of e)if(Tr.isPair(i)&&(i.key===t||i.key===r||Tr.isScalar(i.key)&&i.key.value===r))return i}var Gu=class extends RC.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Tr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push($s.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Tr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new $s.Pair(t,t?.value):i=new $s.Pair(t.key,t.value);let n=ya(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Tr.isScalar(n.value)&&PC.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=ya(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ya(this.items,t)?.value;return(!r&&Tr.isScalar(n)?n.value:n)??void 0}has(t){return!!ya(this.items,t)}set(t,r){this.add(new $s.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)CC.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Tr.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})),xC.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Ju.YAMLMap=Gu;Ju.findPair=ya});var Zi=R(kv=>{"use strict";var _C=z(),bv=jr(),AC={collection:"map",default:!0,nodeClass:bv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return _C.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>bv.YAMLMap.from(e,t,r)};kv.map=AC});var $r=R(Sv=>{"use strict";var IC=pa(),TC=zu(),jC=ys(),Hs=z(),$C=pe(),OC=Rr(),Uu=class extends jC.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Hs.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Os(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Os(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Hs.isScalar(n)?n.value:n}has(t){let r=Os(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Os(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Hs.isScalar(n)&&$C.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(OC.toJS(a,String(n++),r));return i}toString(t,r,i){return t?TC.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(IC.createNode(s,void 0,i))}}return a}};function Os(e){let t=Hs.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Sv.YAMLSeq=Uu});var en=R(xv=>{"use strict";var HC=z(),Ev=$r(),DC={collection:"seq",default:!0,nodeClass:Ev.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return HC.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Ev.YAMLSeq.from(e,t,r)};xv.seq=DC});var Na=R(Cv=>{"use strict";var BC=va(),FC={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),BC.stringifyString(e,t,r,i)}};Cv.string=FC});var Ds=R(_v=>{"use strict";var Rv=pe(),Pv={identify:e=>e==null,createNode:()=>new Rv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Rv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Pv.test.test(e)?e:t.options.nullStr};_v.nullTag=Pv});var Ku=R(Iv=>{"use strict";var LC=pe(),Av={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new LC.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Av.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Iv.boolTag=Av});var tn=R(Tv=>{"use strict";function qC({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}Tv.stringifyNumber=qC});var Xu=R(Bs=>{"use strict";var MC=pe(),Yu=tn(),VC={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:Yu.stringifyNumber},WC={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():Yu.stringifyNumber(e)}},zC={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 MC.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Yu.stringifyNumber};Bs.float=zC;Bs.floatExp=WC;Bs.floatNaN=VC});var Zu=R(Ls=>{"use strict";var jv=tn(),Fs=e=>typeof e=="bigint"||Number.isInteger(e),Qu=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function $v(e,t,r){let{value:i}=e;return Fs(i)&&i>=0?r+i.toString(t):jv.stringifyNumber(e)}var GC={identify:e=>Fs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Qu(e,2,8,r),stringify:e=>$v(e,8,"0o")},JC={identify:Fs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Qu(e,0,10,r),stringify:jv.stringifyNumber},UC={identify:e=>Fs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Qu(e,2,16,r),stringify:e=>$v(e,16,"0x")};Ls.int=JC;Ls.intHex=UC;Ls.intOct=GC});var Hv=R(Ov=>{"use strict";var KC=Zi(),YC=Ds(),XC=en(),QC=Na(),ZC=Ku(),ed=Xu(),td=Zu(),eR=[KC.map,XC.seq,QC.string,YC.nullTag,ZC.boolTag,td.intOct,td.int,td.intHex,ed.floatNaN,ed.floatExp,ed.float];Ov.schema=eR});var Fv=R(Bv=>{"use strict";var tR=pe(),rR=Zi(),iR=en();function Dv(e){return typeof e=="bigint"||Number.isInteger(e)}var qs=({value:e})=>JSON.stringify(e),nR=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:qs},{identify:e=>e==null,createNode:()=>new tR.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:qs},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:qs},{identify:Dv,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})=>Dv(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:qs}],aR={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},oR=[rR.map,iR.seq].concat(nR,aR);Bv.schema=oR});var id=R(Lv=>{"use strict";var ba=os("buffer"),rd=pe(),sR=va(),cR={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ba.Buffer=="function")return ba.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 ba.Buffer=="function")s=o instanceof ba.Buffer?o.toString("base64"):ba.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=rd.Scalar.BLOCK_LITERAL),t!==rd.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,p=0;d<l;++d,p+=c)u[d]=s.substr(p,c);s=u.join(t===rd.Scalar.BLOCK_LITERAL?`
56
+ `:" ")}return sR.stringifyString({comment:e,type:t,value:s},i,n,a)}};Lv.binary=cR});var Ws=R(Vs=>{"use strict";var Ms=z(),nd=Ir(),lR=pe(),uR=$r();function qv(e,t){if(Ms.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Ms.isPair(i)){if(Ms.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new nd.Pair(new lR.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]=ns.isPair(i)?i:new fu.Pair(i)}}else t("Expected a sequence for this tag");return e}function _m(e,t,r){let{replacer:i}=r,n=new px.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(fu.createPair(s,c,r))}return n}var hx={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Rm,createNode:_m};as.createPairs=_m;as.pairs=hx;as.resolvePairs=Rm});var mu=P(hu=>{"use strict";var Am=W(),pu=mr(),Kn=br(),mx=kr(),Im=os(),ri=class e extends mx.YAMLSeq{constructor(){super(),this.add=Kn.YAMLMap.prototype.add.bind(this),this.delete=Kn.YAMLMap.prototype.delete.bind(this),this.get=Kn.YAMLMap.prototype.get.bind(this),this.has=Kn.YAMLMap.prototype.has.bind(this),this.set=Kn.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(Am.isPair(n)?(a=pu.toJS(n.key,"",r),o=pu.toJS(n.value,a,r)):a=pu.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=Im.createPairs(t,r,i),a=new this;return a.items=n.items,a}};ri.tag="tag:yaml.org,2002:omap";var vx={collection:"seq",identify:e=>e instanceof Map,nodeClass:ri,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Im.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Am.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ri,r)},createNode:(e,t,r)=>ri.from(e,t,r)};hu.YAMLOMap=ri;hu.omap=vx});var Hm=P(vu=>{"use strict";var jm=ue();function Tm({value:e,source:t},r){return t&&(e?$m:Om).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var $m={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 jm.Scalar(!0),stringify:Tm},Om={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 jm.Scalar(!1),stringify:Tm};vu.falseTag=Om;vu.trueTag=$m});var Dm=P(ss=>{"use strict";var gx=ue(),gu=Di(),wx={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:gu.stringifyNumber},yx={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():gu.stringifyNumber(e)}},Nx={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 gx.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:gu.stringifyNumber};ss.float=Nx;ss.floatExp=yx;ss.floatNaN=wx});var Fm=P(Xn=>{"use strict";var qm=Di(),Yn=e=>typeof e=="bigint"||Number.isInteger(e);function cs(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 wu(e,t,r){let{value:i}=e;if(Yn(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return qm.stringifyNumber(e)}var bx={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>cs(e,2,2,r),stringify:e=>wu(e,2,"0b")},kx={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>cs(e,1,8,r),stringify:e=>wu(e,8,"0")},Sx={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>cs(e,0,10,r),stringify:qm.stringifyNumber},Ex={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>cs(e,2,16,r),stringify:e=>wu(e,16,"0x")};Xn.int=Sx;Xn.intBin=bx;Xn.intHex=Ex;Xn.intOct=kx});var Nu=P(yu=>{"use strict";var ds=W(),ls=yr(),us=br(),ii=class e extends us.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;ds.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new ls.Pair(t.key,null):r=new ls.Pair(t,null),us.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=us.findPair(this.items,t);return!r&&ds.isPair(i)?ds.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=us.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new ls.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(ls.createPair(o,null,i));return a}};ii.tag="tag:yaml.org,2002:set";var xx={collection:"map",identify:e=>e instanceof Set,nodeClass:ii,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>ii.from(e,t,r),resolve(e,t){if(ds.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ii,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};yu.YAMLSet=ii;yu.set=xx});var ku=P(fs=>{"use strict";var Cx=Di();function bu(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 Lm(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Cx.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 Px={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})=>bu(e,r),stringify:Lm},Rx={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=>bu(e,!1),stringify:Lm},Bm={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(Bm.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=bu(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};fs.floatTime=Rx;fs.intTime=Px;fs.timestamp=Bm});var Wm=P(Mm=>{"use strict";var _x=Oi(),Ax=Zo(),Ix=Hi(),jx=Gn(),Tx=du(),Vm=Hm(),Su=Dm(),ps=Fm(),$x=zo(),Ox=mu(),Hx=os(),Dx=Nu(),Eu=ku(),qx=[_x.map,Ix.seq,jx.string,Ax.nullTag,Vm.trueTag,Vm.falseTag,ps.intBin,ps.intOct,ps.int,ps.intHex,Su.floatNaN,Su.floatExp,Su.float,Tx.binary,$x.merge,Ox.omap,Hx.pairs,Dx.set,Eu.intTime,Eu.floatTime,Eu.timestamp];Mm.schema=qx});var ev=P(Pu=>{"use strict";var Um=Oi(),Fx=Zo(),Km=Hi(),Lx=Gn(),Bx=iu(),xu=au(),Cu=su(),Vx=Sm(),Mx=Cm(),Ym=du(),Qn=zo(),Xm=mu(),Qm=os(),zm=Wm(),Zm=Nu(),hs=ku(),Jm=new Map([["core",Vx.schema],["failsafe",[Um.map,Km.seq,Lx.string]],["json",Mx.schema],["yaml11",zm.schema],["yaml-1.1",zm.schema]]),Gm={binary:Ym.binary,bool:Bx.boolTag,float:xu.float,floatExp:xu.floatExp,floatNaN:xu.floatNaN,floatTime:hs.floatTime,int:Cu.int,intHex:Cu.intHex,intOct:Cu.intOct,intTime:hs.intTime,map:Um.map,merge:Qn.merge,null:Fx.nullTag,omap:Xm.omap,pairs:Qm.pairs,seq:Km.seq,set:Zm.set,timestamp:hs.timestamp},Wx={"tag:yaml.org,2002:binary":Ym.binary,"tag:yaml.org,2002:merge":Qn.merge,"tag:yaml.org,2002:omap":Xm.omap,"tag:yaml.org,2002:pairs":Qm.pairs,"tag:yaml.org,2002:set":Zm.set,"tag:yaml.org,2002:timestamp":hs.timestamp};function zx(e,t,r){let i=Jm.get(t);if(i&&!e)return r&&!i.includes(Qn.merge)?i.concat(Qn.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Jm.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(Qn.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Gm[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Gm).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Pu.coreKnownTags=Wx;Pu.getTags=zx});var Au=P(tv=>{"use strict";var Ru=W(),Jx=Oi(),Gx=Hi(),Ux=Gn(),ms=ev(),Kx=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_u=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ms.getTags(t,"compat"):t?ms.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?ms.coreKnownTags:{},this.tags=ms.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Ru.MAP,{value:Jx.map}),Object.defineProperty(this,Ru.SCALAR,{value:Ux.string}),Object.defineProperty(this,Ru.SEQ,{value:Gx.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Kx:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};tv.Schema=_u});var iv=P(rv=>{"use strict";var Yx=W(),Iu=Wn(),Zn=Ln();function Xx(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Iu.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Zn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Yx.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Zn.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Iu.stringify(e.contents,n,()=>s=null,c);s&&(l+=Zn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Iu.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
59
- `)?(r.push("..."),r.push(Zn.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Zn.indentComment(a(c),"")))}return r.join(`
58
+ ${a.comment}`:i.comment}i=n}e.items[r]=Ms.isPair(i)?i:new nd.Pair(i)}}else t("Expected a sequence for this tag");return e}function Mv(e,t,r){let{replacer:i}=r,n=new uR.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(nd.createPair(s,c,r))}return n}var dR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qv,createNode:Mv};Vs.createPairs=Mv;Vs.pairs=dR;Vs.resolvePairs=qv});var sd=R(od=>{"use strict";var Vv=z(),ad=Rr(),ka=jr(),pR=$r(),Wv=Ws(),mi=class e extends pR.YAMLSeq{constructor(){super(),this.add=ka.YAMLMap.prototype.add.bind(this),this.delete=ka.YAMLMap.prototype.delete.bind(this),this.get=ka.YAMLMap.prototype.get.bind(this),this.has=ka.YAMLMap.prototype.has.bind(this),this.set=ka.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(Vv.isPair(n)?(a=ad.toJS(n.key,"",r),o=ad.toJS(n.value,a,r)):a=ad.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=Wv.createPairs(t,r,i),a=new this;return a.items=n.items,a}};mi.tag="tag:yaml.org,2002:omap";var fR={collection:"seq",identify:e=>e instanceof Map,nodeClass:mi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Wv.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Vv.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new mi,r)},createNode:(e,t,r)=>mi.from(e,t,r)};od.YAMLOMap=mi;od.omap=fR});var Kv=R(cd=>{"use strict";var zv=pe();function Gv({value:e,source:t},r){return t&&(e?Jv:Uv).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Jv={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 zv.Scalar(!0),stringify:Gv},Uv={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 zv.Scalar(!1),stringify:Gv};cd.falseTag=Uv;cd.trueTag=Jv});var Yv=R(zs=>{"use strict";var hR=pe(),ld=tn(),mR={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:ld.stringifyNumber},vR={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():ld.stringifyNumber(e)}},gR={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 hR.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:ld.stringifyNumber};zs.float=gR;zs.floatExp=vR;zs.floatNaN=mR});var Qv=R(Ea=>{"use strict";var Xv=tn(),Sa=e=>typeof e=="bigint"||Number.isInteger(e);function Gs(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 ud(e,t,r){let{value:i}=e;if(Sa(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Xv.stringifyNumber(e)}var wR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Gs(e,2,2,r),stringify:e=>ud(e,2,"0b")},yR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Gs(e,1,8,r),stringify:e=>ud(e,8,"0")},NR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Gs(e,0,10,r),stringify:Xv.stringifyNumber},bR={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Gs(e,2,16,r),stringify:e=>ud(e,16,"0x")};Ea.int=NR;Ea.intBin=wR;Ea.intHex=bR;Ea.intOct=yR});var pd=R(dd=>{"use strict";var Ks=z(),Js=Ir(),Us=jr(),vi=class e extends Us.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Ks.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Js.Pair(t.key,null):r=new Js.Pair(t,null),Us.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Us.findPair(this.items,t);return!r&&Ks.isPair(i)?Ks.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=Us.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Js.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(Js.createPair(o,null,i));return a}};vi.tag="tag:yaml.org,2002:set";var kR={collection:"map",identify:e=>e instanceof Set,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>vi.from(e,t,r),resolve(e,t){if(Ks.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new vi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};dd.YAMLSet=vi;dd.set=kR});var hd=R(Ys=>{"use strict";var SR=tn();function fd(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 Zv(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return SR.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 ER={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})=>fd(e,r),stringify:Zv},xR={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=>fd(e,!1),stringify:Zv},eg={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(eg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=fd(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ys.floatTime=xR;Ys.intTime=ER;Ys.timestamp=eg});var ig=R(rg=>{"use strict";var CR=Zi(),RR=Ds(),PR=en(),_R=Na(),AR=id(),tg=Kv(),md=Yv(),Xs=Qv(),IR=_s(),TR=sd(),jR=Ws(),$R=pd(),vd=hd(),OR=[CR.map,PR.seq,_R.string,RR.nullTag,tg.trueTag,tg.falseTag,Xs.intBin,Xs.intOct,Xs.int,Xs.intHex,md.floatNaN,md.floatExp,md.float,AR.binary,IR.merge,TR.omap,jR.pairs,$R.set,vd.intTime,vd.floatTime,vd.timestamp];rg.schema=OR});var fg=R(yd=>{"use strict";var sg=Zi(),HR=Ds(),cg=en(),DR=Na(),BR=Ku(),gd=Xu(),wd=Zu(),FR=Hv(),LR=Fv(),lg=id(),xa=_s(),ug=sd(),dg=Ws(),ng=ig(),pg=pd(),Qs=hd(),ag=new Map([["core",FR.schema],["failsafe",[sg.map,cg.seq,DR.string]],["json",LR.schema],["yaml11",ng.schema],["yaml-1.1",ng.schema]]),og={binary:lg.binary,bool:BR.boolTag,float:gd.float,floatExp:gd.floatExp,floatNaN:gd.floatNaN,floatTime:Qs.floatTime,int:wd.int,intHex:wd.intHex,intOct:wd.intOct,intTime:Qs.intTime,map:sg.map,merge:xa.merge,null:HR.nullTag,omap:ug.omap,pairs:dg.pairs,seq:cg.seq,set:pg.set,timestamp:Qs.timestamp},qR={"tag:yaml.org,2002:binary":lg.binary,"tag:yaml.org,2002:merge":xa.merge,"tag:yaml.org,2002:omap":ug.omap,"tag:yaml.org,2002:pairs":dg.pairs,"tag:yaml.org,2002:set":pg.set,"tag:yaml.org,2002:timestamp":Qs.timestamp};function MR(e,t,r){let i=ag.get(t);if(i&&!e)return r&&!i.includes(xa.merge)?i.concat(xa.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(ag.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(xa.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?og[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(og).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}yd.coreKnownTags=qR;yd.getTags=MR});var kd=R(hg=>{"use strict";var Nd=z(),VR=Zi(),WR=en(),zR=Na(),Zs=fg(),GR=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,bd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Zs.getTags(t,"compat"):t?Zs.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Zs.coreKnownTags:{},this.tags=Zs.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Nd.MAP,{value:VR.map}),Object.defineProperty(this,Nd.SCALAR,{value:zR.string}),Object.defineProperty(this,Nd.SEQ,{value:WR.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?GR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};hg.Schema=bd});var vg=R(mg=>{"use strict";var JR=z(),Sd=ga(),Ca=fa();function UR(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Sd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Ca.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(JR.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Ca.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Sd.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ca.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Sd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
59
+ `)?(r.push("..."),r.push(Ca.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Ca.indentComment(a(c),"")))}return r.join(`
60
60
  `)+`
61
- `}rv.stringifyDocument=Xx});var ea=P(nv=>{"use strict";var Qx=qn(),qi=Oo(),Qe=W(),Zx=yr(),eC=mr(),tC=Au(),rC=iv(),ju=Io(),iC=Hl(),nC=Fn(),Tu=Ol(),$u=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Qe.NODE_TYPE,{value:Qe.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 Tu.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,{[Qe.NODE_TYPE]:{value:Qe.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=Qe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Fi(this.contents)&&this.contents.add(t)}addIn(t,r){Fi(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=ju.anchorNames(this);t.anchor=!r||i.has(r)?ju.findNewAnchor(r||"a",i):r}return new Qx.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=b=>typeof b=="number"||b instanceof String||b 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:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=ju.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=nC.createNode(t,u,m);return s&&Qe.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 Zx.Pair(n,a)}delete(t){return Fi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return qi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Fi(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Qe.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return qi.isEmptyPath(t)?!r&&Qe.isScalar(this.contents)?this.contents.value:this.contents:Qe.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Qe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return qi.isEmptyPath(t)?this.contents!==void 0:Qe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=qi.collectionFromPath(this.schema,[t],r):Fi(this.contents)&&this.contents.set(t,r)}setIn(t,r){qi.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=qi.collectionFromPath(this.schema,Array.from(t),r):Fi(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 Tu.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 Tu.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 tC.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=eC.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?iC.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return rC.stringifyDocument(this,t)}};function Fi(e){if(Qe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}nv.Document=$u});var ia=P(ra=>{"use strict";var ta=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Ou=class extends ta{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Hu=class extends ta{constructor(t,r,i){super("YAMLWarning",t,r,i)}},aC=(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
+ `}mg.stringifyDocument=UR});var Ra=R(gg=>{"use strict";var KR=da(),rn=ys(),it=z(),YR=Ir(),XR=Rr(),QR=kd(),ZR=vg(),Ed=ms(),eP=Pu(),tP=pa(),xd=Ru(),Cd=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,it.NODE_TYPE,{value:it.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 xd.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,{[it.NODE_TYPE]:{value:it.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=it.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){nn(this.contents)&&this.contents.add(t)}addIn(t,r){nn(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Ed.anchorNames(this);t.anchor=!r||i.has(r)?Ed.findNewAnchor(r||"a",i):r}return new KR.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=b=>typeof b=="number"||b instanceof String||b 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:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:f}=Ed.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=tP.createNode(t,u,m);return s&&it.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new YR.Pair(n,a)}delete(t){return nn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return rn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):nn(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return it.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return rn.isEmptyPath(t)?!r&&it.isScalar(this.contents)?this.contents.value:this.contents:it.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return it.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return rn.isEmptyPath(t)?this.contents!==void 0:it.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=rn.collectionFromPath(this.schema,[t],r):nn(this.contents)&&this.contents.set(t,r)}setIn(t,r){rn.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=rn.collectionFromPath(this.schema,Array.from(t),r):nn(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 xd.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 xd.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 QR.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=XR.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?eP.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return ZR.stringifyDocument(this,t)}};function nn(e){if(it.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}gg.Document=Cd});var Aa=R(_a=>{"use strict";var Pa=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Rd=class extends Pa{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Pd=class extends Pa{constructor(t,r,i){super("YAMLWarning",t,r,i)}},rP=(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,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
63
63
 
64
64
  ${o}
65
65
  ${l}
66
- `}};ra.YAMLError=ta;ra.YAMLParseError=Ou;ra.YAMLWarning=Hu;ra.prettifyError=aC});var na=P(av=>{"use strict";function oC(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,m=!1,h=null,v=null,g=null,b=null,S=null,N=null,x=null;for(let E of e)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&a(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),u=!0;break;case"comment":{u||a(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";d?d+=f+y:d=y,f="",l=!1;break}case"newline":l?d?d+=E.source:(!N||r!=="seq-item-ind")&&(c=!0):f+=E.source,l=!0,p=!0,(v||g)&&(b=E),u=!0;break;case"anchor":v&&a(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&a(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=E,x??(x=E.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(E,"MULTIPLE_TAGS","A node can have at most one tag"),g=E,x??(x=E.offset),l=!1,u=!1,m=!0;break}case r:(v||g)&&a(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),N&&a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),N=E,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){S&&a(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),S=E,l=!1,u=!1;break}default:a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,u=!1}let w=e[e.length-1],k=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:N,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:g,newlineAfterProp:b,end:k,start:x??k}}av.resolveProps=oC});var vs=P(ov=>{"use strict";function Du(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(Du(t.key)||Du(t.value))return!0}return!1;default:return!0}}ov.containsNewline=Du});var qu=P(sv=>{"use strict";var sC=vs();function cC(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&sC.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}sv.flowIndentCheck=cC});var Fu=P(lv=>{"use strict";var cv=W();function lC(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||cv.isScalar(a)&&cv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}lv.mapIncludes=lC});var mv=P(hv=>{"use strict";var uv=yr(),uC=br(),dv=na(),dC=vs(),fv=qu(),fC=Fu(),pv="All mapping items must start at the same column";function pC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??uC.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:f,sep:p,value:m}=u,h=dv.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&n(c,"BAD_INDENT",pv)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
68
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||dC.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(c,"BAD_INDENT",pv);r.atKey=!0;let g=h.end,b=f?e(r,f,h,n):t(r,g,d,null,h,n);r.schema.compat&&fv.flowIndentCheck(i.indent,f,n),r.atKey=!1,fC.mapIncludes(r,s.items,b)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let S=dv.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){v&&(m?.type==="block-map"&&!S.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<S.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=m?e(r,m,S,n):t(r,c,p,null,S,n);r.schema.compat&&fv.flowIndentCheck(i.indent,m,n),c=N.range[2];let x=new uv.Pair(b,N);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(b.comment?b.comment+=`
69
- `+S.comment:b.comment=S.comment);let N=new uv.Pair(b);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}hv.resolveBlockMap=pC});var gv=P(vv=>{"use strict";var hC=kr(),mC=na(),vC=qu();function gC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??hC.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let f=mC.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,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(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(r,d,f,n):t(r,f.end,u,null,f,n);r.schema.compat&&vC.flowIndentCheck(i.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}vv.resolveBlockSeq=gC});var Li=P(wv=>{"use strict";function wC(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}wv.resolveEnd=wC});var kv=P(bv=>{"use strict";var yC=W(),NC=yr(),yv=br(),bC=kr(),kC=Li(),Nv=na(),SC=vs(),EC=Fu(),Lu="Block collections are not allowed within flow collections",Bu=e=>e&&(e.type==="block-map"||e.type==="block-seq");function xC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?yv.YAMLMap:bC.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:b,key:S,sep:N,value:x}=g,w=Nv.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:S??N?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!N&&!x){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&&(l.comment?l.comment+=`
70
- `+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&SC.containsNewline(S)&&n(S,"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 k="";e:for(let E of b)switch(E.type){case"comma":case"space":break;case"comment":k=E.source.substring(1);break e;default:break e}if(k){let E=l.items[l.items.length-1];yC.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
71
- `+k:E.comment=k,w.comment=w.comment.substring(k.length+1)}}if(!o&&!N&&!w.found){let k=x?e(r,x,w,n):t(r,w.end,N,null,w,n);l.items.push(k),d=k.range[2],Bu(x)&&n(k.range,"BLOCK_IN_FLOW",Lu)}else{r.atKey=!0;let k=w.end,E=S?e(r,S,w,n):t(r,k,b,null,w,n);Bu(S)&&n(E.range,"BLOCK_IN_FLOW",Lu),r.atKey=!1;let y=Nv.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:x,offset:E.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(y.found){if(!o&&!w.found&&r.options.strict){if(N)for(let j of N){if(j===y.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<y.found.offset-1024&&n(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(y.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=x?e(r,x,y,n):y.found?t(r,y.end,N,null,y,n):null;C?Bu(x)&&n(C.range,"BLOCK_IN_FLOW",Lu):y.comment&&(E.comment?E.comment+=`
72
- `+y.comment:E.comment=y.comment);let O=new NC.Pair(E,C);if(r.options.keepSourceTokens&&(O.srcToken=g),o){let j=l;EC.mapIncludes(r,j.items,E)&&n(k,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(O)}else{let j=new yv.YAMLMap(r.schema);j.flow=!0,j.items.push(O);let Y=(C??E).range;j.range=[E.range[0],Y[1],Y[2]],l.items.push(j)}d=C?C.range[2]:y.end}}let f=o?"}":"]",[p,...m]=i.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=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",g),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=kC.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
73
- `+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}bv.resolveFlowCollection=xC});var Ev=P(Sv=>{"use strict";var CC=W(),PC=ue(),RC=br(),_C=kr(),AC=mv(),IC=gv(),jC=kv();function Vu(e,t,r,i,n,a){let o=r.type==="block-map"?AC.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?IC.resolveBlockSeq(e,t,r,i,a):jC.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 TC(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:p}=i,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!p||p.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===RC.YAMLMap.tagName&&s==="map"||o===_C.YAMLSeq.tagName&&s==="seq")return Vu(e,t,r,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?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),Vu(e,t,r,n,o)}let l=Vu(e,t,r,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=CC.isNode(u)?u:new PC.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Sv.composeCollection=TC});var Wu=P(xv=>{"use strict";var Mu=ue();function $C(e,t,r){let i=t.offset,n=OC(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Mu.Scalar.BLOCK_FOLDED:Mu.Scalar.BLOCK_LITERAL,o=t.source?HC(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 c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,g]=o[h];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
75
- `;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===Mu.Scalar.BLOCK_LITERAL?(d+=f+v.slice(c)+g,f=`
76
- `):v.length>c||g[0]===" "?(f===" "?f=`
77
- `:!p&&f===`
78
- `&&(f=`
66
+ `}};_a.YAMLError=Pa;_a.YAMLParseError=Rd;_a.YAMLWarning=Pd;_a.prettifyError=rP});var Ia=R(wg=>{"use strict";function iP(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",f=!1,m=!1,h=null,v=null,g=null,b=null,k=null,N=null,x=null;for(let E of e)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&a(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),u=!0;break;case"comment":{u||a(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let y=E.source.substring(1)||" ";d?d+=p+y:d=y,p="",l=!1;break}case"newline":l?d?d+=E.source:(!N||r!=="seq-item-ind")&&(c=!0):p+=E.source,l=!0,f=!0,(v||g)&&(b=E),u=!0;break;case"anchor":v&&a(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&a(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=E,x??(x=E.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&a(E,"MULTIPLE_TAGS","A node can have at most one tag"),g=E,x??(x=E.offset),l=!1,u=!1,m=!0;break}case r:(v||g)&&a(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),N&&a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),N=E,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=E,l=!1,u=!1;break}default:a(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,u=!1}let w=e[e.length-1],S=w?w.offset+w.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:N,spaceBefore:c,comment:d,hasNewline:f,anchor:v,tag:g,newlineAfterProp:b,end:S,start:x??S}}wg.resolveProps=iP});var ec=R(yg=>{"use strict";function _d(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(_d(t.key)||_d(t.value))return!0}return!1;default:return!0}}yg.containsNewline=_d});var Ad=R(Ng=>{"use strict";var nP=ec();function aP(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&nP.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ng.flowIndentCheck=aP});var Id=R(kg=>{"use strict";var bg=z();function oP(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||bg.isScalar(a)&&bg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}kg.mapIncludes=oP});var Pg=R(Rg=>{"use strict";var Sg=Ir(),sP=jr(),Eg=Ia(),cP=ec(),xg=Ad(),lP=Id(),Cg="All mapping items must start at the same column";function uP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??sP.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:p,sep:f,value:m}=u,h=Eg.resolveProps(d,{indicator:"explicit-key-ind",next:p??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(p&&(p.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&n(c,"BAD_INDENT",Cg)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
68
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||cP.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Cg);r.atKey=!0;let g=h.end,b=p?e(r,p,h,n):t(r,g,d,null,h,n);r.schema.compat&&xg.flowIndentCheck(i.indent,p,n),r.atKey=!1,lP.mapIncludes(r,s.items,b)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let k=Eg.resolveProps(f??[],{indicator:"map-value-ind",next:m,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=m?e(r,m,k,n):t(r,c,f,null,k,n);r.schema.compat&&xg.flowIndentCheck(i.indent,m,n),c=N.range[2];let x=new Sg.Pair(b,N);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
69
+ `+k.comment:b.comment=k.comment);let N=new Sg.Pair(b);r.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Rg.resolveBlockMap=uP});var Ag=R(_g=>{"use strict";var dP=$r(),pP=Ia(),fP=Ad();function hP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??dP.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let p=pP.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?n(p.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(s.comment=p.comment);continue}let f=d?e(r,d,p,n):t(r,p.end,u,null,p,n);r.schema.compat&&fP.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}_g.resolveBlockSeq=hP});var an=R(Ig=>{"use strict";function mP(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Ig.resolveEnd=mP});var Og=R($g=>{"use strict";var vP=z(),gP=Ir(),Tg=jr(),wP=$r(),yP=an(),jg=Ia(),NP=ec(),bP=Id(),Td="Block collections are not allowed within flow collections",jd=e=>e&&(e.type==="block-map"||e.type==="block-seq");function kP({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Tg.YAMLMap:wP.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:b,key:k,sep:N,value:x}=g,w=jg.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??N?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!N&&!x){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&&(l.comment?l.comment+=`
70
+ `+w.comment:l.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&NP.containsNewline(k)&&n(k,"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 S="";e:for(let E of b)switch(E.type){case"comma":case"space":break;case"comment":S=E.source.substring(1);break e;default:break e}if(S){let E=l.items[l.items.length-1];vP.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
71
+ `+S:E.comment=S,w.comment=w.comment.substring(S.length+1)}}if(!o&&!N&&!w.found){let S=x?e(r,x,w,n):t(r,w.end,N,null,w,n);l.items.push(S),d=S.range[2],jd(x)&&n(S.range,"BLOCK_IN_FLOW",Td)}else{r.atKey=!0;let S=w.end,E=k?e(r,k,w,n):t(r,S,b,null,w,n);jd(k)&&n(E.range,"BLOCK_IN_FLOW",Td),r.atKey=!1;let y=jg.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:x,offset:E.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(y.found){if(!o&&!w.found&&r.options.strict){if(N)for(let T of N){if(T===y.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<y.found.offset-1024&&n(y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(y.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=x?e(r,x,y,n):y.found?t(r,y.end,N,null,y,n):null;C?jd(x)&&n(C.range,"BLOCK_IN_FLOW",Td):y.comment&&(E.comment?E.comment+=`
72
+ `+y.comment:E.comment=y.comment);let O=new gP.Pair(E,C);if(r.options.keepSourceTokens&&(O.srcToken=g),o){let T=l;bP.mapIncludes(r,T.items,E)&&n(S,"DUPLICATE_KEY","Map keys must be unique"),T.items.push(O)}else{let T=new Tg.YAMLMap(r.schema);T.flow=!0,T.items.push(O);let Q=(C??E).range;T.range=[E.range[0],Q[1],Q[2]],l.items.push(T)}d=C?C.range[2]:y.end}}let p=o?"}":"]",[f,...m]=i.end,h=d;if(f?.source===p)h=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${p}`:`${v} in block collection must be sufficiently indented and end with a ${p}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),f&&f.source.length!==1&&m.unshift(f)}if(m.length>0){let v=yP.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
73
+ `+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}$g.resolveFlowCollection=kP});var Dg=R(Hg=>{"use strict";var SP=z(),EP=pe(),xP=jr(),CP=$r(),RP=Pg(),PP=Ag(),_P=Og();function $d(e,t,r,i,n,a){let o=r.type==="block-map"?RP.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?PP.resolveBlockSeq(e,t,r,i,a):_P.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 AP(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,p=>n(a,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:f}=i,m=p&&a?p.offset>a.offset?p:a:p??a;m&&(!f||f.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===xP.YAMLMap.tagName&&s==="map"||o===CP.YAMLSeq.tagName&&s==="seq")return $d(e,t,r,n,o);let c=t.schema.tags.find(p=>p.tag===o&&p.collection===s);if(!c){let p=t.schema.knownTags[o];if(p?.collection===s)t.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?n(a,"BAD_COLLECTION_TYPE",`${p.tag} used for ${s} collection, but expects ${p.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$d(e,t,r,n,o)}let l=$d(e,t,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),t.options)??l,d=SP.isNode(u)?u:new EP.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Hg.composeCollection=AP});var Hd=R(Bg=>{"use strict";var Od=pe();function IP(e,t,r){let i=t.offset,n=TP(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Od.Scalar.BLOCK_FOLDED:Od.Scalar.BLOCK_LITERAL,o=t.source?jP(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 c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,g]=o[h];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",p="",f=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
75
+ `;for(let h=u;h<s;++h){let[v,g]=o[h];l+=v.length+g.length+1;let b=g[g.length-1]==="\r";if(b&&(g=g.slice(0,-1)),g&&v.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(b?2:1),"BAD_INDENT",N),v=""}a===Od.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+g,p=`
76
+ `):v.length>c||g[0]===" "?(p===" "?p=`
77
+ `:!f&&p===`
78
+ `&&(p=`
79
79
 
80
- `),d+=f+v.slice(c)+g,f=`
81
- `,p=!0):g===""?f===`
80
+ `),d+=p+v.slice(c)+g,p=`
81
+ `,f=!0):g===""?p===`
82
82
  `?d+=`
83
- `:f=`
84
- `:(d+=f+g,f=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
83
+ `:p=`
84
+ `:(d+=p+g,p=" ",f=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
85
85
  `+o[h][0].slice(c);d[d.length-1]!==`
86
86
  `&&(d+=`
87
87
  `);break;default:d+=`
88
- `}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function OC({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=e+f)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":r&&!l&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function HC(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}xv.resolveBlockScalar=$C});var Ju=P(Pv=>{"use strict";var zu=ue(),DC=Li();function qC(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(f,p,m)=>r(i+f,p,m);switch(n){case"scalar":s=zu.Scalar.PLAIN,c=FC(a,l);break;case"single-quoted-scalar":s=zu.Scalar.QUOTE_SINGLE,c=LC(a,l);break;case"double-quoted-scalar":s=zu.Scalar.QUOTE_DOUBLE,c=BC(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=DC.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function FC(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}`),Cv(e)}function LC(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Cv(e.slice(1,-1)).replace(/''/g,"'")}function Cv(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
+ `}let m=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function TP({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let p=1;p<n.length;++p){let f=n[p];if(!s&&(f==="-"||f==="+"))s=f;else{let m=Number(f);!o&&m?o=m:c===-1&&(c=e+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let p=1;p<t.length;++p){let f=t[p];switch(f.type){case"space":l=!0;case"newline":d+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),d+=f.source.length;break;default:{let m=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",m);let h=f.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function jP(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}Bg.resolveBlockScalar=IP});var Bd=R(Lg=>{"use strict";var Dd=pe(),$P=an();function OP(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(p,f,m)=>r(i+p,f,m);switch(n){case"scalar":s=Dd.Scalar.PLAIN,c=HP(a,l);break;case"single-quoted-scalar":s=Dd.Scalar.QUOTE_SINGLE,c=DP(a,l);break;case"double-quoted-scalar":s=Dd.Scalar.QUOTE_DOUBLE,c=BP(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=$P.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function HP(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}`),Fg(e)}function DP(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Fg(e.slice(1,-1)).replace(/''/g,"'")}function Fg(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 BC(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 BP(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}=VC(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=MC[a];if(o)r+=o;else if(a===`
94
+ `){let{fold:a,offset:o}=FP(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=LP[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+=WC(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+=qP(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 VC(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 FP(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 MC={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function WC(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}}Pv.resolveFlowScalar=qC});var Av=P(_v=>{"use strict";var ni=W(),Rv=ue(),zC=Wu(),JC=Ju();function GC(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?zC.resolveBlockScalar(e,t,i):JC.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ni.SCALAR]:c?l=UC(e.schema,n,c,r,i):t.type==="scalar"?l=KC(e,n,t,i):l=e.schema[ni.SCALAR];let u;try{let d=l.resolve(n,f=>i(r??t,"TAG_RESOLVE_FAILED",f),e.options);u=ni.isScalar(d)?d:new Rv.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",f),u=new Rv.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function UC(e,t,r,i,n){if(r==="!")return e[ni.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[ni.SCALAR])}function KC({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[ni.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[ni.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}_v.composeScalar=GC});var jv=P(Iv=>{"use strict";function YC(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}Iv.emptyScalarPosition=YC});var Ov=P(Uu=>{"use strict";var XC=qn(),QC=W(),ZC=Ev(),Tv=Av(),eP=Li(),tP=jv(),rP={composeNode:$v,composeEmptyNode:Gu};function $v(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=iP(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Tv.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=ZC.composeCollection(rP,e,t,r,i),s&&(l.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 l??(l=Gu(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!QC.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Gu(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:tP.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Tv.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function iP({options:e},{offset:t,source:r,end:i},n){let a=new XC.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=eP.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Uu.composeEmptyNode=Gu;Uu.composeNode=$v});var qv=P(Dv=>{"use strict";var nP=ea(),Hv=Ov(),aP=Li(),oP=na();function sP(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new nP.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=oP.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Hv.composeNode(l,n,u,o):Hv.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],f=aP.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[r,d,f.offset],c}Dv.composeDoc=sP});var Yu=P(Bv=>{"use strict";var cP=xo("process"),lP=Ol(),uP=ea(),aa=ia(),Fv=W(),dP=qv(),fP=Li();function oa(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 Lv(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 LP={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function qP(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}}Lg.resolveFlowScalar=OP});var Vg=R(Mg=>{"use strict";var gi=z(),qg=pe(),MP=Hd(),VP=Bd();function WP(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?MP.resolveBlockScalar(e,t,i):VP.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[gi.SCALAR]:c?l=zP(e.schema,n,c,r,i):t.type==="scalar"?l=GP(e,n,t,i):l=e.schema[gi.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??t,"TAG_RESOLVE_FAILED",p),e.options);u=gi.isScalar(d)?d:new qg.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",p),u=new qg.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function zP(e,t,r,i,n){if(r==="!")return e[gi.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[gi.SCALAR])}function GP({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[gi.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[gi.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Mg.composeScalar=WP});var zg=R(Wg=>{"use strict";function JP(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}Wg.emptyScalarPosition=JP});var Ug=R(Ld=>{"use strict";var UP=da(),KP=z(),YP=Dg(),Gg=Vg(),XP=an(),QP=zg(),ZP={composeNode:Jg,composeEmptyNode:Fd};function Jg(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=e_(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Gg.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=YP.composeCollection(ZP,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Fd(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!KP.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Fd(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:QP.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Gg.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function e_({options:e},{offset:t,source:r,end:i},n){let a=new UP.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=XP.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ld.composeEmptyNode=Fd;Ld.composeNode=Jg});var Xg=R(Yg=>{"use strict";var t_=Ra(),Kg=Ug(),r_=an(),i_=Ia();function n_(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new t_.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=i_.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Kg.composeNode(l,n,u,o):Kg.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=r_.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}Yg.composeDoc=n_});var Md=R(ew=>{"use strict";var a_=os("process"),o_=Ru(),s_=Ra(),Ta=Aa(),Qg=z(),c_=Xg(),l_=an();function ja(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 Zg(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 Ku=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=oa(r);a?this.warnings.push(new aa.YAMLWarning(o,i,n)):this.errors.push(new aa.YAMLParseError(o,i,n))},this.directives=new lP.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Lv(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(Fv.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Fv.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 qd=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=ja(r);a?this.warnings.push(new Ta.YAMLWarning(o,i,n)):this.errors.push(new Ta.YAMLParseError(o,i,n))},this.directives=new o_.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Zg(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(Qg.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Qg.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:Lv(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(cP.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=oa(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=dP.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 aa.YAMLParseError(oa(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 aa.YAMLParseError(oa(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=fP.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 aa.YAMLParseError(oa(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 uP.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}}};Bv.Composer=Ku});var Wv=P(gs=>{"use strict";var pP=Wu(),hP=Ju(),mP=ia(),Vv=Mn();function vP(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 mP.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return hP.resolveFlowScalar(e,t,i);case"block-scalar":return pP.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function gP(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Vv.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
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:Zg(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(a_.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=ja(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=c_.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 Ta.YAMLParseError(ja(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 Ta.YAMLParseError(ja(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=l_.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 Ta.YAMLParseError(ja(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 s_.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}}};ew.Composer=qd});var iw=R(tc=>{"use strict";var u_=Hd(),d_=Bd(),p_=Aa(),tw=va();function f_(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 p_.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return d_.resolveFlowScalar(e,t,i);case"block-scalar":return u_.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function h_(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=tw.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
111
111
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
112
112
  `),u=s.substring(0,l),d=s.substring(l+1)+`
113
- `,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Mv(f,c)||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:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function wP(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Vv.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":yP(e,c);break;case'"':Xu(e,c,"double-quoted-scalar");break;case"'":Xu(e,c,"single-quoted-scalar");break;default:Xu(e,c,"scalar")}}function yP(e,t){let r=t.indexOf(`
113
+ `,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return rw(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
114
+ `}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function m_(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=tw.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":v_(e,c);break;case'"':Vd(e,c,"double-quoted-scalar");break;case"'":Vd(e,c,"single-quoted-scalar");break;default:Vd(e,c,"scalar")}}function v_(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}];Mv(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
117
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Mv(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 Xu(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})}}}gs.createScalarToken=gP;gs.resolveAsScalar=vP;gs.setScalarValue=wP});var Jv=P(zv=>{"use strict";var NP=e=>"type"in e?ys(e):ws(e);function ys(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=ys(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=ws(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=ws(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=ws(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 ws({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=ys(t)),r)for(let a of r)n+=a.source;return i&&(n+=ys(i)),n}zv.stringify=NP});var Yv=P(Kv=>{"use strict";var Qu=Symbol("break visit"),bP=Symbol("skip children"),Gv=Symbol("remove item");function ai(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Uv(Object.freeze([]),e,t)}ai.BREAK=Qu;ai.SKIP=bP;ai.REMOVE=Gv;ai.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};ai.parentCollection=(e,t)=>{let r=ai.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 Uv(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=Uv(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Qu)return Qu;s===Gv&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Kv.visit=ai});var Ns=P(qe=>{"use strict";var Zu=Wv(),kP=Jv(),SP=Yv(),ed="\uFEFF",td="",rd="",id="",EP=e=>!!e&&"items"in e,xP=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function CP(e){switch(e){case ed:return"<BOM>";case td:return"<DOC>";case rd:return"<FLOW_END>";case id:return"<SCALAR>";default:return JSON.stringify(e)}}function PP(e){switch(e){case ed:return"byte-order-mark";case td:return"doc-mode";case rd:return"flow-error-end";case id: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}];rw(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
117
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function rw(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 Vd(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})}}}tc.createScalarToken=h_;tc.resolveAsScalar=f_;tc.setScalarValue=m_});var aw=R(nw=>{"use strict";var g_=e=>"type"in e?ic(e):rc(e);function ic(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=ic(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=rc(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=rc(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=rc(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 rc({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=ic(t)),r)for(let a of r)n+=a.source;return i&&(n+=ic(i)),n}nw.stringify=g_});var lw=R(cw=>{"use strict";var Wd=Symbol("break visit"),w_=Symbol("skip children"),ow=Symbol("remove item");function wi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),sw(Object.freeze([]),e,t)}wi.BREAK=Wd;wi.SKIP=w_;wi.REMOVE=ow;wi.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};wi.parentCollection=(e,t)=>{let r=wi.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 sw(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=sw(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Wd)return Wd;s===ow&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}cw.visit=wi});var nc=R(Me=>{"use strict";var zd=iw(),y_=aw(),N_=lw(),Gd="\uFEFF",Jd="",Ud="",Kd="",b_=e=>!!e&&"items"in e,k_=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function S_(e){switch(e){case Gd:return"<BOM>";case Jd:return"<DOC>";case Ud:return"<FLOW_END>";case Kd:return"<SCALAR>";default:return JSON.stringify(e)}}function E_(e){switch(e){case Gd:return"byte-order-mark";case Jd:return"doc-mode";case Ud:return"flow-error-end";case Kd: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}qe.createScalarToken=Zu.createScalarToken;qe.resolveAsScalar=Zu.resolveAsScalar;qe.setScalarValue=Zu.setScalarValue;qe.stringify=kP.stringify;qe.visit=SP.visit;qe.BOM=ed;qe.DOCUMENT=td;qe.FLOW_END=rd;qe.SCALAR=id;qe.isCollection=EP;qe.isScalar=xP;qe.prettyToken=CP;qe.tokenType=PP});var od=P(Qv=>{"use strict";var sa=Ns();function ft(e){switch(e){case void 0:case" ":case`
121
- `:case"\r":case" ":return!0;default:return!1}}var Xv=new Set("0123456789ABCDEFabcdef"),RP=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),bs=new Set(",[]{}"),_P=new Set(` ,[]{}
122
- \r `),nd=e=>!e||_P.has(e),ad=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}Me.createScalarToken=zd.createScalarToken;Me.resolveAsScalar=zd.resolveAsScalar;Me.setScalarValue=zd.setScalarValue;Me.stringify=y_.stringify;Me.visit=N_.visit;Me.BOM=Gd;Me.DOCUMENT=Jd;Me.FLOW_END=Ud;Me.SCALAR=Kd;Me.isCollection=b_;Me.isScalar=k_;Me.prettyToken=S_;Me.tokenType=E_});var Qd=R(dw=>{"use strict";var $a=nc();function Nt(e){switch(e){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var uw=new Set("0123456789ABCDEFabcdef"),x_=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ac=new Set(",[]{}"),C_=new Set(` ,[]{}
122
+ \r `),Yd=e=>!e||C_.has(e),Xd=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==="...")&&ft(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]===sa.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 sa.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==="...")&&ft(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&&!ft(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===":")&&ft(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(nd),"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("..."))&&ft(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield sa.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(nd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ft(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==="...")&&Nt(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]===$a.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 $a.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==="...")&&Nt(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&&!Nt(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===":")&&Nt(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(Yd),"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("..."))&&Nt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield $a.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(Yd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Nt(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=>ft(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=>Nt(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 sa.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(ft(a)||t&&bs.has(a))break;r=i}else if(ft(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 $a.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(Nt(a)||t&&ac.has(a))break;r=i}else if(Nt(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&&bs.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&&bs.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield sa.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(nd),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ft(i)||r&&bs.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(;!ft(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(RP.has(r))r=this.buffer[++t];else if(r==="%"&&Xv.has(this.buffer[t+1])&&Xv.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&&ac.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&&ac.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield $a.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(Yd),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Nt(i)||r&&ac.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(;!Nt(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(x_.has(r))r=this.buffer[++t];else if(r==="%"&&uw.has(this.buffer[t+1])&&uw.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)}};Qv.Lexer=ad});var cd=P(Zv=>{"use strict";var sd=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}}}};Zv.LineCounter=sd});var ud=P(ng=>{"use strict";var AP=xo("process"),eg=Ns(),IP=od();function Sr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function tg(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 ig(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 ks(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 Bi(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 Ss(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 rg(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Sr(t.start,"explicit-key-ind")&&!Sr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,ig(t.value)?t.value.end?Ss(t.value.end,t.sep):t.value.end=t.sep:Ss(t.start,t.sep),delete t.sep)}var ld=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 IP.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,AP.env.LOG_TOKENS&&console.log("|",eg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=eg.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"&&rg(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&&tg(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":{tg(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=ks(this.peek(2)),i=Bi(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)}};dw.Lexer=Xd});var ep=R(pw=>{"use strict";var Zd=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}}}};pw.LineCounter=Zd});var rp=R(gw=>{"use strict";var R_=os("process"),fw=nc(),P_=Qd();function Or(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function hw(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 vw(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 oc(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 on(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 sc(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 mw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Or(t.start,"explicit-key-ind")&&!Or(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,vw(t.value)?t.value.end?sc(t.value.end,t.sep):t.value.end=t.sep:sc(t.start,t.sep),delete t.sep)}var tp=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 P_.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,R_.env.LOG_TOKENS&&console.log("|",fw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=fw.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"&&mw(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&&hw(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":{hw(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=oc(this.peek(2)),i=on(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)){Ss(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Sr(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(ig(r.key)&&!Sr(r.sep,"newline")){let o=Bi(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Sr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Bi(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]}):Sr(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&&!Sr(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)){Ss(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||Sr(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=ks(i),a=Bi(n);rg(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)){sc(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Or(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(vw(r.key)&&!Or(r.sep,"newline")){let o=on(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Or(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=on(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]}):Or(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&&!Or(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)){sc(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||Or(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=oc(i),a=on(n);mw(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=ks(t),i=Bi(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=ks(t),i=Bi(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())}}};ng.Parser=ld});var lg=P(la=>{"use strict";var ag=Yu(),jP=ea(),ca=ia(),TP=Ul(),$P=W(),OP=cd(),og=ud();function sg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new OP.LineCounter||null,prettyErrors:t}}function HP(e,t={}){let{lineCounter:r,prettyErrors:i}=sg(t),n=new og.Parser(r?.addNewLine),a=new ag.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(ca.prettifyError(e,r)),s.warnings.forEach(ca.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function cg(e,t={}){let{lineCounter:r,prettyErrors:i}=sg(t),n=new og.Parser(r?.addNewLine),a=new ag.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 ca.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(ca.prettifyError(e,r)),o.warnings.forEach(ca.prettifyError(e,r))),o}function DP(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=cg(e,r);if(!n)return null;if(n.warnings.forEach(a=>TP.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 qP(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 $P.isDocument(e)&&!i?e.toString(r):new jP.Document(e,i,r).toString(r)}la.parse=DP;la.parseAllDocuments=HP;la.parseDocument=cg;la.stringify=qP});var It=P(G=>{"use strict";var FP=Yu(),LP=ea(),BP=Au(),dd=ia(),VP=qn(),Er=W(),MP=yr(),WP=ue(),zP=br(),JP=kr(),GP=Ns(),UP=od(),KP=cd(),YP=ud(),Es=lg(),ug=$n();G.Composer=FP.Composer;G.Document=LP.Document;G.Schema=BP.Schema;G.YAMLError=dd.YAMLError;G.YAMLParseError=dd.YAMLParseError;G.YAMLWarning=dd.YAMLWarning;G.Alias=VP.Alias;G.isAlias=Er.isAlias;G.isCollection=Er.isCollection;G.isDocument=Er.isDocument;G.isMap=Er.isMap;G.isNode=Er.isNode;G.isPair=Er.isPair;G.isScalar=Er.isScalar;G.isSeq=Er.isSeq;G.Pair=MP.Pair;G.Scalar=WP.Scalar;G.YAMLMap=zP.YAMLMap;G.YAMLSeq=JP.YAMLSeq;G.CST=GP;G.Lexer=UP.Lexer;G.LineCounter=KP.LineCounter;G.Parser=YP.Parser;G.parse=Es.parse;G.parseAllDocuments=Es.parseAllDocuments;G.parseDocument=Es.parseDocument;G.stringify=Es.stringify;G.visit=ug.visit;G.visitAsync=ug.visitAsync});import fd from"path";function ZP(e){return e.toLowerCase().startsWith(".env")}function jt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>ZP(i))?"environment-file":r.some(i=>QP.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>XP.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function pd(e,t){let r=jt(t);if(r)return r;let i=fd.resolve(e.projectRoot,...t.split("/")),n=fd.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===fd.resolve(e.configFile)?"native-runtime":null}var XP,QP,ua=I(()=>{"use strict";XP=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),QP=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function xr(e){return e!==0&&e!==0n&&e!=="0"}function Je(e,t){return xr(e.dev)&&xr(t.dev)&&xr(e.ino)&&xr(t.ino)}function z(e,t){let r=xr(e.dev)&&xr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=xr(e.ino)&&xr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var da=I(()=>{"use strict"});var Tt=I(()=>{"use strict";da()});import{createHash as eR}from"node:crypto";import{promises as pt}from"node:fs";import Ze from"node:path";import{TextDecoder as tR}from"node:util";function hd(e,t){let r=Ze.relative(e,t);return r===""||!Ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ze.sep}`)}function rR(e){let t=Ze.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})||Ze.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=jt(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 iR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function nR(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xs(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function dg(e){let t=await pt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await pt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function aR(e,t){let r=Ze.resolve(e),i=Ze.resolve(t);if(!hd(r,i))throw new Error("Native artifact path is outside its root");let n=[await dg(r)],a=r;for(let o of Ze.relative(r,i).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s=await dg(a);if(!hd(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function fg(e){for(let t of e){let r=await pt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!nR(t,r)||await pt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ee(e){let t=rR(e.ref),r=e.maxBytes===null?null:iR(e.maxBytes??md),i=Ze.resolve(e.root,...t.split("/")),n=await aR(e.root,Ze.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await pt.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 pt.realpath(i);if(!hd(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await pt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),pt.lstat(i),pt.realpath(i)]);if(await fg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!xs(a,c)||!xs(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let S=r===null?p.length:r+1-f,N=await s.read(p,0,Math.min(p.length,S),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),pt.lstat(i),pt.realpath(i)]);if(await fg(n),!h.isFile()||h.isSymbolicLink()||v!==o||!xs(c,m)||!xs(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),b;try{b=new tR("utf-8",{fatal:!0}).decode(g)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:eR("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var md,et=I(()=>{"use strict";ua();Tt();md=1024*1024});import{promises as gd}from"node:fs";async function wd(e,t){let r;for(let i=0;i<=vd.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===vd.length||!oR.has(a??""))throw n;await new Promise(o=>setTimeout(o,vd[i]))}throw r}async function yd(e,t){await wd(()=>gd.rename(e,t),`rename ${t}`)}async function Nd(e){await wd(()=>gd.unlink(e),`unlink ${e}`)}async function bd(e,t){await wd(()=>gd.link(e,t),`link ${t}`)}var oR,vd,kd=I(()=>{"use strict";oR=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),vd=[50,100,200]});import{randomUUID as sR}from"crypto";import{promises as Ae}from"fs";import ht from"path";function Cs(e,t){let r=ht.relative(e,t);return r===""||!ht.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ht.sep}`)}function cR(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ps(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function lR(e,t){return Ps(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pg(e){let t=await Ae.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 Ae.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Vi(e){for(let t of e){let r=await Ae.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!cR(t,r)||await Ae.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function uR(e,t,r){let[i,n]=await Promise.all([Ae.lstat(e),Ae.realpath(e),r?Vi(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Ps(i,t)||r&&!Cs(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function dR(e,t){let r=ht.resolve(e),i=ht.resolve(t);if(!Cs(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await pg(r)],a=ht.relative(r,i).split(ht.sep).filter(Boolean),o=r;for(let s of a){await Vi(n),o=ht.join(o,s);try{await Ae.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await pg(o);if(!Cs(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Vi(n),n}async function fR(e){let t;try{t=await Ae.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 pR(e,t,r={}){let i=ht.dirname(e),n=r.containedRoot?await dR(r.containedRoot,i):null;n||await Ae.mkdir(i,{recursive:!0});let a=ht.join(i,`.${ht.basename(e)}.${sR()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Ae.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ae.lstat(a),Ae.realpath(a)]);if(await Vi(n),!l.isFile()||l.isSymbolicLink()||!Ps(s,l)||!Cs(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(),c=await o.stat(),!Ps(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await uR(a,c,n),await r.beforeCommit?.(),n){await Vi(n);let l=await Ae.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!lR(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await bd(a,e),await Nd(a)):await yd(a,e),await fR(i)}catch(l){if(await o?.close(),!n)await Ae.rm(a,{force:!0});else try{await Vi(n),await Ae.rm(a,{force:!0})}catch{}throw l}}async function $t(e,t,r={}){await pR(e,t,r)}async function Fe(e,t,r={}){await $t(e,JSON.stringify(t,null,2)+`
144
- `,r)}var le=I(()=>{"use strict";kd();Tt()});function vR(e,t){return Sd[e][t]}function Rs(e){return hg.get(e.trim().toLocaleLowerCase("en-US"))??null}function mg(e){return Ed.get(e.trim().toLocaleLowerCase("en-US"))??null}function _s(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${vR(e,r)}
145
- `).join(`
146
- `)}var Sd,hR,mR,hg,Ed,oi=I(()=>{"use strict";Sd={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:"验证预期"}},hR={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:"结论"}},mR={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:"结论"}},hg=new Map,Ed=new Map;for(let e of Object.keys(Sd)){for(let[t,r]of Object.entries(Sd[e]))hg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(hR[e]))Ed.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(mR[e]))Ed.set(r.toLocaleLowerCase("en-US"),t)}});import Cr from"path";function bR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Cr.posix.isAbsolute(r)||Cr.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 si(e){let t=bR(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Sg(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 Ts(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||Cr.posix.isAbsolute(i)||Cr.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 Xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Eg(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 $s(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>Is)throw new Error(`${t} exceeds ${Is} 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>js)throw new Error(`${t} contains more than ${js} wildcard tokens`);return e}function Ng(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=>$s(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function fa(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 bg(e,t,r){let i=fa(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 kR(e){if(e===void 0)return{...Ie,include:[...Ie.include],exclude:[...Ie.exclude]};let t=Xt(e,"native.snapshot");return{include:Ng(t.include,"native.snapshot.include",Ie.include),exclude:Ng(t.exclude,"native.snapshot.exclude",Ie.exclude),max_files:fa(t.max_files,Ie.max_files,"native.snapshot.max_files"),max_total_bytes:fa(t.max_total_bytes,Ie.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:fa(t.max_duration_ms,Ie.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:fa(t.max_selection_records,Ie.max_selection_records,"native.snapshot.max_selection_records")}}function SR(e){if(e===void 0)return;let t=Xt(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=Xt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:si(i),toArtifactRoot:si(n),stage:a,...o?{cleanup:o}:{}}}function ER(e){if(e===void 0)return;let t=Xt(e,"native.finish");if(t.pull_request===void 0)return{};let r=Xt(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(Cr.posix.isAbsolute(i[0])||Cr.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??gR;if(!Number.isSafeInteger(n)||n<1||n>yg)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${yg}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function xR(e,t={}){let r=Xt(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??Cd;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=SR(r.pending_root_move),l=ER(r.finish);return{artifact_root:si(i),language:Eg(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:kR(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function CR(e){let t=Xt(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:Sg(t.artifact_layout),language:Eg(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function PR(e){let r=Xt(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)=>Ts(i,`hook.allow_paths[${n}]`)))]}}function RR(e){if(e===void 0)return{...As};let t=Xt(e,"memory"),r=t.learning??As.learning,i=t.retrieval??As.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 Pd(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _R(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")||Cr.posix.isAbsolute(r)||Cr.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>vg)throw new Error(`${t} exceeds ${vg} 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>gg)throw new Error(`${t} contains more than ${gg} wildcard tokens`);return r}function AR(e){let t=Pd(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)=>_R(n,`knowledge.local.include[${a}]`)))],max_file_mb:bg(t.max_file_mb,wg.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:bg(t.max_total_mb,wg.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 IR(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 jR(e){let t=Pd(e,"knowledge.remote"),r=IR(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 TR(e){if(e===void 0)return{...kg};let t=Pd(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:AR(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:jR(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 $R(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function OR(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let 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 ha(e,t={}){let r=(0,xd.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=$R(n.ambient_resume),o=n.hook===void 0?void 0:PR(n.hook),s=RR(n.memory),c=TR(n.knowledge),l=n.native===void 0?void 0:xR(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:CR(n.classic),d=OR(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Os(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...As},knowledge:{...kg},native:{artifact_root:si(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Cd,snapshot:{...Ie,include:[...Ie.include],exclude:[...Ie.exclude]}}}}var xd,pa,Is,js,vg,gg,Cd,As,wg,kg,gR,yg,wR,yR,NR,Ie,Pr=I(()=>{"use strict";xd=Gt(It(),1),pa=Number.MAX_SAFE_INTEGER,Is=1024,js=64,vg=1024,gg=64,Cd=5,As={learning:!0,retrieval:!0},wg={include:[],max_file_mb:1,max_total_mb:32},kg={provider:"local"},gR=12e4,yg=6e5,wR=[".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/**"],yR=["**/.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"],NR=[...wR,...yR].sort((e,t)=>e.localeCompare(t,"en")),Ie={include:["**/*"],exclude:[...NR],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as Hs,promises as ci}from"fs";function Rd(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function xg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ma(e){return{dev:e.dev,ino:e.ino,birthtime:Rd(e)}}function Ds(e,t){let r=ma(e),i=ma(t);return Je(r,i)?z(r,i):z(r,i)&&Rd(e)===Rd(t)&&xg(e)===xg(t)&&e.size===t.size}async function li(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 ci.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new mt("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new mt("too-large",`${i} exceeds ${t} bytes`);let o=await ci.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ma(a)});let s=process.platform==="win32"?Hs.O_RDONLY:Hs.O_RDONLY|Hs.O_NOFOLLOW|Hs.O_NONBLOCK,c;try{c=await ci.open(e,s)}catch(l){throw l.code==="ELOOP"?new mt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),ci.lstat(e,{bigint:n}),ci.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ds(a,l)||!Ds(a,u))throw new mt("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ma(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-p,{bytesRead:S}=await c.read(m,0,Math.min(m.length,b),null);if(S===0)break;if(p+=S,p>t)throw new mt("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),ci.lstat(e,{bigint:n}),ci.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Ds(a,h)||!Ds(a,v))throw new mt("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ma(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:g}}finally{await c.close()}}var mt,va=I(()=>{"use strict";da();mt=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as qs}from"fs";import Rr from"path";function HR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function _d(e,t){let r=Rr.relative(e,t);return r===""||!Rr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Rr.sep}`)}async function Cg(e,t){let r=Rr.resolve(e),i=await qs.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return qs.realpath(r)}async function Pg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Rr.join(n,r[a]);let o;try{o=await qs.lstat(n)}catch(u){if(HR(u))return{exists:!1,kind:"missing"};throw u}let s=Rr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await qs.realpath(n);if(!_d(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Mi(e,t,r){let i=Ts(t,r.label),n=Rr.resolve(e),a=await Cg(n,r.label),o=i.split("/"),s=Rr.resolve(n,...o);if(!_d(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Pg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Qt(e,t,r,i){let n=await Mi(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 Cg(n.projectRoot,i.label);return li(n.target,r,{...i,verify:async(o,s)=>{if(!_d(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Pg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var _r=I(()=>{"use strict";va();Pr()});import{createHash as DR}from"crypto";function qR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Fs(e,t={}){return(await Ls(e,t)).document}async function FR(e){try{return(await Qt(e,ga,pa,{label:ga})).bytes}catch(t){if(qR(t))return null;throw t}}function LR(e){return e?{exists:!0,sha256:DR("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ls(e,t={}){let r=await FR(e);return{document:r?ha(r.toString("utf8"),t):null,identity:LR(r)}}async function Ad(e){return(await Fs(e))?.config??null}var ga,Wi=I(()=>{"use strict";Pr();_r();ga=".comet/config.yaml"});var zi=I(()=>{"use strict";kd();da()});var qF,Id=I(()=>{"use strict";zi();Wi();_r();qF=16*1024});var $d=I(()=>{"use strict";zi();Pr();Wi();_r();Id()});import{existsSync as _g,promises as Ar}from"fs";import q from"path";import zR from"os";async function Od(e){try{return await Ar.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function GR(e){try{let t=await Ar.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Gi(e,t){let r=q.relative(e,t);return r===""||!q.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${q.sep}`)}async function Ji(e){let t=[],r=e;for(;!await Od(r);){let n=q.dirname(r);if(n===r)break;t.push(q.basename(r)),r=n}let i=await Ar.realpath(r);return q.resolve(i,...t.reverse())}async function Hd(e){try{return(await Ar.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Vs(e){let t=q.resolve(e);try{(await Ar.stat(t)).isDirectory()||(t=q.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=q.resolve(zR.homedir());for(;;){if(!(t===i&&r!==i)){let o=q.join(t,...Bs.split("/")),s=t===r||await GR(o);if(await Od(o)&&s)return t}if(await Od(q.join(t,".git")))return t;let a=q.dirname(t);if(a===t)return r;t=a}}function Ms(e){return si(e)}async function UR(e,t){let r=Ms(t),i=q.resolve(e,...r.split("/")),n=await Ar.realpath(e),a=await Ji(i);if(!Gi(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ot(e,t){let r=Ms(t),i=await UR(e,r),n=q.join(i,"comet");if(await Hd(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ji(i),Ji(n)]);if(!Gi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=q.resolve(e),c=q.join(s,".comet","runtime","native");if(await Hd(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ar.realpath(s),Ji(c)]);if(!Gi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:q.join(e,...Bs.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:q.join(n,"specs"),changesDir:q.join(n,"changes"),archiveDir:q.join(n,"archive"),runtimeDir:c,changesRuntimeDir:q.join(c,"changes"),locksDir:q.join(c,"locks"),transactionsDir:q.join(c,"transactions")}}function Dd(e){if(!JR.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vt(e,t){Dd(t);let r=q.join(e.changesRuntimeDir,t);if(!B(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ig(e,t){Dd(t);let r=q.join(e.changesDir,t,"runtime");if(!B(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function K(e,t){let r=vt(e,t);if(_g(r))return r;let i=Ig(e,t);return _g(i)?i:r}function ya(e,t){Dd(t);let r=q.join(e.changesDir,t),i=K(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:q.join(r,"brief.md"),childrenPath:q.join(r,"children.yaml"),specsDir:q.join(r,"specs"),verificationPath:q.join(r,"verification.md"),statePath:q.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:q.join(i,"state.json")}}async function Ag(e){try{let t=await Ar.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function qd(e,t){let r=vt(e,t),i=Ig(e,t),[n,a]=await Promise.all([Ag(r),Ag(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Ir(e,t){if(!t.startsWith("runtime/")||q.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=q.resolve(e,...t.slice(8).split("/"));if(!B(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function we(e,t){let r=q.resolve(t);if(B(e.runtimeDir,r))return e.runtimeDir;if(B(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function B(e,t){return Gi(q.resolve(e),q.resolve(t))}async function V(e,t){let r=q.resolve(e),i=q.resolve(t);if(!Gi(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Hd(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ji(r),Ji(i)]);if(!Gi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Bs,JR,U=I(()=>{"use strict";Pr();Bs=".comet/config.yaml",JR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function YR(e="docs",t="en"){return Os(e,t)}async function ke(e){let t=(await Fs(e))?.config??null;return t?.native?t:null}async function zs(e){let t=await ke(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 jg(e){let t=await Vs(e.startPath),r=await ke(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Bs} 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?Ms(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??YR(i??"docs"),a=await Ot(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Fd,Ws,Ge=I(()=>{"use strict";Pr();Wi();$d();le();U();Fd=Ie,Ws=$s});import{existsSync as XR}from"node:fs";import Na from"node:path";function Tg(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function ZR(e){let t=(Tg(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function e_(e,t,r){let n=Na.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Tg(t,"PATH")??"").split(Na.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Na.win32.extname(e)?[e]:ZR(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Na.join(s,c):Na.resolve(r,c)))}function Ld(e,t,r){return e_(e,t,r).find(i=>XR(i))??e}function Bd(e){if(e.some(t=>QR.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var QR,sL,Js=I(()=>{"use strict";QR=/[&|<>()^%"!\r\n]/u,sL=["$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 t_}from"node:child_process";import $g from"node:path";function n_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Ui(e,t,r={}){let i=r.timeoutMs??r_,n=r.maxBufferBytes??i_;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=$g.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Ld(e,o,a):e,c=$g.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Bd(t);try{return t_(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"&&l})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Vd(e,t,d,{cause:u,timedOut:n_(u)})}}var r_,i_,Vd,Gs=I(()=>{"use strict";Js();r_=6e4,i_=8*1024*1024,Vd=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 Og}from"node:fs";import Hg from"node:path";function s_(e){let t=Wd.get(e);if(!t)return;let r=t.value===null?o_:a_;if(Date.now()-t.at>r){Wd.delete(e);return}return t.value}async function ba(e){if(e===process.pid&&Md!==null)return Md;let t=s_(e);if(t!==void 0)return t;let r=await c_(e);return e===process.pid&&r!==null&&(Md=r),e!==process.pid&&Wd.set(e,{value:r,at:Date.now()}),r}async function c_(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Og.readFile(`/proc/${e}/stat`,"utf8"),Og.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 u_(e);if(process.platform==="darwin"){let t=Ui("/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 l_(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function u_(e){try{let n=Ui(Hg.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=Hg.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=Ui(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return l_(i)}function Us(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function zd(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 ba(e);return r===t?"alive":r===null||Us(r)!==Us(t)&&Dg.has(Us(r))&&Dg.has(Us(t))?"unknown":"dead"}var Md,a_,o_,Wd,Dg,Ks=I(()=>{"use strict";Gs();Md=null,a_=6e4,o_=1e4,Wd=new Map;Dg=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as d_}from"async_hooks";import{randomUUID as Lg}from"crypto";import{promises as tt}from"fs";import Bg from"os";import de from"path";function h_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function m_(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 Vg(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 Xs(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Je(r,i)?z(r,i):z(r,i)&&e.size===t.size}function Qs(e,t){return Xs(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function v_(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&&Qs(e.identity,t.identity)}async function gt(e){let t,r;try{let i=await li(e,qg,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof mt?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${qg} 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:m_(JSON.parse(t.toString("utf8")),e),identity:Vg(r)}}async function g_(e){return(await gt(e))?.owner??null}async function Gd(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Bg.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await zd(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function w_(e,t){try{await tt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await tt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Zs(e,t){let r=await gt(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Qs(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await tt.mkdir(t,{recursive:!0});let i=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${Lg()}.removed`);try{await tt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await gt(i);if(!n||n.owner.id!==e.owner.id||!Xs(n.identity,e.identity))throw await w_(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await tt.rm(i,{force:!0}),"removed"}async function Mg(e){let t=await ba(process.pid);return{id:Lg(),pid:process.pid,hostname:Bg.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Wg(e,t){let r;try{r=await tt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await g_(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)+`
147
- `,"utf8"),await r.sync(),i=Vg(await r.stat({bigint:!0}))}finally{await r.close()}let n=await gt(e);if(!i||!n||n.owner.id!==t.id||!Xs(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function y_(e,t){let r=await V(e.runtimeDir,e.locksDir);await tt.mkdir(r,{recursive:!0});let i=await V(e.runtimeDir,de.join(r,Jd));await tt.mkdir(i,{recursive:!0});let n=await Mg(t),a=de.join(i,`.${n.id}.tmp`),o=de.join(i,`${n.id}.claim`);try{let s=await Wg(a,n);await tt.rename(a,o);let c=await gt(o);if(!c||!Xs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await tt.rm(a,{force:!0})}}async function N_(e){let t=de.dirname(e.file),r=!1,i=de.basename(e.file);for(let n of await tt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=de.join(t,n.name);if(de.resolve(a)!==de.resolve(e.file))try{let o=await gt(a),s=await Gd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Zs(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function zg(e){let t=await gt(e.file);if(t){if(t.owner.id!==e.owner.id||!Qs(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Zs(t,de.dirname(e.file))}}async function b_(e,t){let r=Date.now()+f_;for(;;){let i=await y_(e,t);if(!await N_(i))return i;if(await zg(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 k_(e){let t=Ys.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ys.set(e,n),await t,()=>{r(),Ys.get(e)===n&&Ys.delete(e)}}async function Ud(e,t,r){let i=de.resolve(e.locksDir),n=Fg.getStore();if(n?.has(i))return r();let a=await k_(i);try{let o=await b_(e,t),s=new Map(n??[]);return s.set(i,o),await Fg.run(s,async()=>{try{return await r()}finally{await zg(o)}})}finally{a()}}async function ec(e,t,r){return Ud(e,`acquire ${t}`,async()=>{let i=await V(e.runtimeDir,e.locksDir);await tt.mkdir(i,{recursive:!0});let n=await V(e.runtimeDir,de.join(i,h_(t))),a=await Mg(r),o=await Wg(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function tc(e){await gt(e.file)&&await Ud({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${de.basename(e.file)}`,async()=>{let t=await gt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Qs(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=de.join(e.locksDir,Jd);await Zs(t,r)})}function S_(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 Jg(e){return Gd(await gt(e))}async function Gg(e,t,r,i={}){return Ud(e,`take over ${de.basename(t)}`,async()=>{let n=await V(e.runtimeDir,e.locksDir),a=await V(e.runtimeDir,t);if(de.resolve(de.dirname(a))!==de.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await gt(a),s=await Gd(o);if(s.status==="missing")return{status:"missing"};if(r&&!v_(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&S_(o?.owner??null)>=p_;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=de.join(n,Jd);return await Zs(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var qg,Jd,f_,p_,Fg,Ys,ka=I(()=>{"use strict";va();Ks();U();Tt();qg=16*1024,Jd=".coordinator",f_=5e3,p_=900*1e3,Fg=new d_,Ys=new Map});import{createHash as E_}from"node:crypto";function Xg(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=oc(t),i=on(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=oc(t),i=on(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())}}};gw.Parser=tp});var kw=R(Ha=>{"use strict";var ww=Md(),__=Ra(),Oa=Aa(),A_=Lu(),I_=z(),T_=ep(),yw=rp();function Nw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new T_.LineCounter||null,prettyErrors:t}}function j_(e,t={}){let{lineCounter:r,prettyErrors:i}=Nw(t),n=new yw.Parser(r?.addNewLine),a=new ww.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Oa.prettifyError(e,r)),s.warnings.forEach(Oa.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function bw(e,t={}){let{lineCounter:r,prettyErrors:i}=Nw(t),n=new yw.Parser(r?.addNewLine),a=new ww.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 Oa.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Oa.prettifyError(e,r)),o.warnings.forEach(Oa.prettifyError(e,r))),o}function $_(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=bw(e,r);if(!n)return null;if(n.warnings.forEach(a=>A_.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 O_(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 I_.isDocument(e)&&!i?e.toString(r):new __.Document(e,i,r).toString(r)}Ha.parse=$_;Ha.parseAllDocuments=j_;Ha.parseDocument=bw;Ha.stringify=O_});var Bt=R(U=>{"use strict";var H_=Md(),D_=Ra(),B_=kd(),ip=Aa(),F_=da(),Hr=z(),L_=Ir(),q_=pe(),M_=jr(),V_=$r(),W_=nc(),z_=Qd(),G_=ep(),J_=rp(),cc=kw(),Sw=sa();U.Composer=H_.Composer;U.Document=D_.Document;U.Schema=B_.Schema;U.YAMLError=ip.YAMLError;U.YAMLParseError=ip.YAMLParseError;U.YAMLWarning=ip.YAMLWarning;U.Alias=F_.Alias;U.isAlias=Hr.isAlias;U.isCollection=Hr.isCollection;U.isDocument=Hr.isDocument;U.isMap=Hr.isMap;U.isNode=Hr.isNode;U.isPair=Hr.isPair;U.isScalar=Hr.isScalar;U.isSeq=Hr.isSeq;U.Pair=L_.Pair;U.Scalar=q_.Scalar;U.YAMLMap=M_.YAMLMap;U.YAMLSeq=V_.YAMLSeq;U.CST=W_;U.Lexer=z_.Lexer;U.LineCounter=G_.LineCounter;U.Parser=J_.Parser;U.parse=cc.parse;U.parseAllDocuments=cc.parseAllDocuments;U.parseDocument=cc.parseDocument;U.stringify=cc.stringify;U.visit=Sw.visit;U.visitAsync=Sw.visitAsync});import np from"path";function Y_(e){return e.toLowerCase().startsWith(".env")}function Ft(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Y_(i))?"environment-file":r.some(i=>K_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>U_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function ap(e,t){let r=Ft(t);if(r)return r;let i=np.resolve(e.projectRoot,...t.split("/")),n=np.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===np.resolve(e.configFile)?"native-runtime":null}var U_,K_,Da=I(()=>{"use strict";U_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),K_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Dr(e){return e!==0&&e!==0n&&e!=="0"}function Xe(e,t){return Dr(e.dev)&&Dr(t.dev)&&Dr(e.ino)&&Dr(t.ino)}function G(e,t){let r=Dr(e.dev)&&Dr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Dr(e.ino)&&Dr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Ba=I(()=>{"use strict"});var Lt=I(()=>{"use strict";Ba()});import{createHash as X_}from"node:crypto";import{promises as bt}from"node:fs";import nt from"node:path";import{TextDecoder as Q_}from"node:util";function op(e,t){let r=nt.relative(e,t);return r===""||!nt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${nt.sep}`)}function Z_(e){let t=nt.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})||nt.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=Ft(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 eA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function tA(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ew(e){let t=await bt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await bt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function rA(e,t){let r=nt.resolve(e),i=nt.resolve(t);if(!op(r,i))throw new Error("Native artifact path is outside its root");let n=[await Ew(r)],a=r;for(let o of nt.relative(r,i).split(nt.sep).filter(Boolean)){a=nt.join(a,o);let s=await Ew(a);if(!op(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function xw(e){for(let t of e){let r=await bt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tA(t,r)||await bt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=Z_(e.ref),r=e.maxBytes===null?null:eA(e.maxBytes??sp),i=nt.resolve(e.root,...t.split("/")),n=await rA(e.root,nt.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await bt.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 bt.realpath(i);if(!op(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await bt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await xw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!lc(a,c)||!lc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,N=await s.read(f,0,Math.min(f.length,k),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(f.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),bt.lstat(i),bt.realpath(i)]);if(await xw(n),!h.isFile()||h.isSymbolicLink()||v!==o||!lc(c,m)||!lc(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,p),b;try{b=new Q_("utf-8",{fatal:!0}).decode(g)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:p,hash:e.includeHash===!1?null:X_("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var sp,at=I(()=>{"use strict";Da();Lt();sp=1024*1024});import{promises as lp}from"node:fs";async function up(e,t){let r;for(let i=0;i<=cp.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===cp.length||!iA.has(a??""))throw n;await new Promise(o=>setTimeout(o,cp[i]))}throw r}async function dp(e,t){await up(()=>lp.rename(e,t),`rename ${t}`)}async function pp(e){await up(()=>lp.unlink(e),`unlink ${e}`)}async function fp(e,t){await up(()=>lp.link(e,t),`link ${t}`)}var iA,cp,hp=I(()=>{"use strict";iA=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),cp=[50,100,200]});import{randomUUID as nA}from"crypto";import{promises as $e}from"fs";import kt from"path";function uc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function aA(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dc(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function oA(e,t){return dc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Cw(e){let t=await $e.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 $e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sn(e){for(let t of e){let r=await $e.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!aA(t,r)||await $e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function sA(e,t,r){let[i,n]=await Promise.all([$e.lstat(e),$e.realpath(e),r?sn(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!dc(i,t)||r&&!uc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function cA(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!uc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Cw(r)],a=kt.relative(r,i).split(kt.sep).filter(Boolean),o=r;for(let s of a){await sn(n),o=kt.join(o,s);try{await $e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Cw(o);if(!uc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await sn(n),n}async function lA(e){let t;try{t=await $e.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 uA(e,t,r={}){let i=kt.dirname(e),n=r.containedRoot?await cA(r.containedRoot,i):null;n||await $e.mkdir(i,{recursive:!0});let a=kt.join(i,`.${kt.basename(e)}.${nA()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await $e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([$e.lstat(a),$e.realpath(a)]);if(await sn(n),!l.isFile()||l.isSymbolicLink()||!dc(s,l)||!uc(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(),c=await o.stat(),!dc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await sA(a,c,n),await r.beforeCommit?.(),n){await sn(n);let l=await $e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!oA(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await fp(a,e),await pp(a)):await dp(a,e),await lA(i)}catch(l){if(await o?.close(),!n)await $e.rm(a,{force:!0});else try{await sn(n),await $e.rm(a,{force:!0})}catch{}throw l}}async function qt(e,t,r={}){await uA(e,t,r)}async function Oe(e,t,r={}){await qt(e,JSON.stringify(t,null,2)+`
144
+ `,r)}var oe=I(()=>{"use strict";hp();Lt()});function Rw(e,t){return mp[e][t]}function pc(e){return Pw.get(e.trim().toLocaleLowerCase("en-US"))??null}function Iw(e){return vp.get(e.trim().toLocaleLowerCase("en-US"))??null}function fA(e){return yi[e].section}function hA(e,t){return yi[e].subsections[t]}function Tw(e){return`${yi.en.subsections[e]}/${yi["zh-CN"].subsections[e]}`}function jw(e){return _w.has(e.trim().toLocaleLowerCase("en-US"))}function $w(e){return Aw.get(e.trim().toLocaleLowerCase("en-US"))??null}function fc(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>{if(i!=="scope")return`# ${Rw(e,i)}
145
+ `;let n=[`# ${Rw(e,i)}
146
+ `];n.push(`## ${fA(e)}
147
+ `);for(let a of gp)n.push(`### ${hA(e,a)}
148
+ `);return n.join(`
149
+ `)}).join(`
150
+ `)}var gp,mp,dA,pA,Pw,vp,_w,Aw,yi,Ni=I(()=>{"use strict";gp=["created","modified","deleted","notCreated"],mp={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:"验证预期"}},dA={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:"结论"}},pA={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:"结论"}},Pw=new Map,vp=new Map,_w=new Set,Aw=new Map,yi={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(mp)){for(let[t,r]of Object.entries(mp[e]))Pw.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(dA[e]))vp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(pA[e]))vp.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(yi)){_w.add(yi[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(yi[e].subsections))Aw.set(r.toLocaleLowerCase("en-US"),t)}});import Br from"path";function yA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Br.posix.isAbsolute(r)||Br.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 bi(e){let t=yA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Mw(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 gc(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||Br.posix.isAbsolute(i)||Br.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 sr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Vw(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 wc(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>mc)throw new Error(`${t} exceeds ${mc} 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>vc)throw new Error(`${t} contains more than ${vc} wildcard tokens`);return e}function Fw(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=>wc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Fa(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 Lw(e,t,r){let i=Fa(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 NA(e){if(e===void 0)return{...He,include:[...He.include],exclude:[...He.exclude]};let t=sr(e,"native.snapshot");return{include:Fw(t.include,"native.snapshot.include",He.include),exclude:Fw(t.exclude,"native.snapshot.exclude",He.exclude),max_files:Fa(t.max_files,He.max_files,"native.snapshot.max_files"),max_total_bytes:Fa(t.max_total_bytes,He.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Fa(t.max_duration_ms,He.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Fa(t.max_selection_records,He.max_selection_records,"native.snapshot.max_selection_records")}}function bA(e){if(e===void 0)return;let t=sr(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=sr(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:bi(i),toArtifactRoot:bi(n),stage:a,...o?{cleanup:o}:{}}}function kA(e){if(e===void 0)return;let t=sr(e,"native.finish");if(t.pull_request===void 0)return{};let r=sr(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(Br.posix.isAbsolute(i[0])||Br.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??mA;if(!Number.isSafeInteger(n)||n<1||n>Bw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Bw}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function SA(e,t={}){let r=sr(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??yp;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=bA(r.pending_root_move),l=kA(r.finish);return{artifact_root:bi(i),language:Vw(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:NA(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function EA(e){let t=sr(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:Mw(t.artifact_layout),language:Vw(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function xA(e){let r=sr(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)=>gc(i,`hook.allow_paths[${n}]`)))]}}function CA(e){if(e===void 0)return{...hc};let t=sr(e,"memory"),r=t.learning??hc.learning,i=t.retrieval??hc.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 Np(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function RA(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")||Br.posix.isAbsolute(r)||Br.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>Ow)throw new Error(`${t} exceeds ${Ow} 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>Hw)throw new Error(`${t} contains more than ${Hw} wildcard tokens`);return r}function PA(e){let t=Np(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)=>RA(n,`knowledge.local.include[${a}]`)))],max_file_mb:Lw(t.max_file_mb,Dw.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Lw(t.max_total_mb,Dw.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 _A(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 AA(e){let t=Np(e,"knowledge.remote"),r=_A(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 IA(e){if(e===void 0)return{...qw};let t=Np(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:PA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:AA(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 TA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function jA(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(p=>p!=="native"&&p!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(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 qa(e,t={}){let r=(0,wp.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=TA(n.ambient_resume),o=n.hook===void 0?void 0:xA(n.hook),s=CA(n.memory),c=IA(n.knowledge),l=n.native===void 0?void 0:SA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:EA(n.classic),d=jA(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function yc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...hc},knowledge:{...qw},native:{artifact_root:bi(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:yp,snapshot:{...He,include:[...He.include],exclude:[...He.exclude]}}}}var wp,La,mc,vc,Ow,Hw,yp,hc,Dw,qw,mA,Bw,vA,gA,wA,He,Fr=I(()=>{"use strict";wp=ir(Bt(),1),La=Number.MAX_SAFE_INTEGER,mc=1024,vc=64,Ow=1024,Hw=64,yp=5,hc={learning:!0,retrieval:!0},Dw={include:[],max_file_mb:1,max_total_mb:32},qw={provider:"local"},mA=12e4,Bw=6e5,vA=[".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/**"],gA=["**/.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"],wA=[...vA,...gA].sort((e,t)=>e.localeCompare(t,"en")),He={include:["**/*"],exclude:[...wA],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as Nc,promises as ki}from"fs";function bp(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ww(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ma(e){return{dev:e.dev,ino:e.ino,birthtime:bp(e)}}function bc(e,t){let r=Ma(e),i=Ma(t);return Xe(r,i)?G(r,i):G(r,i)&&bp(e)===bp(t)&&Ww(e)===Ww(t)&&e.size===t.size}async function Si(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 ki.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new St("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new St("too-large",`${i} exceeds ${t} bytes`);let o=await ki.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ma(a)});let s=process.platform==="win32"?Nc.O_RDONLY:Nc.O_RDONLY|Nc.O_NOFOLLOW|Nc.O_NONBLOCK,c;try{c=await ki.open(e,s)}catch(l){throw l.code==="ELOOP"?new St("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),ki.lstat(e,{bigint:n}),ki.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!bc(a,l)||!bc(a,u))throw new St("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Ma(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,b),null);if(k===0)break;if(f+=k,f>t)throw new St("too-large",`${i} exceeds ${t} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat({bigint:n}),ki.lstat(e,{bigint:n}),ki.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!bc(a,h)||!bc(a,v))throw new St("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Ma(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:g}}finally{await c.close()}}var St,Va=I(()=>{"use strict";Ba();St=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as kc}from"fs";import Lr from"path";function $A(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function kp(e,t){let r=Lr.relative(e,t);return r===""||!Lr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Lr.sep}`)}async function zw(e,t){let r=Lr.resolve(e),i=await kc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return kc.realpath(r)}async function Gw(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Lr.join(n,r[a]);let o;try{o=await kc.lstat(n)}catch(u){if($A(u))return{exists:!1,kind:"missing"};throw u}let s=Lr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await kc.realpath(n);if(!kp(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function cn(e,t,r){let i=gc(t,r.label),n=Lr.resolve(e),a=await zw(n,r.label),o=i.split("/"),s=Lr.resolve(n,...o);if(!kp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Gw(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Mt(e,t,r,i){let n=await cn(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 zw(n.projectRoot,i.label);return Si(n.target,r,{...i,verify:async(o,s)=>{if(!kp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Gw(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var cr=I(()=>{"use strict";Va();Fr()});import{createHash as OA}from"crypto";function HA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Sc(e,t={}){return(await Ec(e,t)).document}async function DA(e){try{return(await Mt(e,Wa,La,{label:Wa})).bytes}catch(t){if(HA(t))return null;throw t}}function BA(e){return e?{exists:!0,sha256:OA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Ec(e,t={}){let r=await DA(e);return{document:r?qa(r.toString("utf8"),t):null,identity:BA(r)}}async function Sp(e){return(await Sc(e))?.config??null}var Wa,ln=I(()=>{"use strict";Fr();cr();Wa=".comet/config.yaml"});var un=I(()=>{"use strict";hp();Ba()});var X1,Ep=I(()=>{"use strict";un();ln();cr();X1=16*1024});var Rp=I(()=>{"use strict";un();Fr();ln();cr();Ep()});import{existsSync as Uw,promises as qr}from"fs";import B from"path";import VA from"os";async function Pp(e){try{return await qr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function zA(e){try{let t=await qr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function pn(e,t){let r=B.relative(e,t);return r===""||!B.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${B.sep}`)}async function dn(e){let t=[],r=e;for(;!await Pp(r);){let n=B.dirname(r);if(n===r)break;t.push(B.basename(r)),r=n}let i=await qr.realpath(r);return B.resolve(i,...t.reverse())}async function _p(e){try{return(await qr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Cc(e){let t=B.resolve(e);try{(await qr.stat(t)).isDirectory()||(t=B.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=B.resolve(VA.homedir());for(;;){if(!(t===i&&r!==i)){let o=B.join(t,...xc.split("/")),s=t===r||await zA(o);if(await Pp(o)&&s)return t}if(await Pp(B.join(t,".git")))return t;let a=B.dirname(t);if(a===t)return r;t=a}}function Rc(e){return bi(e)}async function GA(e,t){let r=Rc(t),i=B.resolve(e,...r.split("/")),n=await qr.realpath(e),a=await dn(i);if(!pn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Vt(e,t){let r=Rc(t),i=await GA(e,r),n=B.join(i,"comet");if(await _p(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([dn(i),dn(n)]);if(!pn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=B.resolve(e),c=B.join(s,".comet","runtime","native");if(await _p(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([qr.realpath(s),dn(c)]);if(!pn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:B.join(e,...xc.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:B.join(n,"specs"),changesDir:B.join(n,"changes"),archiveDir:B.join(n,"archive"),runtimeDir:c,changesRuntimeDir:B.join(c,"changes"),locksDir:B.join(c,"locks"),transactionsDir:B.join(c,"transactions")}}function Ap(e){if(!WA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Et(e,t){Ap(t);let r=B.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Yw(e,t){Ap(t);let r=B.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Y(e,t){let r=Et(e,t);if(Uw(r))return r;let i=Yw(e,t);return Uw(i)?i:r}function Ga(e,t){Ap(t);let r=B.join(e.changesDir,t),i=Y(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:B.join(r,"brief.md"),childrenPath:B.join(r,"children.yaml"),specsDir:B.join(r,"specs"),verificationPath:B.join(r,"verification.md"),statePath:B.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:B.join(i,"state.json")}}async function Kw(e){try{let t=await qr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ip(e,t){let r=Et(e,t),i=Yw(e,t),[n,a]=await Promise.all([Kw(r),Kw(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Mr(e,t){if(!t.startsWith("runtime/")||B.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=B.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ne(e,t){let r=B.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return pn(B.resolve(e),B.resolve(t))}async function V(e,t){let r=B.resolve(e),i=B.resolve(t);if(!pn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await _p(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([dn(r),dn(i)]);if(!pn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var xc,WA,K=I(()=>{"use strict";Fr();xc=".comet/config.yaml",WA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function UA(e="docs",t="en"){return yc(e,t)}async function xe(e){let t=(await Sc(e))?.config??null;return t?.native?t:null}async function _c(e){let t=await xe(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 Xw(e){let t=await Cc(e.startPath),r=await xe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${xc} 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?Rc(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??UA(i??"docs"),a=await Vt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Tp,Pc,Qe=I(()=>{"use strict";Fr();ln();Rp();oe();K();Tp=He,Pc=wc});import{createHash as $p,randomUUID as KA}from"node:crypto";import{promises as Ze}from"node:fs";import YA from"node:os";import Ve from"node:path";async function jp(e,t){let r=await Ze.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await Ze.readFile(e),n=await Ze.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 ey(e){try{let t=JSON.parse((await jp(Ve.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ve.join(e,t.file),i=await jp(r,65536);return $p("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function ZA(e,t){let r,i=KA(),n=Ve.join(e,`probe-${i}.cs`),a=Ve.join(e,`probe-${i}.exe`),o=Ve.join(e,`probe-${i}.json`);try{if(await Ze.mkdir(e,{recursive:!0,mode:448}),(await Ze.lstat(e)).isSymbolicLink())return null;r=await Ze.open(Ve.join(e,"prepare.lock"),"wx",384);let s=await ey(e);if(s)return s;await Ze.writeFile(n,Zw,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=Ve.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await Ze.access(d),c=d;break}catch{}}if(!c)return null;await Er(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=$p("sha256").update(await jp(a,65536)).digest("hex");return await Ze.writeFile(o,JSON.stringify({file:Ve.basename(a),hash:l}),{flag:"wx",mode:384}),await Ze.rename(o,Ve.join(e,"probe.json")),a}catch{return null}finally{await Ze.unlink(n).catch(()=>{}),await Ze.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await Ze.unlink(Ve.join(e,"prepare.lock")).catch(()=>{}))}}async function Qw(e,t,r){try{let i=await Er(Ve.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 Er(Ve.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 eI(e,t){let r=Ac.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:ZA(e,t),retryAfter:1/0};return Ac.set(e,i),i.promise.then(n=>{Ac.get(e)===i&&(n?Ac.delete(e):i.retryAfter=performance.now()+QA)}),i.promise}async function ty(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ve.join(t.cacheRoot??Ve.join(YA.tmpdir(),"comet-process-identity"),XA),n=async l=>{if(!l)return null;try{let d=(await Er(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await ey(i);if(a){let l=await n(a);return l||Qw(e,r,new AbortController().signal)}let o=eI(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),Qw(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Zw,XA,QA,Ac,ry=I(()=>{"use strict";Ui();Zw=`using System;
151
+ using System.Runtime.InteropServices;
152
+ class CometProcessIdentity {
153
+ [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
154
+ [DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
155
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
156
+ static int Main(string[] args) {
157
+ int pid; if(args.Length != 1 || !int.TryParse(args[0], out pid) || pid <= 0) return 1;
158
+ IntPtr handle=OpenProcess(0x1000, false, pid); if(handle == IntPtr.Zero) return 1;
159
+ try { long creation, exit, kernel, user; if(!GetProcessTimes(handle,out creation,out exit,out kernel,out user)) return 1;
160
+ Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
161
+ } finally { CloseHandle(handle); }
162
+ }
163
+ }`,XA=$p("sha256").update(Zw).digest("hex"),QA=1e4,Ac=new Map});import{promises as iy}from"node:fs";function rI(e){let t=Hp.get(e);if(t){if(Date.now()-t.at>tI){Hp.delete(e);return}return t.value}}async function Ja(e){if(e===process.pid&&Op!==null)return Op;let t=rI(e);if(t!==void 0)return t;let r=Ic.get(e);r||(r=iI(e),Ic.set(e,r));let i=await r;return Ic.get(e)===r&&Ic.delete(e),e===process.pid&&i!==null&&(Op=i),i===null&&Hp.set(e,{value:null,at:Date.now()}),i}async function iI(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([iy.readFile(`/proc/${e}/stat`,"utf8"),iy.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 ty(e);if(process.platform==="darwin"){let t=(await Er("/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 Tc(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Dp(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 Ja(e);return r===t?"alive":r===null||Tc(r)!==Tc(t)&&ny.has(Tc(r))&&ny.has(Tc(t))?"unknown":"dead"}var Op,tI,Hp,Ic,ny,jc=I(()=>{"use strict";Ui();ry();Op=null,tI=1e4,Hp=new Map,Ic=new Map;ny=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as nI}from"async_hooks";import{randomUUID as sy}from"crypto";import{promises as ot}from"fs";import cy from"os";import fe from"path";function sI(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function cI(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 ly(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 Oc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Xe(r,i)?G(r,i):G(r,i)&&e.size===t.size}function Ua(e,t){return Oc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function lI(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&&Ua(e.identity,t.identity)}async function st(e){let t,r;try{let i=await Si(e,ay,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof St?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${ay} 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:cI(JSON.parse(t.toString("utf8")),e),identity:ly(r)}}async function uI(e){return(await st(e))?.owner??null}async function Fp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==cy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Dp(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dI(e,t){try{await ot.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ot.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Hc(e,t){let r=await st(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ua(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ot.mkdir(t,{recursive:!0});let i=fe.join(t,`${fe.basename(e.file)}.${e.owner.id}.${sy()}.removed`);try{await ot.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await st(i);if(!n||n.owner.id!==e.owner.id||!Oc(n.identity,e.identity))throw await dI(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ot.rm(i,{force:!0}),"removed"}async function uy(e){let t=await Ja(process.pid);return{id:sy(),pid:process.pid,hostname:cy.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function dy(e,t){let r;try{r=await ot.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await uI(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)+`
164
+ `,"utf8"),await r.sync(),i=ly(await r.stat({bigint:!0}))}finally{await r.close()}let n=await st(e);if(!i||!n||n.owner.id!==t.id||!Oc(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function pI(e,t){let r=await V(e.runtimeDir,e.locksDir);await ot.mkdir(r,{recursive:!0});let i=await V(e.runtimeDir,fe.join(r,Bp));await ot.mkdir(i,{recursive:!0});let n=await uy(t),a=fe.join(i,`.${n.id}.tmp`),o=fe.join(i,`${n.id}.claim`);try{let s=await dy(a,n);await ot.rename(a,o);let c=await st(o);if(!c||!Oc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await ot.rm(a,{force:!0})}}async function fI(e){let t=fe.dirname(e.file),r=!1,i=fe.basename(e.file);for(let n of await ot.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=fe.join(t,n.name);if(fe.resolve(a)!==fe.resolve(e.file))try{let o=await st(a),s=await Fp(o);if(s.status==="missing")continue;let c=await st(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Ua(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await Hc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function py(e){let t=await st(e.file);if(t){if(t.owner.id!==e.owner.id||!Ua(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Hc(t,fe.dirname(e.file))}}async function hI(e,t){let r=Date.now()+aI;for(;;){let i=await pI(e,t);if(!await fI(i))return i;if(await py(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 mI(e){let t=$c.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return $c.set(e,n),await t,()=>{r(),$c.get(e)===n&&$c.delete(e)}}async function Lp(e,t,r){let i=fe.resolve(e.locksDir),n=oy.getStore();if(n?.has(i))return r();let a=await mI(i);try{let o=await hI(e,t),s=new Map(n??[]);return s.set(i,o),await oy.run(s,async()=>{try{return await r()}finally{await py(o)}})}finally{a()}}async function Dc(e,t,r){return Lp(e,`acquire ${t}`,async()=>{let i=await V(e.runtimeDir,e.locksDir);await ot.mkdir(i,{recursive:!0});let n=await V(e.runtimeDir,fe.join(i,sI(t))),a=await uy(r),o=await dy(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Bc(e){await st(e.file)&&await Lp({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${fe.basename(e.file)}`,async()=>{let t=await st(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ua(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=fe.join(e.locksDir,Bp);await Hc(t,r)})}function vI(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 fy(e){return Fp(await st(e))}async function hy(e,t,r,i={}){return Lp(e,`take over ${fe.basename(t)}`,async()=>{let n=await V(e.runtimeDir,e.locksDir),a=await V(e.runtimeDir,t);if(fe.resolve(fe.dirname(a))!==fe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await st(a),s=await Fp(o);if(s.status==="missing")return{status:"missing"};if(r&&!lI(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&vI(o?.owner??null)>=oI;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=fe.join(n,Bp);return await Hc(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var ay,Bp,aI,oI,oy,$c,Ka=I(()=>{"use strict";Va();jc();K();Lt();ay=16*1024,Bp=".coordinator",aI=5e3,oI=900*1e3,oy=new nI,$c=new Map});import{createHash as gI}from"node:crypto";function wy(e){return e.replaceAll(`\r
148
165
  `,`
149
166
  `).replaceAll("\r",`
150
- `)}function R_(e){return E_("sha256").update(Xg(e)).digest("hex")}function Qd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new te(`${t} must be an object`);return e}function Qg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new te(`${r} has unknown field(s): ${i.join(", ")}`)}function Zd(e,t){if(typeof e!="string"||e.trim().length===0)throw new te(`${t} must be a non-empty string`);return e.trim()}function Kg(e,t){if(e!==void 0){if(typeof e!="string")throw new te(`${t} must be text`);return Xg(e).replace(/^\n+|\n+$/gu,"")}}function rc(e,t){let r=Zd(e,t).toLowerCase();if(!P_.test(r))throw new te(`${t} must be a SHA-256 hash`);return r}function Yg(e,t,r){let i=Qd(e,t),n=Object.entries(i);if(n.length>Ug)throw new te(`${t} must contain at most ${Ug} entries`);let a={};for(let[o,s]of n){if(Yd(o,`${t} ID`)!==o)throw new te(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=rc(s,`${t}.${o}`)}return a}function Yd(e,t){let r=Zd(e,t);if(!C_.test(r))throw new te(`${t} is not a valid stable requirement ID`);return r}function __(e,t){let r=Zd(e,t);if(!x_.test(r))throw new te(`${t} is not a valid capability ID`);return r}function A_(e,t){let r=`Native delta operations[${t}]`,i=Qd(e,r);Qg(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Yd(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new te(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Yd(i.to_id,`${r}.to_id`),c=Kg(i.title,`${r}.title`),l=Kg(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:rc(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new te(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new te(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new te(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new te(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function I_(e){let t=Qd(e,"Native delta");if(Qg(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Kd)throw new te(`Native delta schema must be ${Kd}`);let r=__(t.capability,"Native delta capability"),i=rc(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new te("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:rc(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=Yg(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:Yg(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new te("Native delta operations must be an array");let s=t.operations.map(A_),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(c.has(f))throw new te(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${l}`);c.add(f)}}if(o!==void 0){if(a===void 0)throw new te("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new te(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new te(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Kd,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 j_(e){let t=(0,Xd.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new te(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function ef(e){return I_(typeof e=="string"?j_(e):e)}function Sa(e){return R_(e)}var Xd,Kd,x_,C_,P_,Ug,te,tf=I(()=>{"use strict";Xd=Gt(It(),1),Kd="comet.native.delta.v1",x_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,C_=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,P_=/^[a-f0-9]{64}$/iu,Ug=512,te=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});var Ht,Zt,er,Ki,Yi,Ea,xa=I(()=>{"use strict";Ht="comet.native.v3",Zt="comet.native.v2",er="comet.native.v1",Ki="comet.native.transition.v3",Yi="comet.native.transition.v2",Ea="comet.native.transition.v1"});import T_ from"node:path";function Pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rw(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 ui(e){if(!tw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function iw(e){if(!tw.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function nw(e,t){if(e.length===0||T_.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function B_(e,t){let r=Pa(e,`spec_changes[${t}]`);if(rw(r,H_,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(iw(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"&&nw(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"||!nf.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"||!nf.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 V_(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 af(e,t){if(rw(e,t,Dt),typeof e.name!="string")throw new Error("Native change name is required");if(ui(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"||!D_.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&&!q_.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(B_),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"||!F_.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"&&nw(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!V_(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 di(e){let t=Pa(e,Dt);if(t.schema!==er)throw new Error(`Expected ${er}`);return{schema:er,...af(t,$_)}}function Ca(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rf(e,t,r){if(e===null)return null;let i=typeof e=="string"?L_.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 M_(e){if(e==null)return null;if(typeof e!="string"||!nf.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function W_(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 fi(e){let t=Pa(e,Dt);if(t.schema!==Zt)throw new Error(`Expected ${Zt}`);if(Ca(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Zt} minimum_runtime_version must be 2`);return{schema:Zt,minimum_runtime_version:2,revision:Ca(t.revision,"Native v2 revision"),...af(t,ew)}}function qt(e){let t=Pa(e,Dt);if(t.schema!==Ht){if(t.schema===er||t.schema===Zt){let o=t.schema===er?di(t):fi(t);throw new Xi(o.name,o.schema)}throw new tr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Ca(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new tr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Ca(t.revision,"Native revision"),n=af(t,O_),a=M_(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ht,minimum_runtime_version:3,revision:i,verification_protocol:W_(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:rf(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:rf(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:rf(t.partial_allowance,"Native partial_allowance","allowances")}}function ic(e){let t=Pa(e,Dt);if(t.schema===er){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ht}`}}if(t.schema===Zt){let n=fi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ht}`}}if(t.schema!==Ht){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 tr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Ca(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new tr(t.schema,r).message};let i=qt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Zg,$_,ew,O_,H_,D_,q_,F_,Dt,nf,tw,L_,Xi,tr,nc=I(()=>{"use strict";xa();Zg=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],$_=new Set(Zg),ew=new Set([...Zg,"minimum_runtime_version","revision"]),O_=new Set([...ew,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),H_=new Set(["capability","operation","source","base_hash"]),D_=new Set(["shape","build","verify","archive"]),q_=new Set(["implicit","confirmed"]),F_=new Set(["pending","pass","fail"]),Dt="comet-state.yaml",nf=/^[a-f0-9]{64}$/u,tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,L_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Xi=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"},tr=class extends Error{constructor(r,i){super(r!==Ht||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 aw from"node:path";function X_(e,t){return e<t?-1:e>t?1:0}function cw(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:r,truncated:!0}}function lw(e,t){let r=t.toString(36),i=T("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function Q_(e){if(!K_.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=Y_.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==T("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function Z_(e,t){let r=cw(e.text,rr.maxTextBytes),i=e.context.slice(0,rr.maxContextItems).map(n=>cw(n,rr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function dw(e){let t=Q_({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(X_),n=i.slice(0,rr.maxFailedCheckIds),a=e.criteria.slice(t,t+rr.maxItems);for(let c of a){let l=[...r,Z_(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?lw(e.acceptanceHash,u):null,limits:{...rr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>rr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?lw(e.acceptanceHash,o):null,limits:{...rr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>rr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function sf(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 of(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 uw(e){return e.includes("-->")||e.includes("--!>")}function*Qi(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
167
+ `)}function bI(e){return gI("sha256").update(wy(e)).digest("hex")}function Wp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ie(`${t} must be an object`);return e}function yy(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new ie(`${r} has unknown field(s): ${i.join(", ")}`)}function zp(e,t){if(typeof e!="string"||e.trim().length===0)throw new ie(`${t} must be a non-empty string`);return e.trim()}function vy(e,t){if(e!==void 0){if(typeof e!="string")throw new ie(`${t} must be text`);return wy(e).replace(/^\n+|\n+$/gu,"")}}function Fc(e,t){let r=zp(e,t).toLowerCase();if(!NI.test(r))throw new ie(`${t} must be a SHA-256 hash`);return r}function gy(e,t,r){let i=Wp(e,t),n=Object.entries(i);if(n.length>my)throw new ie(`${t} must contain at most ${my} entries`);let a={};for(let[o,s]of n){if(Mp(o,`${t} ID`)!==o)throw new ie(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Fc(s,`${t}.${o}`)}return a}function Mp(e,t){let r=zp(e,t);if(!yI.test(r))throw new ie(`${t} is not a valid stable requirement ID`);return r}function kI(e,t){let r=zp(e,t);if(!wI.test(r))throw new ie(`${t} is not a valid capability ID`);return r}function SI(e,t){let r=`Native delta operations[${t}]`,i=Wp(e,r);yy(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Mp(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new ie(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Mp(i.to_id,`${r}.to_id`),c=vy(i.title,`${r}.title`),l=vy(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Fc(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new ie(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new ie(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new ie(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new ie(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function EI(e){let t=Wp(e,"Native delta");if(yy(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==qp)throw new ie(`Native delta schema must be ${qp}`);let r=kI(t.capability,"Native delta capability"),i=Fc(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new ie("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Fc(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=gy(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:gy(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new ie("Native delta operations must be an array");let s=t.operations.map(SI),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let p of d){if(c.has(p))throw new ie(`Native delta operations contain duplicate or overlapping requirement ID ${p} at ${l}`);c.add(p)}}if(o!==void 0){if(a===void 0)throw new ie("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new ie(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new ie(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:qp,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 xI(e){let t=(0,Vp.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new ie(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Gp(e){return EI(typeof e=="string"?xI(e):e)}function Ya(e){return bI(e)}var Vp,qp,wI,yI,NI,my,ie,Jp=I(()=>{"use strict";Vp=ir(Bt(),1),qp="comet.native.delta.v1",wI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yI=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,NI=/^[a-f0-9]{64}$/iu,my=512,ie=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});var Wt,lr,ur,fn,hn,Xa,Qa=I(()=>{"use strict";Wt="comet.native.v3",lr="comet.native.v2",ur="comet.native.v1",fn="comet.native.transition.v3",hn="comet.native.transition.v2",Xa="comet.native.transition.v1"});import CI from"node:path";function eo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Sy(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 Ei(e){if(!ky.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ey(e){if(!ky.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function xy(e,t){if(e.length===0||CI.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function $I(e,t){let r=eo(e,`spec_changes[${t}]`);if(Sy(r,_I,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Ey(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"&&xy(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"||!Kp.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"||!Kp.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 OI(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 Yp(e,t){if(Sy(e,t,zt),typeof e.name!="string")throw new Error("Native change name is required");if(Ei(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"||!AI.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&&!II.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($I),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"||!TI.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"&&xy(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!OI(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 xi(e){let t=eo(e,zt);if(t.schema!==ur)throw new Error(`Expected ${ur}`);return{schema:ur,...Yp(t,RI)}}function Za(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Up(e,t,r){if(e===null)return null;let i=typeof e=="string"?jI.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 HI(e){if(e==null)return null;if(typeof e!="string"||!Kp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function DI(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=eo(e,zt);if(t.schema!==lr)throw new Error(`Expected ${lr}`);if(Za(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${lr} minimum_runtime_version must be 2`);return{schema:lr,minimum_runtime_version:2,revision:Za(t.revision,"Native v2 revision"),...Yp(t,by)}}function Gt(e){let t=eo(e,zt);if(t.schema!==Wt){if(t.schema===ur||t.schema===lr){let o=t.schema===ur?xi(t):Ci(t);throw new mn(o.name,o.schema)}throw new dr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Za(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new dr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Za(t.revision,"Native revision"),n=Yp(t,PI),a=HI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Wt,minimum_runtime_version:3,revision:i,verification_protocol:DI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Up(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Up(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Up(t.partial_allowance,"Native partial_allowance","allowances")}}function Lc(e){let t=eo(e,zt);if(t.schema===ur){let n=xi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Wt}`}}if(t.schema===lr){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 ${Wt}`}}if(t.schema!==Wt){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 dr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Za(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new dr(t.schema,r).message};let i=Gt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Ny,RI,by,PI,_I,AI,II,TI,zt,Kp,ky,jI,mn,dr,qc=I(()=>{"use strict";Qa();Ny=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],RI=new Set(Ny),by=new Set([...Ny,"minimum_runtime_version","revision"]),PI=new Set([...by,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),_I=new Set(["capability","operation","source","base_hash"]),AI=new Set(["shape","build","verify","archive"]),II=new Set(["implicit","confirmed"]),TI=new Set(["pending","pass","fail"]),zt="comet-state.yaml",Kp=/^[a-f0-9]{64}$/u,ky=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,mn=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"},dr=class extends Error{constructor(r,i){super(r!==Wt||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 Cy from"node:path";function WI(e,t){return e<t?-1:e>t?1:0}function _y(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:r,truncated:!0}}function Ay(e,t){let r=t.toString(36),i=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function zI(e){if(!MI.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=VI.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function GI(e,t){let r=_y(e.text,pr.maxTextBytes),i=e.context.slice(0,pr.maxContextItems).map(n=>_y(n,pr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function Ty(e){let t=zI({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(WI),n=i.slice(0,pr.maxFailedCheckIds),a=e.criteria.slice(t,t+pr.maxItems);for(let c of a){let l=[...r,GI(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(p=>p.verificationStatus==="failed").map(p=>p.id),missingAcceptanceIds:l.filter(p=>p.verificationStatus==="missing").map(p=>p.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?Ay(e.acceptanceHash,u):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>pr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?Ay(e.acceptanceHash,o):null,limits:{...pr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>pr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Qp(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Xp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Iy(e){return e.includes("-->")||e.includes("--!>")}function*vn(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
151
168
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
152
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=of(l,t);else if(r)uw(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=of(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!uw(f))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function eA(e){return[...Qi(e)].map(({line:t,body:r})=>({line:t,body:r}))}function ac(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function tA(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function cf(e,t,r,i=[],n="content-hash"){let a=ac(r),o=t.replaceAll("\\","/").trim(),s=i.map(ac);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-${T(z_,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function lf(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 rA(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Qi(e)){n=s+1;let c=o?sf(a):null;c?.level===1&&(Rs(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function uf(e,t="brief.md",r=Ra.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=rA(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Qi(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Qi(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),lf(o.map(l=>cf("brief-example",t,l.join(`
153
- `),[],i)),"Brief",i)}function df(e,t="spec.md",r=Ra.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(cf("spec-scenario",t,[o.title,...o.body].join(`
154
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Qi(e)){let u=l?sf(c):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=ac(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(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),lf(n,"Specification",i)}function fw(e,t="spec.md",r=Ra.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=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(cf("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Qi(e)){let f=d?sf(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||of(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),lf(n,"Specification mandatory requirements",i)}function iA(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||tA(r)||aw.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=aw.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!U_.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function nA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!G_.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function pw(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=nA(r,i),a=n.acceptance_id;if(typeof a!="string"||!J_.test(a))throw new Error(`Acceptance evidence entry ${i} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return iA(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function hw(e){let t=eA(e);if(t.some(({line:l,body:u})=>!u&&(l===ow||l===sw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===ow?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===sw?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
155
- `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=pw(o),c=aA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function aA(e){let t=pw([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var z_,J_,G_,U_,K_,Y_,rr,Ra,ow,sw,_a=I(()=>{"use strict";oi();ce();z_="comet.native.acceptance.v1",J_=/^acceptance-[a-f0-9]{64}$/u,G_=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),U_=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,K_=/^[a-f0-9]{64}$/u,Y_=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;rr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ra=Object.freeze({maxCriteria:1024}),ow="<!-- comet-native:acceptance-evidence:start -->",sw="<!-- comet-native:acceptance-evidence:end -->"});var ff=I(()=>{"use strict";_a()});function pf(){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 Zi,oc,mw,Aa=I(()=>{"use strict";Zi="comet.native.v4",oc="comet.native.local-execution.v4",mw=["multi-session","single-session"]});var wf={};gS(wf,{NativePortableStateVersionConflictError:()=>Ia,appendNativePortableHistory:()=>ja,compareAndSwapNativePortableState:()=>ww,createNativePortableState:()=>gw,parseNativePortableState:()=>Be,readNativePortableState:()=>jr,writeNativePortableState:()=>gf});import{promises as oA}from"node:fs";function je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Te(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 ye(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 mf(e,t){return e===null?null:ye(e,t)}function vf(e,t){let r=ye(e,t);if(!uA.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function en(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ne(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 fA(e,t){return e===null?null:ne(e,t,Number.MIN_SAFE_INTEGER)}function fe(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ft(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function uc(e,t){return Ft(e,t,(r,i)=>ye(r,`${t}[${i}]`))}function pi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function tn(e,t){let r=ye(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function cc(e,t,r=!1){let i=ye(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 rt(e,t){let r=je(e,t);return Te(r,new Set(["text","truncated"]),t),{text:ye(r.text,`${t}.text`,{empty:!0}),truncated:en(r.truncated,`${t}.truncated`)}}function pA(e,t){let r=`Native spec_changes[${t}]`,i=je(e,r);Te(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ye(i.capability,`${r}.capability`);if(!cA.test(n))throw new Error(`${r}.capability is invalid`);let a=fe(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:cc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:cc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:vf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function hA(e){let t="Native workspace",r=je(e,t);Te(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=fe(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=mf(r.change_branch,`${t}.change_branch`),a=mf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:fe(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 mA(e){let t="Native loop",r=je(e,t);Te(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=uc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);pi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:fe(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:fe(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ne(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ne(r.iteration,`${t}.iteration`),attempt:ne(r.attempt,`${t}.attempt`),retry_epoch:ne(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ne(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ne(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ne(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:mf(r.next_action,`${t}.next_action`)}}function vA(e,t){let r=`Native acceptance[${t}]`,i=je(e,r);Te(i,new Set(["id","source","text","result","reason"]),r);let n=ye(i.id,`${r}.id`);if(!lA.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:cc(i.source,`${r}.source`),text:ye(i.text,`${r}.text`),result:fe(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:rt(i.reason,`${r}.reason`)}}function gA(e,t){let r=`Native builder_handoff.checks[${t}]`,i=je(e,r);return Te(i,new Set(["name","result","note"]),r),{name:rt(i.name,`${r}.name`),result:fe(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:rt(i.note,`${r}.note`)}}function wA(e){let t="Native builder_handoff",r=je(e,t);Te(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=uc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);pi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:je(r.review,`${t}.review`);return n&&Te(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:ye(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ye(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ne(r.iteration,`${t}.iteration`,1),summary:rt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ft(r.checks,`${t}.checks`,gA),checks_truncated:en(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ft(r.known_limits,`${t}.known_limits`,(a,o)=>rt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:en(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:fe(n.status,["passed"],`${t}.review.status`),summary:rt(n.summary,`${t}.review.summary`),reviewer_execution_ref:ye(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:tn(r.submitted_at,`${t}.submitted_at`)}}function yA(e,t){let r=`Native blockers[${t}]`,i=je(e,r);Te(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=uc(i.acceptance_ids,`${r}.acceptance_ids`);return pi(n,`${r}.acceptance_ids`),{owner:fe(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:rt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:fe(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function NA(e,t){let r=`Native verification.checks[${t}]`,i=je(e,r);return Te(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ye(i.id,`${r}.id`),name:rt(i.name,`${r}.name`),argv_display:Ft(i.argv_display,`${r}.argv_display`,(n,a)=>rt(n,`${r}.argv_display[${a}]`)),argv_truncated:en(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:cc(i.cwd_ref,`${r}.cwd_ref`,!0),status:fe(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:fA(i.exit_code,`${r}.exit_code`),duration_ms:ne(i.duration_ms,`${r}.duration_ms`)}}function bA(e){let t="Native verification",r=je(e,t);Te(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ft(r.checks,`${t}.checks`,NA);pi(i.map(a=>a.id),`${t}.checks IDs`);let n=ye(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ye(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ye(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ne(r.iteration,`${t}.iteration`,1),attempt:ne(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":fe(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:fe(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:rt(r.summary,`${t}.summary`),risks:Ft(r.risks,`${t}.risks`,(a,o)=>rt(a,`${t}.risks[${o}]`)),risks_truncated:en(r.risks_truncated,`${t}.risks_truncated`),completed_at:tn(r.completed_at,`${t}.completed_at`)}}function vw(e,t){let r=`Native history[${t}]`,i=je(e,r);Te(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=uc(i.unresolved_ids,`${r}.unresolved_ids`);return pi(n,`${r}.unresolved_ids`),{goal_cycle:ne(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ne(i.iteration,`${r}.iteration`),attempt:ne(i.attempt,`${r}.attempt`),outcome:fe(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:rt(i.summary,`${r}.summary`),completed_at:tn(i.completed_at,`${r}.completed_at`)}}function kA(e){let t="Native history_overflow.outcome_counts",r=je(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Te(r,new Set(i),t),{pass:ne(r.pass,`${t}.pass`),fail:ne(r.fail,`${t}.fail`),blocked:ne(r.blocked,`${t}.blocked`),"execution-error":ne(r["execution-error"],`${t}.execution-error`),recovery:ne(r.recovery,`${t}.recovery`)}}function SA(e){let t="Native history_overflow",r=je(e,t);Te(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ne(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:tn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:tn(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=kA(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function EA(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 xA(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 Be(e){let t=je(e,"Native portable state");if(Te(t,dA,"Native portable state"),t.schema!==Zi)throw new Error(`Native portable state schema must be ${Zi}`);let r=ye(t.name,"Native state name");if(!sA.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=Ft(t.spec_changes,"Native spec_changes",pA);pi(i.map(s=>s.capability),"Native spec change capabilities");let n=Ft(t.acceptance,"Native acceptance",vA);pi(n.map(s=>s.id),"Native acceptance IDs");let a=Ft(t.history,"Native history",vw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Zi,name:r,language:fe(t.language,["en","zh-CN"],"Native state language"),phase:fe(t.phase,["shape","build","verify","archive"],"Native state phase"),status:fe(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ne(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:vf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:vf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:fe(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:hA(t.workspace),loop:mA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:wA(t.builder_handoff),blockers:Ft(t.blockers,"Native blockers",yA),verification:t.verification===null?null:bA(t.verification),history:a,history_overflow:SA(t.history_overflow),verification_result:fe(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:fe(t.verification_report,["verification.md"],"Native verification_report"),archived:en(t.archived,"Native archived"),created_at:tn(t.created_at,"Native created_at")};return EA(o),xA(o),o}function gw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return Be({schema:Zi,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:pf(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ja(e,t){let r=Be(e),i=vw(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 Be({...r,history:n,history_overflow:a})}function CA(e,t){let r=(0,lc.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 jr(e){let t=await oA.readFile(e,"utf8");return Be(CA(t,"Native portable state"))}async function gf(e,t,r={}){let i=Be(t);await $t(e,(0,lc.stringify)(i),r)}async function PA(e,t){let r=sc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);sc.set(e,a),await r;try{return await t()}finally{i(),sc.get(e)===a&&sc.delete(e)}}async function ww(e){return PA(e.file,async()=>{let t=ne(e.expectedStateVersion,"Native expected state version",1),r=Be(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await jr(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ia(t,i.state_version);return await gf(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await jr(e.file);if(n.state_version!==t)throw new Ia(t,n.state_version)}}),r})}var lc,sA,cA,lA,uA,dA,Ia,sc,wt=I(()=>{"use strict";lc=Gt(It(),1);le();Aa();sA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lA=/^A[1-9][0-9]*$/u,uA=/^[a-f0-9]{64}$/u,dA=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"]),Ia=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"};sc=new Map});var hi=I(()=>{"use strict"});function TA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $A(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 Nw(e){let t=TA(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!RA.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==yw)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!AA.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!_A.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!jA.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!IA.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yw,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:$A(t.createdAt,"Native portable migration transaction createdAt")}}var yw,RA,_A,AA,IA,jA,bw=I(()=>{"use strict";nc();ff();wt();hi();Aa();xa();yw="comet.native.portable-migration.v1",RA=new Set(["schema","id","change","fromSchema","status","createdAt"]),_A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AA=/^[a-z0-9][a-z0-9-]{7,127}$/u,IA=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),jA=new Set([er,Zt,Ht])});import OA from"node:path";function Cw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Pw(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 yf(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 Sw(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function MA(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Cw(e,r);if(Pw(i,VA,r),typeof i.capability!="string"||!xw.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=yf(i.base_hash,`${r}.base_hash`),s=Sw(i.delta_content,`${r}.delta_content`),c=Sw(i.source_content,`${r}.source_content`),l=yf(i.expected_target_hash,`${r}.expected_target_hash`),u=yf(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=ef(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(Sa(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Sa(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(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||Sa(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function WA(e){let t=Cw(e,"Native portable Archive transaction");if(Pw(t,BA,"Native portable Archive transaction"),t.schema!==kw)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!qA.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!xw.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"||!FA.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"||!LA.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(MA);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:kw,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 Nf(e){let t=HA.exec(e);if(t)return{kind:"archive",change:t[1]};let r=DA.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Rw(e,t){let r=Nf(t);if(!r)return null;let i=await ee({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=OA.join(e.transactionsDir,t);if(r.kind==="archive"){let s=WA(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=Nw(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function _w(e){return e.kind==="archive"||e.journal.status!=="committed"}var kw,Ew,HA,DA,qA,FA,LA,BA,VA,xw,bf=I(()=>{"use strict";et();tf();bw();kw="comet.native.archive-transaction.v4",Ew="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",HA=new RegExp(`^portable-archive-(${Ew})\\.json$`,"u"),DA=new RegExp(`^portable-migration-(${Ew})\\.json$`,"u"),qA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,FA=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LA=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),BA=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),VA=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),xw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Aw}from"node:crypto";import{constants as Tr,promises as pe}from"node:fs";import Ve from"node:path";import{TextDecoder as zA}from"node:util";function rn(e,t){let r=Ve.relative(e,t);return r===""||!Ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ve.sep}`)}function Iw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function JA(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function $r(e,t){return z({...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 dc(e,t){let r=await pe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await pe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function fc(e,t,r){let i=Ve.resolve(e),n=Ve.resolve(t);if(!rn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await dc(i,r)],o=i;for(let s of Ve.relative(i,n).split(Ve.sep).filter(Boolean)){await $e(a,r),o=Ve.join(o,s);let c=await dc(o,r);if(!rn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await $e(a,r),a}async function $e(e,t){for(let r of e){let i=await pe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!JA(r,i)||await pe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function GA(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 Or(e){let t=e.maxBytes===null?null:Iw(e.maxBytes),r=Ve.resolve(e.file),i=await fc(e.root,Ve.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>dc(Ve.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await $e(i,e.label);let a=await pe.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=jw(a),s=await pe.realpath(r);if(!rn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>rn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Tr.O_RDONLY:Tr.O_RDONLY|Tr.O_NOFOLLOW|Tr.O_NONBLOCK,l=await pe.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([pe.lstat(r),pe.realpath(r)]);if(await $e(i,e.label),await $e(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!$r(o,u)||!$r(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await GA(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),pe.lstat(r),pe.realpath(r)]);if(await $e(i,e.label),await $e(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!$r(o,m)||!$r(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Aw("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function kf(e){let t=Ve.resolve(e.file),r=await fc(e.root,Ve.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>dc(Ve.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await $e(r,e.label);let n=await pe.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=jw(n),o=await pe.realpath(t);if(!rn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>rn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Tr.O_RDONLY:Tr.O_RDONLY|Tr.O_NOFOLLOW|Tr.O_NONBLOCK,c=await pe.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([pe.lstat(t),pe.realpath(t)]);if(await $e(r,e.label),await $e(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!$r(a,l)||!$r(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=Aw("sha256"),p=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;p+=b,f.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),pe.lstat(t),pe.realpath(t)]);if(await $e(r,e.label),await $e(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!$r(a,h)||!$r(a,v))throw new Error(`${e.label} changed while reading`);return{hash:f.digest("hex"),size:p}}finally{await c.close()}}async function Tw(e){let t=await Or(e),r;try{r=new zA("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function $a(e){let t=await fc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await pe.readdir(e.directory,{withFileTypes:!0});else{let i=Iw(e.maxEntries);r=[];let n=await pe.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await $e(t,e.label),{entries:r,verify:()=>$e(t,e.label)}}async function Sf(e){let t=await fc(e.root,e.directory,e.label);return{verify:()=>$e(t,e.label)}}var yt=I(()=>{"use strict";le();Tt()});import ir from"path";import{TextDecoder as KA}from"util";function hc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mc(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 Dw(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ef(e,t){if(typeof e!="string"||e.length===0||ir.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function pc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $w(e,t){if(Ef(e,t),e.includes("\\")||e!==ir.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 tI(e,t){let r=hc(e,`transaction operations[${t}]`);if(mc(r,XA,`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`);Ef(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Ef(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 qw(e){let t=hc(e,"Native Archive transaction journal");if(mc(t,QA,"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"||!Hw.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(!Dw(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(pc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=hc(s,`Archive transaction operations[${c}]`);if(mc(l,ZA,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);$w(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&$w(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&pc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(pc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);pc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function rI(e){let t=hc(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return qw(t);if(mc(t,YA,"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"||!Hw.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ir.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ir.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(!Dw(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(tI),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 iI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ir.join(e.transactionsDir,t)}function Fw(e,t){let r=iI(e,t);return{directory:r,journal:ir.join(r,"transaction.json"),events:ir.join(r,"events.jsonl"),staged:ir.join(r,"staged"),backups:ir.join(r,"backups")}}async function xf(e,t){let r=Fw(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function Cf(e,t,r={}){let i=await xf(e,t),n=await Or({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(eI.decode(n.bytes)),o=rI(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var YA,XA,QA,ZA,Hw,eI,vc=I(()=>{"use strict";le();U();yt();YA=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),XA=new Set(["id","type","source","target","staged","backup"]),QA=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),ZA=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Hw=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),eI=new KA("utf-8",{fatal:!0})});import{promises as nI}from"fs";import aI from"path";async function oI(e,t,r){let i;try{i=await nI.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 Cf(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(Nf(n.name))try{let a=await Rw(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(_w(a))return!0}catch{return!0}return!1}async function sI(e,t){let r=Date.now()+5e3,i=aI.join(e.locksDir,"root-move.lock");for(;;)try{return await ec(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Jg(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Gg(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 Se(e,t,r,i){let n=await sI(e,t);try{if(await zs(e.projectRoot),await oI(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await tc(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
156
- `)}}}var Ee=I(()=>{"use strict";Ge();ka();bf();vc()});import{createHash as Lw}from"crypto";import{createReadStream as cI}from"fs";async function Pf(e){let t=Lw("sha256");for await(let r of cI(e))t.update(r);return t.digest("hex")}function Q(e){return Lw("sha256").update(e).digest("hex")}var Lt=I(()=>{"use strict"});import{createHash as bc}from"crypto";import{spawn as Kw}from"node:child_process";import{promises as re}from"fs";import F from"path";function Xw(e){let t=e.deadlineMs??CI;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Nt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return Nt(e)>=1}function Rf(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function on(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function AI(e,t){let r={..._I,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function II(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=Kw(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),PI),u.unref()}catch{d(!1)}});for(let s=0;s<RI;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function $f(e,t,r,i){let n=Nt(e);if(n<1)throw Rf();let a=e.gitProcess,o=Kw(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=II(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Rf(m.error):Rf()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Qw(e,t){let r={...Tf,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function wc(e,t,r,i=If){let{child:n,completion:a}=$f(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>i&&(u=!0)}),n.stderr.on("data",p=>{if(c>=cn)return;let m=cn-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function _f(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Ha(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=$f(e,t,r,i.stdin!==void 0),c=[],l=bc("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,S=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),k=w<0?N.byteLength:w,E=N.subarray(x,k);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&p+y<=i.maxBytes?(c.push(h),p+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){S(N);return}for(let w=0;w<N.byteLength;w+=x)S(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=cn)return;let x=cn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function yc(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function jI(e,t,r){if(r.length===0)return new Set;let i=await Ha(e,t,["check-ignore","--no-index","-z","--stdin"],{...Tf,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=yc(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function TI(e,t,r){let{child:i,completion:n}=$f(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=cn)return;let d=cn-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function sn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function $I(e,t){return e.map(r=>{let i=sn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function OI(e){let t=F.resolve(e);for(;;){try{return await re.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function HI(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function Zw(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(p=>{let m=F.relative(a,F.resolve(p)).replaceAll("\\","/"),h=sn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(p=>[`:(exclude)${p}`,`:(exclude)${p}/**`]),...HI(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await Ha(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await Ha(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let f=await Ha(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:f}}function ey(e){return{stageBefore:_f(e.stagedBefore),combined:_f(e.combined),stageAfter:_f(e.stagedAfter)}}async function ty(e,t,r=Tf,i={},n){let a=F.resolve(t.projectRoot);if(!await OI(a))return null;let o;try{o=await wc(e,a,["rev-parse","--is-inside-work-tree"])}catch(S){throw on(S)?S:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:S})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await Zw(e,t,r,i,n)}catch(S){throw on(S)?S:new Error("Native Git snapshot provider failed after repository detection",{cause:S})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,f=new Map,p=new Set,m=S=>{for(let N of S){let x=yc(N),w=x.indexOf(" ");if(w<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let k=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(x.slice(0,w))?.groups;if(!k)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=sn(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),k.stage==="0"&&f.set(E,k.objectId),k.mode==="160000"&&k.stage==="0"&&p.add(E)}};m(c.records),m(u.records);let h=l.records.map(yc),v=$I(h,"combined"),g=new Set(v.filter(S=>!d.has(S))),b=new Set(v.filter((S,N)=>!d.has(S)&&h[N].endsWith("/")));for(let S of p)b.delete(S);return{tracked:d,trackedObjectIds:f,untracked:g,gitlinks:p,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:ey(s)}}function Dr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Bw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function DI(e,t){return!Dr(e.stageBefore,e.stageAfter)||!Dr(e.stageAfter,t.stageBefore)||!Dr(e.combined,t.combined)||!Dr(t.stageBefore,t.stageAfter)}async function ry(e,t,r,i,n,a){let o;try{o=await Zw(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw on(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=ey(o),l=Bw(s)||Bw(c),u=DI(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:Q(`comet.native.git-selection-overflow.v2
157
- ${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function FI(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Vw(e){let t=F.resolve(e.paths.projectRoot),r=F.resolve(e.paths.nativeRoot),i=F.resolve(e.paths.runtimeDir),n=F.resolve(e.paths.configFile),a=F.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,m=!1,h=!1,v=()=>Nt(e.execution)>=1?!0:(p=!0,h=!0,!1),g=N=>{let x=Buffer.from(`${N.type}\0${N.path}`,"utf8"),w=bc("sha256").update("comet.native.physical-selection-record.v1\0").update(x).digest();for(let k=0;k<c.length;k+=1)c[k]^=w[k];if(l=l+BigInt(`0x${w.toString("hex")}`)&qI,d+=1,f+=x.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(N)},b=async N=>{if(h||!v())return;let x;try{x=await re.opendir(N)}catch(C){if(!v())return;if(!me(C)&&!he(C)||N===t&&me(C))throw C;m||=he(C),p||=me(C),h=!0;return}if(!v()){try{await x.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let w=!1,k;try{for(;!h&&v();){let C;try{C=await x.read()}catch(X){if(!v())break;if(!me(X)&&!he(X)||N===t&&me(X))throw X;m||=he(X),p||=me(X),h=!0;break}if(!v()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let O=F.join(N,C.name),j=BI(t,O);if(O===n||O===a||bt(r,O)||bt(i,O)||e.denylist.some(X=>bt(X,O))||jt(j)!==null)continue;if(!v())break;let Y;try{Y=await re.lstat(O)}catch(X){if(!v())break;if(!me(X)&&!he(X))throw X;if(m=!0,g({path:j,type:"other"}),s.push({path:j,size:null,type:"file",reason:me(X)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;let Re=FI(Y);if(Re==="directory"){if(zI(e.policy,j))continue;if(!v())break;let X;try{X=await re.realpath(O)}catch(Rt){if(!v())break;if(!me(Rt)&&!he(Rt))throw Rt;if(m=!0,g({path:j,type:Re}),s.push({path:j,size:null,type:"directory",reason:me(Rt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(j),h||!v())break;continue}if(!v())break;if(!B(e.physicalProjectRoot,X)||bt(e.physicalNativeRoot,X))continue;if(g({path:j,type:Re}),await e.hooks?.afterNode?.(j),!v()||(await b(O),h))break;continue}if(g({path:j,type:Re}),await e.hooks?.afterNode?.(j),!v()||h)break}}catch(C){w=!0,k=C}let E;try{await x.close()}catch(C){E=C}let y=v();if(w)throw k;if(y&&E!==void 0&&E.code!=="ERR_DIR_CLOSED")throw E};await b(t),v(),p?(o.length=0,d=0,f=0):(o.sort((N,x)=>N.path.localeCompare(x.path,"en")),s.sort((N,x)=>N.path.localeCompare(x.path,"en")));let S=p?Q(`comet.native.physical-selection-incomplete.v1
158
- ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):Q(`comet.native.physical-selection.v1
159
- ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:S,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:m}}}function iy(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function LI(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!iy(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function ny(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function Mw(e,t){let i=(await wc(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Yw.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return Q(`gitlink:${i}`)}async function Ww(e,t){let r=await Mw(e,t),i=await TI(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Mw(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Oa(e,t){if(jt(t)!==null)return!1;let r=F.resolve(e.projectRoot,...t.split("/"));return!bt(F.resolve(e.nativeRoot),r)&&!bt(F.resolve(e.runtimeDir),r)}function BI(e,t){return F.relative(e,t).split(F.sep).join("/")}function VI(e,t){return t.map(r=>F.resolve(e,...r.split(/[\\/]/u)))}function bt(e,t){let r=F.resolve(e),i=F.resolve(t);return i===r||B(r,i)}function me(e){return xI.has(e.code??"")}function he(e){return e.code==="ENOENT"}function MI(e,t){return Q(`comet.native.snapshot-policy.v1
160
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Af(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function WI(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function zw(e){let t=Ws(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?WI(n):void 0;if(a&&!a())return!1;let o=Af(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Af(r,c,a),o===null||o.size===0)return!1}return Af(r,o,a)?.has(r.length)??!1}}function ay(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Ws(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Ws(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=MI(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(zw),excludeMatchers:r.map(zw),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function zI(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Jw(e,t,r){if(!e)return!0;let i=()=>H(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function Nc(e,t,r){let i=JSON.stringify(r);return Q(`${e}
169
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Xp(l,t);else if(r)Iy(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=Xp(l,null);if(d!==null)t=d;else{let p=l.trimStart();if(p.startsWith("<!--")&&!Iy(p))r=!0;else{let f=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(p);f&&n.has(f[1].toLowerCase())&&!p.startsWith("</")&&!p.endsWith("/>")&&!new RegExp(`</${f[1]}\\s*>`,"iu").test(p)&&(i=f[1])}}}if(c===-1)break;o=c+1}}function JI(e){return[...vn(e)].map(({line:t,body:r})=>({line:t,body:r}))}function Mc(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function UI(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Zp(e,t,r,i=[],n="content-hash"){let a=Mc(r),o=t.replaceAll("\\","/").trim(),s=i.map(Mc);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(BI,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function ef(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 KI(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of vn(e)){n=s+1;let c=o?Qp(a):null;c?.level===1&&(pc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function tf(e,t="brief.md",r=to.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=KI(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of vn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(p===null)continue;let f=p[1].length;a=a===null?f:Math.min(a,f)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of vn(e)){if(d<n.start||d>=n.end)continue;let p=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;p&&p[1].length===a?(c(),s=[p[2]]):s!==null&&s.push(l)}return c(),ef(o.map(l=>Zp("brief-example",t,l.join(`
170
+ `),[],i)),"Brief",i)}function rf(e,t="spec.md",r=to.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,c=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.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(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...Zp("spec-scenario",t,[s.title,...s.body].join(`
171
+ `),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of vn(e)){let d=u?Qp(l):null,p=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(p){for(c();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let f=Mc(p[1]);if(f.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:f,body:[],context:o.map(m=>m.text)}}else if(d){for(s!==null&&d.level<=s.level?c():s!==null&&s.body.push(l);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(l)}return c(),ef(a,"Specification",i)}function jy(e,t="spec.md",r=to.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=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Zp("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of vn(e)){let p=d?Qp(u):null;if(p){for(c(),o!==null&&p.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=p.level;)a.pop();a.push(p),/^Scenario\s*:/iu.test(p.text)&&(o=p.level);continue}let f=u.trim();if(!d||o!==null||l()){c();continue}if(f.length===0||Xp(u,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){c();continue}let m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(f)){c(),s={parts:[f],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[f],context:a.map(h=>h.text)}:s.parts.push(f)}return c(),ef(n,"Specification mandatory requirements",i)}function YI(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||UI(r)||Cy.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=Cy.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!qI.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function XI(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!LI.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function $y(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=XI(r,i),a=n.acceptance_id;if(typeof a!="string"||!FI.test(a))throw new Error(`Acceptance evidence entry ${i} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return YI(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Oy(e){let t=JI(e);if(t.some(({line:l,body:u})=>!u&&(l===Ry||l===Py)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===Ry?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Py?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
172
+ `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=$y(o),c=QI(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function QI(e){let t=$y([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var BI,FI,LI,qI,MI,VI,pr,to,Ry,Py,ro=I(()=>{"use strict";Ni();de();BI="comet.native.acceptance.v1",FI=/^acceptance-[a-f0-9]{64}$/u,LI=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),qI=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,MI=/^[a-f0-9]{64}$/u,VI=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;pr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),to=Object.freeze({maxCriteria:1024}),Ry="<!-- comet-native:acceptance-evidence:start -->",Py="<!-- comet-native:acceptance-evidence:end -->"});var nf=I(()=>{"use strict";ro()});function af(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 io({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var io,Vc=I(()=>{"use strict";io=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 of(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 sf(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}]`;af(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:of(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>of(o,`${n}.evidence`)),note:of(i.note,`${n}.note`)}})}function cf(e,t){if(!t)throw new gn(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),i=t.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new gn(o,s)}var gn,Wc=I(()=>{"use strict";Vc();gn=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 lf(){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 wn,zc,Hy,no=I(()=>{"use strict";wn="comet.native.v4",zc="comet.native.local-execution.v4",Hy=["multi-session","single-session"]});var hf={};ex(hf,{NativePortableStateVersionConflictError:()=>ao,appendNativePortableHistory:()=>oo,compareAndSwapNativePortableState:()=>Fy,createNativePortableState:()=>By,parseNativePortableState:()=>ze,readNativePortableState:()=>Vr,writeNativePortableState:()=>ff});import{promises as ZI}from"node:fs";function De(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Be(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 be(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 df(e,t){return e===null?null:be(e,t)}function pf(e,t){let r=be(e,t);if(!iT.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function yn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function se(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 aT(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function he(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Jt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Kc(e,t){return Jt(e,t,(r,i)=>be(r,`${t}[${i}]`))}function Ri(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Nn(e,t){let r=be(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Jc(e,t,r=!1){let i=be(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 ct(e,t){let r=De(e,t);return Be(r,new Set(["text","truncated"]),t),{text:be(r.text,`${t}.text`,{empty:!0}),truncated:yn(r.truncated,`${t}.truncated`)}}function oT(e,t){let r=`Native spec_changes[${t}]`,i=De(e,r);Be(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=be(i.capability,`${r}.capability`);if(!tT.test(n))throw new Error(`${r}.capability is invalid`);let a=he(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Jc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Jc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:pf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function sT(e){let t="Native workspace",r=De(e,t);Be(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=he(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=df(r.change_branch,`${t}.change_branch`),a=df(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:he(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 cT(e){let t="Native loop",r=De(e,t);Be(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=Kc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ri(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:he(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:he(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:se(r.goal_cycle,`${t}.goal_cycle`,1),iteration:se(r.iteration,`${t}.iteration`),attempt:se(r.attempt,`${t}.attempt`),retry_epoch:se(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:se(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:se(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:se(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:df(r.next_action,`${t}.next_action`)}}function lT(e,t){let r=`Native acceptance[${t}]`,i=De(e,r);Be(i,new Set(["id","source","text","result","reason"]),r);let n=be(i.id,`${r}.id`);if(!rT.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Jc(i.source,`${r}.source`),text:be(i.text,`${r}.text`),result:he(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ct(i.reason,`${r}.reason`)}}function uT(e,t){let r=`Native builder_handoff.checks[${t}]`,i=De(e,r);return Be(i,new Set(["name","result","note"]),r),{name:ct(i.name,`${r}.name`),result:he(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ct(i.note,`${r}.note`)}}function dT(e){let t="Native builder_handoff",r=De(e,t);Be(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=Kc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ri(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:De(r.review,`${t}.review`);return n&&Be(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:be(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:be(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:ct(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:sf(r.acceptance_review)},checks:Jt(r.checks,`${t}.checks`,uT),checks_truncated:yn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Jt(r.known_limits,`${t}.known_limits`,(a,o)=>ct(a,`${t}.known_limits[${o}]`)),known_limits_truncated:yn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:he(n.status,["passed"],`${t}.review.status`),summary:ct(n.summary,`${t}.review.summary`),reviewer_execution_ref:be(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Nn(r.submitted_at,`${t}.submitted_at`)}}function pT(e,t){let r=`Native blockers[${t}]`,i=De(e,r);Be(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Kc(i.acceptance_ids,`${r}.acceptance_ids`);return Ri(n,`${r}.acceptance_ids`),{owner:he(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ct(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:he(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function fT(e,t){let r=`Native verification.checks[${t}]`,i=De(e,r);return Be(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:be(i.id,`${r}.id`),name:ct(i.name,`${r}.name`),argv_display:Jt(i.argv_display,`${r}.argv_display`,(n,a)=>ct(n,`${r}.argv_display[${a}]`)),argv_truncated:yn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Jc(i.cwd_ref,`${r}.cwd_ref`,!0),status:he(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:aT(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function hT(e){let t="Native verification",r=De(e,t);Be(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Jt(r.checks,`${t}.checks`,fT);Ri(i.map(a=>a.id),`${t}.checks IDs`);let n=be(r.identity_provider,`${t}.identity_provider`);return{candidate_id:be(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:be(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),attempt:se(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":he(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:he(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ct(r.summary,`${t}.summary`),risks:Jt(r.risks,`${t}.risks`,(a,o)=>ct(a,`${t}.risks[${o}]`)),risks_truncated:yn(r.risks_truncated,`${t}.risks_truncated`),completed_at:Nn(r.completed_at,`${t}.completed_at`)}}function Dy(e,t){let r=`Native history[${t}]`,i=De(e,r);Be(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Kc(i.unresolved_ids,`${r}.unresolved_ids`);return Ri(n,`${r}.unresolved_ids`),{goal_cycle:se(i.goal_cycle,`${r}.goal_cycle`,1),iteration:se(i.iteration,`${r}.iteration`),attempt:se(i.attempt,`${r}.attempt`),outcome:he(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ct(i.summary,`${r}.summary`),completed_at:Nn(i.completed_at,`${r}.completed_at`)}}function mT(e){let t="Native history_overflow.outcome_counts",r=De(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Be(r,new Set(i),t),{pass:se(r.pass,`${t}.pass`),fail:se(r.fail,`${t}.fail`),blocked:se(r.blocked,`${t}.blocked`),"execution-error":se(r["execution-error"],`${t}.execution-error`),recovery:se(r.recovery,`${t}.recovery`)}}function vT(e){let t="Native history_overflow",r=De(e,t);Be(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=se(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Nn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Nn(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=mT(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function gT(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&&cf(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 wT(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 ze(e){let t=De(e,"Native portable state");if(Be(t,nT,"Native portable state"),t.schema!==wn)throw new Error(`Native portable state schema must be ${wn}`);let r=be(t.name,"Native state name");if(!eT.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=Jt(t.spec_changes,"Native spec_changes",oT);Ri(i.map(s=>s.capability),"Native spec change capabilities");let n=Jt(t.acceptance,"Native acceptance",lT);Ri(n.map(s=>s.id),"Native acceptance IDs");let a=Jt(t.history,"Native history",Dy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:wn,name:r,language:he(t.language,["en","zh-CN"],"Native state language"),phase:he(t.phase,["shape","build","verify","archive"],"Native state phase"),status:he(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:se(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:pf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:pf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:he(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:sT(t.workspace),loop:cT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:dT(t.builder_handoff),blockers:Jt(t.blockers,"Native blockers",pT),verification:t.verification===null?null:hT(t.verification),history:a,history_overflow:vT(t.history_overflow),verification_result:he(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:he(t.verification_report,["verification.md"],"Native verification_report"),archived:yn(t.archived,"Native archived"),created_at:Nn(t.created_at,"Native created_at")};return gT(o),wT(o),o}function By(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ze({schema:wn,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:lf(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function oo(e,t){let r=ze(e),i=Dy(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 ze({...r,history:n,history_overflow:a})}function yT(e,t){let r=(0,Uc.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 Vr(e){let t=await ZI.readFile(e,"utf8");return ze(yT(t,"Native portable state"))}async function ff(e,t,r={}){let i=ze(t);await qt(e,(0,Uc.stringify)(i),r)}async function NT(e,t){let r=Gc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Gc.set(e,a),await r;try{return await t()}finally{i(),Gc.get(e)===a&&Gc.delete(e)}}async function Fy(e){return NT(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=ze(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Vr(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ao(t,i.state_version);return await ff(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Vr(e.file);if(n.state_version!==t)throw new ao(t,n.state_version)}}),r})}var Uc,eT,tT,rT,iT,nT,ao,Gc,xt=I(()=>{"use strict";Wc();Uc=ir(Bt(),1);oe();no();eT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rT=/^A[1-9][0-9]*$/u,iT=/^[a-f0-9]{64}$/u,nT=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ao=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Gc=new Map});var Pi=I(()=>{"use strict"});function CT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function RT(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 qy(e){let t=CT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!bT.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ly)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!ST.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!kT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!xT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!ET.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ly,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:RT(t.createdAt,"Native portable migration transaction createdAt")}}var Ly,bT,kT,ST,ET,xT,My=I(()=>{"use strict";qc();nf();xt();Pi();no();Qa();Ly="comet.native.portable-migration.v1",bT=new Set(["schema","id","change","fromSchema","status","createdAt"]),kT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ST=/^[a-z0-9][a-z0-9-]{7,127}$/u,ET=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),xT=new Set([ur,lr,Wt])});import PT from"node:path";function Jy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Uy(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 mf(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 Wy(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function HT(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Jy(e,r);if(Uy(i,OT,r),typeof i.capability!="string"||!Gy.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(p=>p==="."||p==="..")))throw new Error(`${r}.delta_source is invalid`);let o=mf(i.base_hash,`${r}.base_hash`),s=Wy(i.delta_content,`${r}.delta_content`),c=Wy(i.source_content,`${r}.source_content`),l=mf(i.expected_target_hash,`${r}.expected_target_hash`),u=mf(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let p=Gp(s);if(p.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(p.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Ya(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Ya(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(p=>p==="."||p===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Ya(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function DT(e){let t=Jy(e,"Native portable Archive transaction");if(Uy(t,$T,"Native portable Archive transaction"),t.schema!==Vy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!IT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Gy.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"||!TT.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"||!jT.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(HT);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:Vy,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 vf(e){let t=_T.exec(e);if(t)return{kind:"archive",change:t[1]};let r=AT.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Ky(e,t){let r=vf(t);if(!r)return null;let i=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=PT.join(e.transactionsDir,t);if(r.kind==="archive"){let s=DT(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=qy(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function Yy(e){return e.kind==="archive"||e.journal.status!=="committed"}var Vy,zy,_T,AT,IT,TT,jT,$T,OT,Gy,gf=I(()=>{"use strict";at();Jp();My();Vy="comet.native.archive-transaction.v4",zy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",_T=new RegExp(`^portable-archive-(${zy})\\.json$`,"u"),AT=new RegExp(`^portable-migration-(${zy})\\.json$`,"u"),IT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,TT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),$T=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),OT=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Gy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Xy}from"node:crypto";import{constants as Wr,promises as me}from"node:fs";import Ge from"node:path";import{TextDecoder as BT}from"node:util";function bn(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}function Qy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function FT(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Zy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function zr(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 Yc(e,t){let r=await me.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await me.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Xc(e,t,r){let i=Ge.resolve(e),n=Ge.resolve(t);if(!bn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Yc(i,r)],o=i;for(let s of Ge.relative(i,n).split(Ge.sep).filter(Boolean)){await Fe(a,r),o=Ge.join(o,s);let c=await Yc(o,r);if(!bn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Fe(a,r),a}async function Fe(e,t){for(let r of e){let i=await me.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!FT(r,i)||await me.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function LT(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 Gr(e){let t=e.maxBytes===null?null:Qy(e.maxBytes),r=Ge.resolve(e.file),i=await Xc(e.root,Ge.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Yc(Ge.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(i,e.label);let a=await me.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=Zy(a),s=await me.realpath(r);if(!bn(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>bn(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,l=await me.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,p]=await Promise.all([me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!zr(o,u)||!zr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await LT(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),me.lstat(r),me.realpath(r)]);if(await Fe(i,e.label),await Fe(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!zr(o,m)||!zr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:Xy("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function wf(e){let t=Ge.resolve(e.file),r=await Xc(e.root,Ge.dirname(t),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(l=>Yc(Ge.resolve(l),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Fe(r,e.label);let n=await me.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let a=Zy(n),o=await me.realpath(t);if(!bn(r[0].realPath,o))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(l=>bn(l.realPath,o)))throw new Error(`${e.label} resolves inside an excluded root`);let s=process.platform==="win32"?Wr.O_RDONLY:Wr.O_RDONLY|Wr.O_NOFOLLOW|Wr.O_NONBLOCK,c=await me.open(t,s);try{let l=await c.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!zr(a,l)||!zr(a,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=Xy("sha256"),f=0,m=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:b}=await c.read(m,0,m.length,null);if(b===0)break;f+=b,p.update(m.subarray(0,b))}await e.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([c.stat(),me.lstat(t),me.realpath(t)]);if(await Fe(r,e.label),await Fe(i,e.label),!v.isFile()||v.isSymbolicLink()||g!==o||!zr(a,h)||!zr(a,v))throw new Error(`${e.label} changed while reading`);return{hash:p.digest("hex"),size:f}}finally{await c.close()}}async function eN(e){let t=await Gr(e),r;try{r=new BT("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function co(e){let t=await Xc(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await me.readdir(e.directory,{withFileTypes:!0});else{let i=Qy(e.maxEntries);r=[];let n=await me.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Fe(t,e.label),{entries:r,verify:()=>Fe(t,e.label)}}async function yf(e){let t=await Xc(e.root,e.directory,e.label);return{verify:()=>Fe(t,e.label)}}var Ct=I(()=>{"use strict";oe();Lt()});import fr from"path";import{TextDecoder as MT}from"util";function Zc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function el(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 nN(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Nf(e,t){if(typeof e!="string"||e.length===0||fr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Qc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function tN(e,t){if(Nf(e,t),e.includes("\\")||e!==fr.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 UT(e,t){let r=Zc(e,`transaction operations[${t}]`);if(el(r,WT,`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`);Nf(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Nf(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 aN(e){let t=Zc(e,"Native Archive transaction journal");if(el(t,zT,"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"||!iN.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(!nN(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Qc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Zc(s,`Archive transaction operations[${c}]`);if(el(l,GT,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);tN(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&tN(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Qc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Qc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Qc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function KT(e){let t=Zc(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return aN(t);if(el(t,VT,"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"||!iN.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!fr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!fr.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(!nN(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(UT),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 YT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return fr.join(e.transactionsDir,t)}function oN(e,t){let r=YT(e,t);return{directory:r,journal:fr.join(r,"transaction.json"),events:fr.join(r,"events.jsonl"),staged:fr.join(r,"staged"),backups:fr.join(r,"backups")}}async function bf(e,t){let r=oN(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function kf(e,t,r={}){let i=await bf(e,t),n=await Gr({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(JT.decode(n.bytes)),o=KT(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var VT,WT,zT,GT,iN,JT,tl=I(()=>{"use strict";oe();K();Ct();VT=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),WT=new Set(["id","type","source","target","staged","backup"]),zT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),GT=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),iN=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),JT=new MT("utf-8",{fatal:!0})});import{promises as XT}from"fs";import QT from"path";async function ZT(e,t,r){let i;try{i=await XT.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 kf(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(vf(n.name))try{let a=await Ky(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Yy(a))return!0}catch{return!0}return!1}async function ej(e,t){let r=Date.now()+5e3,i=QT.join(e.locksDir,"root-move.lock");for(;;)try{return await Dc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await fy(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await hy(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 Ce(e,t,r,i){let n=await ej(e,t);try{if(await _c(e.projectRoot),await ZT(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Bc(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
173
+ `)}}}var Re=I(()=>{"use strict";Qe();Ka();gf();tl()});import{createHash as sN}from"crypto";import{createReadStream as tj}from"fs";async function Sf(e){let t=sN("sha256");for await(let r of tj(e))t.update(r);return t.digest("hex")}function ee(e){return sN("sha256").update(e).digest("hex")}var Ut=I(()=>{"use strict"});import{createHash as ol}from"crypto";import{spawn as gN}from"node:child_process";import{promises as ne}from"fs";import F from"path";import{performance as cN}from"node:perf_hooks";function yN(e){let t=e.deadlineMs??yj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Rt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return Rt(e)>=1}function Ef(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function En(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function Sj(e,t){let r={...kj,...t===void 0?{}:{maxNodes:t},...e};if(!Number.isSafeInteger(r.maxNodes)||r.maxNodes<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxPathBytes)||r.maxPathBytes<1||r.maxPathBytes>r.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return r}async function Ej(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&F.win32.isAbsolute(i)?F.win32.resolve(i):"C:\\Windows",a=F.win32.join(n,"System32","taskkill.exe");if(!F.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(p,f=!1)=>{c||(c=!0,u&&clearTimeout(u),f&&l?.kill("SIGKILL"),s(p))};try{l=gN(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",p=>d(p===0)),u=setTimeout(()=>d(!1,!0),Nj),u.unref()}catch{d(!1)}});for(let s=0;s<bj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Af(e,t,r,i){let n=Rt(e);if(n<1)throw Ef();let a=e.gitProcess,o=cN.now(),s=gN(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),c=null,l=!1,u=null;s.once("error",m=>{c=m});let d=new Promise(m=>{s.once("close",m)}),p=setTimeout(()=>{l=!0,u=Ej(s,a).then(()=>({error:null}),m=>({error:m}))},n);p.unref();let f=d.then(async m=>{if(clearTimeout(p),l){let h=await u;throw h?.error?Ef(h.error):Ef()}return{code:m,spawnError:c}}).finally(()=>cs(cN.now()-o));return{child:s,completion:f}}function NN(e,t){let r={..._f,...t===void 0?{}:{maxRecords:t},...e};if(!Number.isSafeInteger(r.maxRecords)||r.maxRecords<1||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<1||!Number.isSafeInteger(r.maxRecordBytes)||r.maxRecordBytes<1||r.maxRecordBytes>r.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return r}async function il(e,t,r,i=Rf){let{child:n,completion:a}=Af(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",f=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(f).subarray(0,m)),l+=f.byteLength,l>i&&(u=!0)}),n.stderr.on("data",f=>{if(c>=Cn)return;let m=Cn-c,h=Buffer.from(f).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:p}=await a;if(d===0&&p===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${p?`: ${p.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function xf(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function uo(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Af(e,t,r,i.stdin!==void 0),c=[],l=ol("sha256"),u=[],d=0,p=0,f=0,m=0,h=Buffer.alloc(0),v=!1,g=!1,b=!1,k=N=>{let x=0;for(;x<N.byteLength;){let w=N.indexOf(0,x),S=w<0?N.byteLength:w,E=N.subarray(x,S);if(!v&&E.byteLength>0&&(h.byteLength+E.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),v=!0,g=!0):h=Buffer.concat([h,E])),w<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let y=h.byteLength+1;!v&&m<=i.maxRecords&&f+y<=i.maxBytes?(c.push(h),f+=y):g=!0,h=Buffer.alloc(0),v=!1,x=w+1}};o.stdout.on("data",N=>{l.update(N),p+=N.byteLength,p>i.maxBytes&&(g=!0);let x=i.outputChunkBytes;if(x===void 0){k(N);return}for(let w=0;w<N.byteLength;w+=x)k(N.subarray(w,Math.min(N.byteLength,w+x)))}),o.stderr.on("data",N=>{if(d>=Cn)return;let x=Cn-d,w=Buffer.from(N).subarray(0,x);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:x})=>{let w=i.acceptedExitCodes??[0];if(N!==null&&w.includes(N)&&x===null&&!b&&h.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:p});return}a(new Error(`git ${r.join(" ")} failed${x?`: ${x.message}`:b||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function nl(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function xj(e,t,r){if(r.length===0)return new Set;let i=await uo(e,t,["check-ignore","--no-index","-z","--stdin"],{..._f,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=nl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function Cj(e,t,r){let{child:i,completion:n}=Af(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=Cn)return;let d=Cn-o,p=Buffer.from(u).subarray(0,d);a.push(p),o+=p.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function xn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function Rj(e,t){return e.map(r=>{let i=xn(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function Pj(e){let t=F.resolve(e);for(;;){try{return await ne.lstat(F.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=F.dirname(t);if(r===t)return!1;t=r}}function _j(e){return e?e.filter(t=>t&&!t.startsWith("!")).flatMap(t=>t.includes("**")?[`:(exclude,glob)${t}`]:[`:(exclude)${t}`]):[]}async function bN(e,t,r,i={},n){let a=F.resolve(t.projectRoot),o=F.join(a,".comet","current-change.json"),c=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,o].map(f=>{let m=F.relative(a,F.resolve(f)).replaceAll("\\","/"),h=xn(m);if(h===null)throw new Error("Native Git snapshot exclusion escaped the project root");return h}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`]),..._j(n)],l={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},u=await uo(e,a,["ls-files","--stage","-z",...c],l);await i.afterStageBefore?.();let d=await uo(e,a,["ls-files","--cached","--others","--exclude-standard","-z",...c],l);await i.afterCombined?.();let p=await uo(e,a,["ls-files","--stage","-z",...c],l);return{stagedBefore:u,combined:d,stagedAfter:p}}function kN(e){return{stageBefore:xf(e.stagedBefore),combined:xf(e.combined),stageAfter:xf(e.stagedAfter)}}async function SN(e,t,r=_f,i={},n){let a=F.resolve(t.projectRoot);if(!await Pj(a))return null;let o;try{o=await il(e,a,["rev-parse","--is-inside-work-tree"])}catch(k){throw En(k)?k:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:k})}if(o.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let s;try{s=await bN(e,t,r,i,n)}catch(k){throw En(k)?k:new Error("Native Git snapshot provider failed after repository detection",{cause:k})}let{stagedBefore:c,combined:l,stagedAfter:u}=s,d=new Set,p=new Map,f=new Set,m=k=>{for(let N of k){let x=nl(N),w=x.indexOf(" ");if(w<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(x.slice(0,w))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let E=xn(x.slice(w+1));if(E===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");d.add(E),S.stage==="0"&&p.set(E,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(E)}};m(c.records),m(u.records);let h=l.records.map(nl),v=Rj(h,"combined"),g=new Set(v.filter(k=>!d.has(k))),b=new Set(v.filter((k,N)=>!d.has(k)&&h[N].endsWith("/")));for(let k of f)b.delete(k);return{tracked:d,trackedObjectIds:p,untracked:g,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:kN(s)}}function Ur(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function lN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function Aj(e,t){return!Ur(e.stageBefore,e.stageAfter)||!Ur(e.stageAfter,t.stageBefore)||!Ur(e.combined,t.combined)||!Ur(t.stageBefore,t.stageAfter)}async function EN(e,t,r,i,n,a){let o;try{o=await bN(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}},a)}catch(d){throw En(d)?d:new Error("Native Git snapshot provider failed during its final selection fence",{cause:d})}let s=i.initialFence,c=kN(o),l=lN(s)||lN(c),u=Aj(s,c);l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),u&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=l||u?{schema:"comet.native.git-selection.v1",status:l&&u?"overflow-and-changed":l?"overflow":"changed",...s,finalStageBefore:c.stageBefore,finalCombined:c.combined,finalStageAfter:c.stageAfter}:null,(s.combined.overflow||c.combined.overflow)&&(i.overflow={count:Math.max(1,s.combined.recordCount-s.combined.storedRecordCount,c.combined.recordCount-c.combined.storedRecordCount),hash:ee(`comet.native.git-selection-overflow.v2
174
+ ${JSON.stringify({initial:s.combined,final:c.combined})}`)})}function Tj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function uN(e){let t=F.resolve(e.paths.projectRoot),r=F.resolve(e.paths.nativeRoot),i=F.resolve(e.paths.runtimeDir),n=F.resolve(e.paths.configFile),a=F.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,p=0,f=!1,m=!1,h=!1,v=()=>Rt(e.execution)>=1?!0:(f=!0,h=!0,!1),g=N=>{let x=Buffer.from(`${N.type}\0${N.path}`,"utf8"),w=ol("sha256").update("comet.native.physical-selection-record.v1\0").update(x).digest();for(let S=0;S<c.length;S+=1)c[S]^=w[S];if(l=l+BigInt(`0x${w.toString("hex")}`)&Ij,d+=1,p+=x.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||p>e.limits.maxBytes){f=!0,h=!0;return}o.push(N)},b=async N=>{if(h||!v())return;let x;try{x=await ne.opendir(N)}catch(C){if(!v())return;if(!ge(C)&&!ve(C)||N===t&&ge(C))throw C;m||=ve(C),f||=ge(C),h=!0;return}if(!v()){try{await x.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let w=!1,S;try{for(;!h&&v();){let C;try{C=await x.read()}catch(Z){if(!v())break;if(!ge(Z)&&!ve(Z)||N===t&&ge(Z))throw Z;m||=ve(Z),f||=ge(Z),h=!0;break}if(!v()||C===null)break;if(u+=1,u>e.limits.maxNodes){f=!0,h=!0;break}let O=F.join(N,C.name),T=$j(t,O);if(O===n||O===a||Pt(r,O)||Pt(i,O)||e.denylist.some(Z=>Pt(Z,O))||Ft(T)!==null)continue;if(!v())break;let Q;try{Q=await ne.lstat(O)}catch(Z){if(!v())break;if(!ge(Z)&&!ve(Z))throw Z;if(m=!0,g({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:ge(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!v())break;continue}if(!v())break;let Te=Tj(Q);if(Te==="directory"){if(Bj(e.policy,T))continue;if(!v())break;let Z;try{Z=await ne.realpath(O)}catch(Ot){if(!v())break;if(!ge(Ot)&&!ve(Ot))throw Ot;if(m=!0,g({path:T,type:Te}),s.push({path:T,size:null,type:"directory",reason:ge(Ot)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!v())break;continue}if(!v())break;if(!q(e.physicalProjectRoot,Z)||Pt(e.physicalNativeRoot,Z))continue;if(g({path:T,type:Te}),await e.hooks?.afterNode?.(T),!v()||(await b(O),h))break;continue}if(g({path:T,type:Te}),await e.hooks?.afterNode?.(T),!v()||h)break}}catch(C){w=!0,S=C}let E;try{await x.close()}catch(C){E=C}let y=v();if(w)throw S;if(y&&E!==void 0&&E.code!=="ERR_DIR_CLOSED")throw E};await b(t),v(),f?(o.length=0,d=0,p=0):(o.sort((N,x)=>N.path.localeCompare(x.path,"en")),s.sort((N,x)=>N.path.localeCompare(x.path,"en")));let k=f?ee(`comet.native.physical-selection-incomplete.v1
175
+ ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):ee(`comet.native.physical-selection.v1
176
+ ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:p,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:k,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:p,overflow:f,unstable:m}}}function xN(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function jj(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!xN(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function CN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function dN(e,t){let i=(await il(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!wN.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return ee(`gitlink:${i}`)}async function pN(e,t){let r=await dN(e,t),i=await Cj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await dN(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function lo(e,t){if(Ft(t)!==null)return!1;let r=F.resolve(e.projectRoot,...t.split("/"));return!Pt(F.resolve(e.nativeRoot),r)&&!Pt(F.resolve(e.runtimeDir),r)}function $j(e,t){return F.relative(e,t).split(F.sep).join("/")}function Oj(e,t){return t.map(r=>F.resolve(e,...r.split(/[\\/]/u)))}function Pt(e,t){let r=F.resolve(e),i=F.resolve(t);return i===r||q(r,i)}function ge(e){return wj.has(e.code??"")}function ve(e){return e.code==="ENOENT"}function Hj(e,t){return ee(`comet.native.snapshot-policy.v1
177
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Cf(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function Dj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function fN(e){let t=Pc(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?Dj(n):void 0;if(a&&!a())return!1;let o=Cf(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Cf(r,c,a),o===null||o.size===0)return!1}return Cf(r,o,a)?.has(r.length)??!1}}function RN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Pc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Pc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=Hj(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(fN),excludeMatchers:r.map(fN),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Bj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function hN(e,t,r){if(!e)return!0;let i=()=>H(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function al(e,t,r){let i=JSON.stringify(r);return ee(`${e}
161
178
  ${Buffer.byteLength(t)}:${t}
162
- ${Buffer.byteLength(i)}:${i}`)}function oy(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function sy(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!oy(r))return e.splice(t,1),r}return null}function Hr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function JI(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await re.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=bc("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Hr(r,c))return{status:"changed"};for(;;){if(!H(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Hr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function it(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function an(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Bt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function cy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function GI(e,t){let r=it(e,`Native snapshot entry ${t}`);nt(r,yI,`Native snapshot entry ${t}`);let i=cy(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!kc.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Bt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Yw.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function UI(e,t){let r=it(e,`Native snapshot omission ${t}`);if(nt(r,NI,`Native snapshot omission ${t}`),!SI.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!EI.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:cy(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Bt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function KI(e){let t=it(e,"Native snapshot omission overflow");if(nt(t,bI,"Native snapshot omission overflow"),typeof t.hash!="string"||!kc.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:an(t.count,"Native snapshot omission overflow count")}}function nn(e,t){let r=it(e,t);if(nt(r,vI,t),typeof r.hash!="string"||!kc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Bt(r.recordCount,`${t} recordCount`),n=Bt(r.storedRecordCount,`${t} storedRecordCount`),a=Bt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Gw(e){let t=it(e,"Native Git selection evidence");if(nt(t,mI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=nn(t.stageBefore,"Native Git selection stageBefore"),i=nn(t.combined,"Native Git selection combined"),n=nn(t.stageAfter,"Native Git selection stageAfter"),a=nn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=nn(t.finalCombined,"Native Git selection finalCombined"),s=nn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Dr(r,n)||!Dr(n,a)||!Dr(i,o)||!Dr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Uw(e,t){let r=it(e,t);if(nt(r,wI,t),typeof r.hash!="string"||!kc.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Bt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Bt(r.recordCount,`${t} recordCount`),a=Bt(r.storedRecordCount,`${t} storedRecordCount`),o=Bt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function YI(e){let t=it(e,"Native physical selection evidence");if(nt(t,gI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Uw(t.before,"Native physical selection before"),i=Uw(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!iy(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function mi(e){let t=it(e,"Native content snapshot manifest");if(nt(t,uI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!kI.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=it(t.capture,"Native content snapshot capture");if(nt(w,pI,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let k=w.gitSelection===void 0?void 0:Gw(w.gitSelection),E=w.physicalSelection===void 0?void 0:YI(w.physicalSelection),y=null;if(w.projection!==void 0){let C=it(w.projection,"Native content snapshot projection");if(nt(C,hI,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:Gw(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...k?{gitSelection:k}:{}}}else{if(k)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=it(t.limits,"Native content snapshot limits");nt(i,dI,"Native content snapshot limits");let n={maxFiles:an(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:an(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:an(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:an(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:an(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=it(t.policy,"Native snapshot policy");if(nt(w,fI,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=ay({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(GI),s=t.omitted.map(UI),c=Bt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:KI(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,k)=>w+k.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>jf||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(S!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function ly(e,t,r={}){let i=mi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=Xw(r),o=Qw(r.gitSelectionLimits),s=await ty(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(ny(s).filter(k=>Oa(e,k))),l=[...s.gitlinks].filter(k=>c.has(k)),u=[...s.nestedRepositories].filter(k=>Oa(e,k)),d=(k,E)=>E.some(y=>k===y||k.startsWith(`${y}/`)),f=k=>d(k,l),p=k=>d(k,u),m=[...i.entries.map(k=>k.path),...i.omitted.flatMap(k=>k.type==="directory"?[k.path,`${k.path}/`]:[k.path])].filter(k=>!c.has(k)&&!f(k)&&!p(k)),h=await jI(a,n,m),v=i.entries.filter(k=>!f(k.path)&&!p(k.path)&&Oa(e,k.path)&&(c.has(k.path)||!h.has(k.path)));await ry(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let k of l)g.push({path:k,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((k,E)=>k.path.localeCompare(E.path,"en"));let b=i.omitted.filter(k=>f(k.path)||p(k.path)||!Oa(e,k.path)?!1:h.has(k.path)?c.has(k.path)||[...c].some(E=>E.startsWith(`${k.path}/`)):!0);for(let k of g)b.some(E=>E.path===k.path&&E.reason===k.reason)||b.push(k);b.sort((k,E)=>k.path.localeCompare(E.path,"en"));let S=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??Q("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,N=Nc(N,"git-selection",{source:"git-selection",...s.overflow}));let x=k=>{S+=1,N=Nc(N,"omission",k)};for(;b.length>jf;){let k=sy(b);if(k===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(k)}return mi({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+S===0,entries:v,omitted:b,omittedCount:b.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:S}}:{}})}function XI(e,t){if(!lI.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(K(e,t),"baseline-manifest.json")}async function uy(e,t={}){let r={maxFiles:t.limits?.maxFiles??gc.maxFiles,maxFileBytes:t.limits?.maxFileBytes??gc.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??gc.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??gc.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=ay(t.policy),n=Xw({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Qw(t.gitSelectionLimits,t.maxSelectionRecords),o=AI(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await re.realpath(s),l=F.resolve(e.nativeRoot),u=await re.realpath(l),d=F.resolve(e.runtimeDir),f=F.resolve(e.configFile),p=F.join(s,".comet","current-change.json"),m=VI(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,S=0,N=0,x=Q("comet.native.snapshot-omission-overflow.v1"),w=0,k=!1,E=null,y=_=>{N+=1,x=Nc(x,"omission",_)},C=_=>{if(S+=1,v.length<jf){v.push(_);return}if(oy(_)){let A=sy(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{S+=_.count,N+=_.count,x=Nc(x,"git-selection",{source:"git-selection",..._})},j=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),k||(k=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Y=(_,A)=>{let $=h.findIndex(Z=>Z.path===_);if($<0)return;let[M]=h.splice($,1);w-=M.size,g.delete(_),C(A)},Re=async(_,A,$,M)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let Z;try{Z=await re.realpath(_)}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;C({path:A,size:$.size,type:"file",reason:he(R)?"changed-during-read":"unreadable"});return}if(!H(n)||!B(c,Z)||bt(u,Z))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let J,D,oe;try{if(J=await JI(Z,$.size,$,n),J.status==="budget-exhausted"||!H(n))return;if(J.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(oe=await re.realpath(_),!H(n)))return;D=await re.lstat(_)}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;C({path:A,size:$.size,type:"file",reason:he(R)?"changed-during-read":"unreadable"});return}if(H(n)){if(J.bytes!==$.size||oe!==Z||!Hr($,J.finalStat)||!Hr(J.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await j({path:A,hash:J.hash,size:D.size,type:"file",...M===void 0?{}:{gitObjectId:M}},{kind:"file",target:_,realTarget:Z,stat:D})}},X=async(_,A,$)=>{if(!H(n))return;let M,Z,J;try{if(M=await re.readlink(_,{encoding:"buffer"}),!H(n)||(J=await re.lstat(_),!H(n)))return;Z=await re.readlink(_,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;C({path:A,size:null,type:"other",reason:he(R)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!J.isSymbolicLink()||!Hr($,J)||J.mtimeMs!==$.mtimeMs||J.ctimeMs!==$.ctimeMs||!M.equals(Z)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=M.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let oe=bc("sha256").update("symlink\0").update(M).digest("hex");H(n)&&await j({path:A,hash:oe,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:M,stat:J})},Rt=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,oe;try{if(D=await re.realpath(A.target),!H(n))return;oe=await re.lstat(A.target)}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;Y(_,{path:_,size:null,type:"file",reason:me(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!oe.isFile()||oe.isSymbolicLink()||!Hr(A.stat,oe)||oe.size!==A.stat.size||oe.mtimeMs!==A.stat.mtimeMs||oe.ctimeMs!==A.stat.ctimeMs)&&Y(_,{path:_,size:oe.isFile()?oe.size:null,type:oe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,oe;try{if(D=await re.lstat(A.target),!H(n))return;oe=await re.readlink(A.target,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!me(R)&&!he(R))throw R;Y(_,{path:_,size:null,type:"other",reason:me(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Hr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(oe))&&Y(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,M;try{if($=await re.realpath(A.target),!H(n))return;M=await re.lstat(A.target)}catch{if(!H(n))return;Y(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&M.isDirectory()&&!M.isSymbolicLink()&&Hr(A.stat,M)&&B(c,$)&&!bt(u,$))){Y(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!H(n))return;J=await Ww(n,$)}catch(D){if(on(D))throw D;Y(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;J.dirty?Y(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Y(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await re.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(he($))continue;if(!me($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},ae=await ty(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(ae===null){let _=await Vw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let M of _.records){if(M.type!=="file"&&M.type!=="symlink"||g.has(M.path))continue;if(Nt(n)<1)break;if(!Jw(i,M.path,n))continue;if(Nt(n)<1)break;let Z=F.resolve(s,...M.path.split("/")),J;try{J=await re.lstat(Z)}catch(D){if(!H(n))break;if(!me(D)&&!he(D))throw D;C({path:M.path,size:null,type:"file",reason:he(D)?"changed-during-read":"unreadable"});continue}if(Nt(n)<1)break;if(M.type==="symlink"&&J.isSymbolicLink()){if(await X(Z,M.path,J),Nt(n)<1)break;continue}if(M.type!=="file"||!J.isFile()||J.isSymbolicLink()){C({path:M.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Re(Z,M.path,J),Nt(n)<1)break}Nt(n)>=1&&await Rt();let A=await Vw({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=LI(_.evidence,A.evidence);E=$.evidence;for(let M of[..._.omissions,...A.omissions,...$.omissions])v.some(Z=>Z.path===M.path&&Z.reason===M.reason)||C(M)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let R=mi(_);for(let ie of R.entries)ie.gitObjectId!==void 0&&A.set(ie.path,ie);$=A.size>0}let M=new Set,Z=!0;try{let R=await Ha(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)$=!1,Z=!1,A.clear();else for(let ie of R.records){let se=yc(ie),_e=se.indexOf(" "),xe=_e<0?null:sn(se.slice(_e+1));if(_e!==1||xe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");se[0]!=="H"&&M.add(xe)}}catch(R){if(on(R))throw R;$=!1,Z=!1,A.clear()}let J=new Set;try{let R=await wc(n,s,["ls-files","--modified","-z"],If);for(let ie of R.toString("utf8").split("\0")){let se=sn(ie);se!==null&&J.add(se)}}catch{$=!1,Z=!1,A.clear()}let D=new Set,oe=new Set;for(let R of ny(ae)){if(g.has(R)||!Oa(e,R))continue;if(Nt(n)<1)break;if(!Jw(i,R,n))continue;if(Nt(n)<1)break;let ie=F.resolve(s,...R.split("/"));if(ie===f||ie===p||bt(d,ie)||m.some(ze=>bt(ze,ie)))continue;if(ae.gitlinks.has(R)){if(h.length>=r.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let ze,Eo;try{[ze,Eo]=await Promise.all([re.realpath(ie),re.lstat(ie)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Eo.isSymbolicLink()||!Eo.isDirectory()||!B(c,ze)||bt(u,ze)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let _i=await Ww(n,ze);if(_i.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await j({path:R,hash:_i.hash,size:0,type:"file"},{kind:"gitlink",target:ie,realTarget:ze,stat:Eo,hash:_i.hash})}catch(_i){if(on(_i))throw _i;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let se;try{se=await re.lstat(ie)}catch(ze){if(he(ze)&&ae.tracked.has(R)){b.set(R,ie);continue}if(!me(ze)&&!he(ze))throw ze;C({path:R,size:null,type:"file",reason:he(ze)?"changed-during-read":"unreadable"});continue}if(se.isSymbolicLink()){await X(ie,R,se);continue}if(!se.isFile()){ae.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let _e=ae.trackedObjectIds.get(R),xe=_e?A.get(R):void 0;if($&&xe?.gitObjectId!==void 0&&xe.gitObjectId===_e&&!M.has(R)&&!J.has(R)){if(h.length>=r.maxFiles){C({path:R,size:xe.size,type:"file",reason:"file-count"});continue}if(xe.size>r.maxFileBytes){C({path:R,size:xe.size,type:"file",reason:"file-size"});continue}if(w+xe.size>r.maxTotalBytes){C({path:R,size:xe.size,type:"file",reason:"total-size"});continue}h.push({...xe}),w+=xe.size,D.add(R);continue}let bh=Z&&!M.has(R)&&!J.has(R)?_e:void 0;await Re(ie,R,se,bh),bh!==void 0&&oe.add(R)}if(await Rt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await ry(n,e,a,ae,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&oe.size>0){let R=await wc(n,s,["ls-files","--modified","-z"],If),ie=new Set;for(let se of R.toString("utf8").split("\0")){let _e=sn(se);_e!==null&&ie.add(_e)}for(let se of D){if(!ie.has(se))continue;let _e=h.find(xe=>xe.path===se);Y(se,{path:se,size:_e?.size??null,type:"file",reason:"changed-during-read"})}for(let se of oe){if(!ie.has(se))continue;let _e=h.find(xe=>xe.path===se);_e&&delete _e.gitObjectId}}for(let R of ae.omissions)C(R);ae.overflow&&O(ae.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let dS=ae===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ae.evidence?{gitSelection:ae.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:dS,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:S,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function Of(e,t,r={}){let n=(await ke(e.projectRoot))?.native.snapshot??Fd;return uy(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Sc(e,t){let r=XI(e,t),i=we(e,r);await V(i,r);try{let n=await Tw({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return mi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var gc,jf,lI,uI,dI,fI,pI,hI,mI,vI,gI,wI,yI,NI,bI,kI,SI,EI,kc,Yw,xI,cn,If,CI,PI,RI,Tf,_I,qI,ln=I(()=>{"use strict";le();Ge();Lt();Tt();U();yt();ua();gc={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},jf=1e3,lI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),dI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),fI=new Set(["schema","include","exclude","hash"]),pI=new Set(["provider","gitSelection","physicalSelection","projection"]),hI=new Set(["provider","selection"]),mI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),vI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),gI=new Set(["schema","status","before","after"]),wI=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),yI=new Set(["path","hash","size","type","gitObjectId"]),NI=new Set(["path","size","type","reason"]),bI=new Set(["ref","hash","count"]),kI=new Set(["change-created","legacy-migration","explicit"]),SI=new Set(["file","directory","other"]),EI=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),kc=/^[a-f0-9]{64}$/u,Yw=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,xI=new Set(["EACCES","EPERM"]),cn=64*1024,If=64*1024,CI=6e4,PI=1e3,RI=2,Tf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},_I={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};qI=(1n<<256n)-1n});function Xy(){Xj+=1}var Xj,Qy=I(()=>{"use strict";Xj=0});import{execFileSync as Qj}from"node:child_process";function tT(e,t){Xy();try{return Qj("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Zj,maxBuffer:eT,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Kf(e,t,i)}}function Ue(e,t){return tT(e,t).trim()}var Zj,eT,Kf,Et=I(()=>{"use strict";Qy();Zj=3e4,eT=8*1024*1024,Kf=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 uT}from"node:fs";import dT from"node:path";function Mc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Vc(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 aN(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 gT(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 oN(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function uN(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===tp&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!sN(e.children,l)),cN(i)?i:null}if(e.schema===wi&&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=>!sN(e.children,a)),cN(i)?i:null}return null}function sN(e,t){return e.some(r=>r.covers.includes(t))}function cN(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Br(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 wT(e){let t=Mc(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=Mc(n,`Native children acceptance_index.${i}`);if(Vc(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 yT(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function dN(e,t,r={}){let i=(0,lN.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Mc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==wi&&a!==Lr)throw Vc(n,nN,"Native children contract"),new Error(`Native children schema must be ${wi} or ${Lr}`);let o=a===wi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Vc(n,o==="indexed-v2"?pT:nN,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let m=Mc(f,`Native child ${p}`);if(Vc(m,o==="indexed-v2"?vT:o==="summary-v2"?mT:hT,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!fT.test(m.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:aN(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?aN(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(m=>!u.has(m));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}gT(c);let d=r.policy==="advisory";if(a===tp){if(o==="indexed-v2"){let f=wT(n.acceptance_index);d||yT(f,t,r);let p=Object.keys(f);return d||oN(c,p,p),{schema:Lr,acceptance_index:f,children:c}}return{schema:Lr,children:c}}return t&&!d&&oN(c,t),{schema:wi,children:c}}async function Mt(e){let t=dT.join(e.changeDir,ep);try{await uT.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ee({root:e.changeDir,ref:ep}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=dN(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?uN(a,e.acceptanceIds,e.validation??{}):null}}var lN,ep,wi,Lr,tp,fT,nN,pT,hT,mT,vT,Wc=I(()=>{"use strict";lN=Gt(It(),1);et();ep="children.yaml",wi="comet.native.children.v1",Lr="comet.native.children.v2",tp=Lr,fT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nN=new Set(["schema","children"]),pT=new Set(["schema","acceptance_index","children"]),hT=new Set(["name","depends_on","covers"]),mT=new Set(["name","summary","depends_on"]),vT=new Set(["name","depends_on","covers"])});var zc,rp=I(()=>{"use strict";zc=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 Ua=I(()=>{"use strict"});var Jc=I(()=>{"use strict";rp();Ua()});function or(e,t){if(!bT.test(e))throw new Error(`${t} must be a Git commit`)}function ip(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Uc(e){or(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:np(e.contract,i.name),contractHash:T("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:Ka,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 np(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 Kc(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 bT,Ka,Gc,yi=I(()=>{"use strict";ce();Jc();bT=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Ka="comet.native.supervisor.v2",Gc=3});import Ya from"node:path";import{promises as pN}from"node:fs";function ap(e,t){return Ya.join(vt(e,t),"supervisor")}function Xa(e,t){return Ya.join(ap(e,t),"state.json")}function hN(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!==Ka)throw new Error(`Native Supervisor state schema must be ${Ka}`);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(or(t.integration.targetCommit,"Native Supervisor target commit"),or(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");or(n.candidateCommit,"Native Supervisor integration candidate commit"),or(n.integrationCommit,"Native Supervisor integration check commit"),fN(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&&or(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(or(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&&fN(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 Ke(e,t,r={}){try{let i=await pN.readFile(Xa(e,t),"utf8"),n=JSON.parse(i);if(hN(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(()=>(wt(),wf)),c=await s(Ya.join(o.changesDir,t,"comet-state.yaml")),l=await Mt({changeDir:Ya.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Br(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=np(l.contract,u.name),u.contractHash=T("comet.native.supervisor-contract.v1",l.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(()=>(wt(),wf)),s=await o(Ya.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 Vr(e,t){hN(t),await pN.mkdir(e.changesRuntimeDir,{recursive:!0}),await Fe(Xa(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function fN(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 Mr=I(()=>{"use strict";le();ce();Wc();U();yi()});var op=I(()=>{"use strict"});function st(e){return e.replace(kT,"$1 [REDACTED]").replace(ST,"[REDACTED PRIVATE KEY]").replace(ET,"$1[REDACTED]@").replace(xT,"[REDACTED TOKEN]").replace(CT,'$1"[REDACTED]"').replace(PT,"$1$2$1$3$4[REDACTED]$4").replace(RT,"$1$2[REDACTED]")}var kT,ST,ET,xT,CT,PT,RT,Ni=I(()=>{"use strict";kT=/\b(Bearer|Basic)\s+[^\s"']+/giu,ST=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,ET=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,xT=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,CT=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,PT=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,RT=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{accessSync as NW,constants as bW,createWriteStream as kW,existsSync as SW,promises as EW,statSync as IT}from"node:fs";import bi from"node:path";function jT(e,t){let r=bi.relative(e,t);return r===""||!bi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${bi.sep}`)}function mN(e,t){if(t.length===0||t.includes("\\")||bi.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||bi.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=bi.resolve(e),i=bi.resolve(r,...t.split("/"));if(!jT(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=IT(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Yc=I(()=>{"use strict";Js();op();Ni()});var vN=I(()=>{"use strict";Et();Yc();ce()});var Xc=I(()=>{"use strict";Et();le()});import{createHash as _N}from"node:crypto";import kN from"path";function Ce(e,t){return e<t?-1:e>t?1:0}function fp(e){if(!mp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function s$(e,t){return e===t?0:e===null?-1:t===null?1:Ce(e,t)}function zr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=kN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||kN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function jN(e,t){return e==="."?e:zr(e,t)}function wn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function c$(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:zr(e.path,`${t} path`),hash:e.hash,size:wn(e.size,`${t} size`),type:"file"}}function l$(e,t){return{path:jN(e.path,`${t} path`),size:e.size===null?null:wn(e.size,`${t} size`),type:e.type,reason:e.reason}}function u$(e,t){return Ce(e.path,t.path)||Ce(e.hash,t.hash)||e.size-t.size}function d$(e,t){return Ce(e.path,t.path)||Ce(e.reason,t.reason)||Ce(e.type,t.type)||(e.size??-1)-(t.size??-1)}function to(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
163
- `,"utf8")}function Wr(e,t,r){let i=`${t}
164
- ${Tn(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function f$(e){if(to(e)<=Si)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=_N("sha256");a.update(`${n$}
165
- `),e.omissionOverflow&&Wr(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(i+=1),n+=1,Wr(a,"omission",f)},s=f=>{i+=1,n+=1,Wr(a,"entry",f)},c=()=>{for(let f=r.length-1;f>=0;f-=1){let p=r[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return r.splice(f,1),p}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;to(u)>Si;){if(r.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(r.length/4));for(let m=0;m<p;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function pp(e){let t=mi(e),r=t.entries.map((n,a)=>c$(n,`Snapshot entry ${a}`));if(r.sort(u$),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>l$(n,`Snapshot omission ${a}`));return i.sort(d$),f$({schema:AN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function ro(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:zr(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>Ce(r.path,i.path)||Ce(r.kind,i.kind))}function io(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function SN(e){return e?{hash:e.hash,size:e.size}:null}function vp(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ce(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:SN(c),after:SN(l)})}}function TN(e,t){return{...e,attributedTo:t.filter(r=>io(r,e.path))}}function gp(e){let t=ro(e.declaredArtifacts),r=[];return vp(e.baseline,e.current,i=>{r.push(TN(i,t))}),r}function sr(e,t){return{id:`scope:${T(r$,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function p$(e,t){let r=t.omitted.map(i=>sr({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(sr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(sr({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function EN(e,t){return p$(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function hp(e,t){return Ce(e.kind,t.kind)||Ce(e.source,t.source)||s$(e.path,t.path)||Ce(e.id,t.id)}function h$(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(hp)}function $N(e){return[...new Set(e.map((t,r)=>zr(t,`Git path ${r}`)))].sort(Ce)}function xN(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function m$(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function ON(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=$N(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:xN(e.baseCommit,"Native external drift base commit"),targetBranch:m$(e.targetBranch,"Native external drift target branch"),targetCommit:xN(e.targetCommit,"Native external drift target commit"),paths:t}}function HN(e){if(typeof e.contractHash!="string"||!mp.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ro(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:$N(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:ON(e.externalDrift)}}}function v$(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,f=0;return vp(e,t,p=>{let m=r.some(h=>io(h,p.path));if(d+=1,c.push(p.path),!m&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<a$){let h=TN(p,r),v=to(h);l+v<=Si?(a.push(h),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function DN(e,t){return sr({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function g$(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:wn(Number(t[1]),"Scope overflow change count"),unresolved:wn(Number(t[2]),"Scope overflow unresolved count"),unattributed:wn(Number(t[3]),"Scope overflow unattributed count")},i=ki(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(DN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function w$(e){let t=_N("sha256");t.update(`${i$}
166
- `);let r=0;vp(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Wr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)io(o,n.path)&&(a+=1,Wr(t,"change-attribution",o));Wr(t,"change-end",{attributionCount:a}),a===0&&Wr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Wr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function qN(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=v$(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let k=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>io(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(k.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(Za,e),c=T(Za,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[k,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=o$)break;l.push(sr({kind:"snapshot-omission",source:k,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${k} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...EN("baseline",e),...EN("current",t),...o.totalChanges===0&&a===null?[sr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(r.gitChangedPaths===void 0)return;let k=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>k.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!k.has(E))}},m=k=>{let E=o.candidates.slice(0,k.detailedChangeCount),y=E.filter(ae=>ae.attributedTo.length===0&&!u.has(ae.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,j=d-k.detailedOmissionCount,Y=O+j,Re=[...y.map(ae=>sr({kind:"unattributed-change",source:"implementation-scope",path:ae.path,evidence:{after:ae.after,before:ae.before,changeKind:ae.kind}},`Changed path is not covered by a declared artifact: ${ae.path}`)),...l.slice(0,k.detailedOmissionCount),...f,...Y>0?[DN(k.overflowHash,{changes:C,unattributed:O,unresolved:Y})]:[]],X=h$(Re),Rt=k.includeGitAdvisory?p():void 0;return{schema:dp,contractHash:i,baselineProjectionRef:fp(s),baselineProjectionHash:s,currentProjectionRef:fp(c),currentProjectionHash:c,complete:X.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:X,noCodeReason:a,...Rt?{gitAdvisory:Rt}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let k=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if(to({...k,scopeHash:b})<=Si)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?w$({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:T(IN,x)};if(to(w)>Si)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function wp(e){let t=pp(e.baseline),r=pp(e.current),i=HN(e);return{authority:i,baseline:t,current:r,scope:qN(t,r,i)}}function Wt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zt(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function ki(e,t){if(typeof e!="string"||!mp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function CN(e,t,r){let i=fp(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function el(e,t){let r=Wt(e,"Native snapshot projection");if(zt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==AN)throw new Error("Native snapshot projection schema is invalid");let i=mi({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=pp(i);if(T(Za,r)!==T(Za,n))throw new Error("Native snapshot projection is not canonical");let a=T(Za,n);if(t!==void 0&&ki(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function yp(e,t){let r=Wt(e,`Declared artifact ${t}`);if(zt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:zr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function PN(e,t){if(e===null)return null;let r=Wt(e,t);return zt(r,["hash","size"],[],t),{hash:ki(r.hash,`${t} hash`),size:wn(r.size,`${t} size`)}}function RN(e,t){let r=Wt(e,`Implementation change ${t}`);if(zt(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(yp),n=ro(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=PN(r.before,`Implementation change ${t} before`),o=PN(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:zr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function N$(e,t){let r=Wt(e,`Unresolved scope ${t}`);zt(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?jN(r.path,`Unresolved scope ${t} path`):zr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function eo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>zr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ce);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function FN(e){let t=Wt(e,"Native implementation external drift");if(zt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=eo(t.paths,"Native external drift paths");return ON({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function tl(e){let t=Wt(e,"Native implementation scope"),r=[...y$].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(zt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==dp)throw new Error("Native implementation scope schema is invalid");let i=ki(t.contractHash,"Implementation scope contractHash"),n=ki(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=CN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=ki(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=CN(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(yp);if(JSON.stringify(c)!==JSON.stringify(ro(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(RN),u=[...l].sort((y,C)=>Ce(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>io(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(RN),p=t.externalDrift===void 0?void 0:FN(t.externalDrift),m=new Set(p?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(N$),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:g$(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...h.map(y=>sr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&S===null?[sr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(hp))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(hp))||t.complete!==(v.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let w;if(t.gitAdvisory!==void 0){let y=Wt(t.gitAdvisory,"Implementation scope Git advisory");if(zt(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=eo(y.changedPaths,"Git changed paths"),O=eo(y.pathsPresentInSnapshotChanges,"Git present paths"),j=eo(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Y=[...O,...j].sort(Ce);if(JSON.stringify(Y)!==JSON.stringify(C)||j.some(Re=>l.some(X=>X.path===Re)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:j}}let k={schema:dp,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:S,...w?{gitAdvisory:w}:{},...p?{externalDrift:p}:{}},E=ki(t.scopeHash,"Implementation scope scopeHash");if(T(IN,k)!==E)throw new Error("Implementation scope content hash mismatch");return{...k,scopeHash:E}}function b$(e){let t=Wt(e,"Native implementation scope authority");if(zt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(yp);if(JSON.stringify(r)!==JSON.stringify(ro(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=eo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:FN(t.externalDrift),a=HN({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function no(e){let t=Wt(e,"Native implementation scope bundle");zt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=b$(t.authority),i=el(t.baseline),n=el(t.current),a=tl(t.scope),o=qN(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function LN(e){let t=tl(e.scope);return no({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var dp,AN,Za,IN,r$,i$,n$,mp,Si,a$,o$,y$,Ei=I(()=>{"use strict";ce();ln();dp="comet.native.implementation-scope.v2",AN="comet.native.content-snapshot-projection.v1",Za="comet.native.content-snapshot-projection.v1",IN="comet.native.implementation-scope.v2",r$="comet.native.unresolved-scope-id.v1",i$="comet.native.scope-detail-overflow.v1",n$="comet.native.snapshot-projection-overflow.v2",mp=/^[a-f0-9]{64}$/u,Si=1024*1024,a$=128,o$=128;y$=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import BN from"node:path";function cr(e,t){if(!MN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function WN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function zN(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Np(e,t,r=2e3){let i=st(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function ao(e,t){let r=BN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||BN.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function x$(e,t,r){let i=ao(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=jt(i),a=i.toLowerCase(),o=r?ao(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function bp(e){let t=ao(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function yn(e,t){return e<t?-1:e>t?1:0}function rl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function il(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function JN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function VN(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function C$(e){let t=rl(e,"Native acceptance trace");if(il(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!MN.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=ao(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=rl(o,`Native acceptance trace entry ${s}`);if(il(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>bp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:ao(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Np(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>yn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=cr(t.traceHash,"Native acceptance trace hash");if(T(k$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function GN(e){let t=rl(e,"Native partial allowance");if(il(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(yn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:zN(t.change),scopeHash:cr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Np(t.reason,"Partial allowance reason"),confirmedSummary:Np(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:WN(t.sourceRevision),confirmedAt:JN(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=cr(t.allowanceHash,"Native partial allowance hash");if(T(S$,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function kp(e){let t=rl(e,"Native verification evidence");if(il(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=cr(t.implementationScopeHash,"Native verification implementation scope hash"),i=C$(t.acceptanceTrace),n=cr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:cr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>bp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(yn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(yn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>bp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:zN(t.change),sourceRevision:WN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:cr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:VN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:x$(t.reportRef,"Native verification report ref"),reportHash:cr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:VN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:JN(t.createdAt,"Native verification timestamp")},d=cr(t.envelopeHash,"Native verification envelope hash");if(T(E$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var MN,k$,S$,E$,nl=I(()=>{"use strict";ce();Ni();ua();Ei();MN=/^[a-f0-9]{64}$/u,k$="comet.native.acceptance-trace.v2",S$="comet.native.partial-allowance.v1",E$="comet.native.verification-evidence.v2"});import UN from"node:path";function Jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Gr(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function lr(e,t){if(typeof e!="string"||!R$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ye(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function eb(e,t){let r=Ye(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function QN(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function O$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>j$||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=UN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||UN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function H$(e){let t=Jr(e,"Native check receipt checker");Gr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Jr(t.limits,"Native check receipt limits");if(Gr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Nn||t.version!==Sp||t.hash!==YN||r.maxFiles!==Me.maxFiles||r.maxFileBytes!==Me.maxFileBytes||r.maxTotalBytes!==Me.maxTotalBytes||r.maxIssues!==Me.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Nn,version:Sp,hash:YN,limits:{...Me}}}function D$(e){let t=Jr(e,"Native check receipt contract");return Gr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:lr(t.expectedHash,"Native check expected contract hash"),beforeHash:lr(t.beforeHash,"Native check before contract hash"),afterHash:lr(t.afterHash,"Native check after contract hash")}}function q$(e){let t=Jr(e,"Native check receipt implementation");return Gr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:lr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:lr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:lr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:lr(t.afterSnapshotHash,"Native check after snapshot hash")}}function F$(e,t){let r=Jr(e,`Native check batch ${t}`);Gr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Ye(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ye(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ye(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ye(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ye(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ye(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Me.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Me.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function L$(e){let t=Jr(e,"Native check receipt counts");Gr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Ye(t.filesSelected,"Native check filesSelected"),filesScanned:Ye(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ye(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ye(t.bytesScanned,"Native check bytesScanned"),issueCount:Ye(t.issueCount,"Native check issueCount"),recordedIssueCount:Ye(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(F$):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Me.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Me.maxFiles||r.bytesScanned>Me.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function B$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||XN.indexOf(e.kind)-XN.indexOf(t.kind)}function V$(e){if(!Array.isArray(e)||e.length>Me.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Jr(i,`Native check issue ${n}`);if(Gr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!T$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:O$(a.path,`Native check issue ${n} path`),line:eb(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(B$);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function M$(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!$$.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=ZN.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function W$(e){return T(I$,e)}function tb(e){let t=Jr(e,"Native check receipt");if(Gr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==KN)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!_$.test(t.change))throw new Error("Native check receipt change name is invalid");let r=eb(t.sourceRevision,"Native check source revision"),i=H$(t.checker),n=D$(t.contract),a=q$(t.implementation),o=W$({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(lr(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=QN(t.startedAt,"Native check receipt startedAt"),c=QN(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=L$(t.counts),u=V$(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=M$(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Me.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Me.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:KN,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=lr(t.receiptHash,"Native check receipt content hash");if(T(P$,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var KN,P$,Nn,Sp,Me,R$,_$,A$,I$,j$,YN,T$,XN,ZN,$$,Ep=I(()=>{"use strict";ce();KN="comet.native.check-receipt.v1",P$="comet.native.check-receipt.v1",Nn="scoped-text-safety",Sp=1,Me=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),R$=/^[a-f0-9]{64}$/u,_$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A$="comet.native.checker-policy.v1",I$="comet.native.check-input.v1",j$=2048,YN=T(A$,{policy:Nn,version:Sp,limits:Me,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),T$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),XN=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],ZN=["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"],$$=new Set(ZN)});function bn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Ur(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ur(e,t){if(typeof e!="string"||!G$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ct(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=st(e).trim();if(!r||r.length>X$||r!==e.trim())throw new Error(`${t} is invalid`);return r}function xp(e,t){let r=Ct(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function oo(e,t,r=Ct,i=!1,n=Q$){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function eO(e,t){if(typeof e!="string"||!U$.test(e))throw new Error(`${t} is invalid`);return e}function tO(e){let t=bn(e,"Native verification receipt bindings");if(Ur(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!K$.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:ur(t.contractHash,"Native verification receipt contract hash"),scopeHash:ur(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:ur(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:ur(t.artifactHash,"Native verification receipt artifact hash")}}function rO(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Y$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function iO(e,t,r,i){let n=bn(t,`Native ${e} evidence`);if(e==="automated-check"){if(Ur(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=xp(n.startedAt,"Native automated-check start time"),o=xp(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=bn(n.worktree,"Native automated-check worktree");if(Ur(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=bn(n.afterFence,"Native automated-check after fence");if(Ur(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ct(n.executable,"Native automated-check executable"),args:oo(n.args,"Native automated-check arguments",Ct,!0),cwd:Ct(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ct(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:ur(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:ur(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:ur(n.outputHash,"Native automated-check output hash"),outputSummary:Ct(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Ur(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=rO(n.checkReceiptRef);if(ur(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:oo(n.subjects,"Native static inspection subjects",Ct,i==="required-check"),rule:Ct(n.rule,"Native static inspection rule"),resultSummary:Ct(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Ur(n,["steps","observations"],"Native manual-evidence evidence"),{steps:oo(n.steps,"Native manual evidence steps"),observations:oo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function nO(e){let t=bn(e,"Native verification receipt");if(Ur(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=Ct(t.actor,"Native verification receipt actor"),o=oo(t.acceptanceIds,"Native receipt acceptance IDs",eO,i==="required-check",Z$).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Cp,kind:r,role:i,status:n,bindings:tO(t.bindings),acceptanceIds:o,actor:a,issuedAt:xp(t.issuedAt,"Native verification receipt issue time"),evidence:iO(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Nn||s.actor!==`native-runtime:${Nn}`))throw new Error("Native required check policy identity is invalid");return s}function rb(e){let t=bn(e,"Native verification receipt");if(Ur(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Cp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=nO(i),a=ur(t.receiptHash,"Native verification receipt hash");if(T(z$,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Pp(e){return T(J$,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Cp,z$,J$,G$,U$,K$,Y$,X$,Q$,Z$,so=I(()=>{"use strict";ce();Ep();Ni();Cp="comet.native.verification-receipt.v3",z$=Cp,J$="comet.native.declared-artifacts.v1",G$=/^[a-f0-9]{64}$/u,U$=/^acceptance-[a-f0-9]{64}$/u,K$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Y$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,X$=4096,Q$=256,Z$=1024});import{createHash as aO}from"node:crypto";import{promises as Pt}from"node:fs";import Jt from"node:path";function Rp(e,t){let r=Jt.relative(e,t);return r===""||!Jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Jt.sep}`)}function oO(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function al(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ib(e){let t=await Pt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Pt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sO(e,t){let r=Jt.resolve(e),i=Jt.resolve(t);if(!Rp(r,i))throw new Error("Native evidence path is outside its change");let n=[await ib(r)],a=r;for(let o of Jt.relative(r,i).split(Jt.sep).filter(Boolean)){a=Jt.join(a,o);let s=await ib(a);if(!Rp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function nb(e){for(let t of e){let r=await Pt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!oO(t,r)||await Pt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function cO(e,t,r={}){let i=await sO(t,Jt.dirname(e));await r.afterParentChainCaptured?.();let n=await Pt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Pt.realpath(e);if(!Rp(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Pt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Pt.lstat(e),Pt.realpath(e)]);if(await nb(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!al(s,n)||!al(s,c))throw new Error("Native evidence document changed while opening");if(s.size>kn)throw new Error(`Native evidence document exceeds ${kn} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=kn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>kn)throw new Error(`Native evidence document exceeds ${kn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Pt.lstat(e),Pt.realpath(e)]);if(await nb(i),!m.isFile()||m.isSymbolicLink()||h!==a||!al(s,p)||!al(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function sb(e,t){if(!ob.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function lO(e,t,r,i,n){if(!ob.test(r))throw new Error("Native report evidence hash is invalid");let a=await xi({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||aO("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Sn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function uO(e,t,r,i,n){let a=sb(r,i);return n?Jt.join(n,...a.split("/")):Ir(K(e,t),a)}async function xi(e){let t=uO(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??we(e.paths,t);return await V(r,t),cO(t,r,e.hooks)}function ab(e,t){return el(e,t)}function dO(e,t){let r=tl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function fO(e,t,r){let i=GN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function pO(e,t,r){let i=kp(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function hO(e,t,r,i=!1,n){let a=await ol(e,t,r.implementationScopeRef,void 0,n);if(i&&await lO(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await cb(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function co(e,t,r,i,n){let a=Sn(r,"scopes"),o=dO(await xi({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Sn(o.baselineProjectionRef,"snapshots"),c=Sn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([xi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ab(d,s)),xi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ab(d,c))]);return LN({baseline:l,current:u,scope:o})}async function ol(e,t,r,i,n){return(await co(e,t,r,i,n)).scope}async function cb(e,t,r,i,n){let a=Sn(r,"allowances");return fO(await xi({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function lo(e,t,r,i,n){let a=Sn(r,"receipts"),o=rb(await xi({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function En(e,t,r,i,n){let a=Sn(r,"verifications"),o=pO(await xi({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await hO(e,t,o,!1,n),o}var ob,kn,K2,Kr=I(()=>{"use strict";le();U();Tt();Ei();nl();so();ob=/^[a-f0-9]{64}$/u,kn=Si,K2=3*kn});import Ri from"node:path";import{realpathSync as XH}from"node:fs";import{execFileSync as yS}from"child_process";import NS from"fs";import pr from"path";function Ai(e,t){return yS("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function jn(e,t){return kh(e)===kh(t)}function kh(e){let t=pr.resolve(e);try{let r=NS.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ve(e){try{let t=pr.resolve(Ai(e,["rev-parse","--show-toplevel"])),i=Ai(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?pr.resolve(i.slice(9)):t,a=null;try{a=Ai(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!jn(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Co(e){try{Ai(e,["rev-parse","--is-inside-work-tree"]);let t=Ai(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:pr.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 hr(e){return Co(e).map(t=>t.root)}function Al(e,t){let r=t.find(a=>jn(pr.resolve(a.root),pr.resolve(e)));if(!r)return null;let i=pr.resolve(t[0].root),n=pr.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!jn(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Ut(e,t){try{let r=Ai(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ce();var Wf=Gt(It(),1);import{promises as Ty}from"fs";import qr from"path";et();le();oi();Ge();Ee();U();yt();ln();import{createHash as Nj}from"crypto";import bj from"path";var at=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});Ee();U();import{constants as Pc,promises as kt}from"node:fs";import St from"node:path";import{TextDecoder as mj}from"node:util";import dj from"path";zi();Pr();var ij=Gt(It(),1);zi();Pr();_r();_r();Wi();$d();zi();_r();var rV=4*1024*1024;var nj=null;function aj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function dy(e,t){return(...r)=>{let i=nj;if(i===null)return t(...r);let n=aj(`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}}Wi();var sV=dy("hookWritePolicy",async e=>(await Ad(e))?.hook??{allow_paths:[]});va();import{randomUUID as oj}from"node:crypto";import{promises as Ec}from"node:fs";import py from"node:path";var xc="comet.selection.v2",hy=16*1024;function Cc(e){return py.join(e,".comet","current-change.json")}function sj(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fy(e){return e===null||typeof e=="string"}function my(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(!sj(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&&!fy(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:xc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==xc)throw new Error(`current change selection schema must be ${xc}`);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(!fy(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 Hf(e){let t;try{let i=Cc(e),{bytes:n}=await li(i,hy,{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",...my(t)}}async function Df(e,t){let r=my(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Cc(e),n=`${i}.${oj()}.tmp`;await Ec.mkdir(py.dirname(i),{recursive:!0});try{await Ec.writeFile(n,`${JSON.stringify(r.selection,null,2)}
167
- `,"utf8"),await Ec.rename(n,i)}catch(a){throw await Ec.rm(n,{force:!0}),a}}Id();da();var vy=(e,t)=>{let r=e[t];return r==null?null:String(r)};function qa(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Da(e,t){let r=qa(e,t);if(dj.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function fj(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function gy(e){if(!e.run_id)return null;let t=qa(e,"run_id"),r=qa(e,"skill"),i=qa(e,"skill_version"),n=qa(e,"skill_hash"),a=Da(e,"pending_ref"),o=Da(e,"trajectory_ref"),s=Da(e,"context_ref"),c=Da(e,"artifacts_ref"),l=Da(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:vy(e,"current_step"),iteration:u,pending:vy(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:fj(e)}}var fM=Number.MAX_SAFE_INTEGER;var pj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function hj(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},r=gy(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function qf(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!pj.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return hj(t)}le();Tt();var un={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};function _c(e,t){let r=St.relative(e,t);return r===""||!St.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${St.sep}`)}function vj(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Rc(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function gj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ac(e,t,r){let i=at[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=St.resolve(e),a=St.resolve(n,...i.slice(8).split("/"));if(!_c(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function wy(e){let t=await kt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await kt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function wj(e,t){let r=St.resolve(e),i=St.resolve(t);if(!_c(r,i))throw new Error("Native Run path is outside its change");let n=[await wy(r)],a=r;for(let o of St.relative(r,i).split(St.sep).filter(Boolean)){a=St.join(a,o);let s;try{s=await wy(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!_c(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function yy(e){for(let t of e){let r=await kt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!gj(t,r)||await kt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function yj(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Ic(e,t,r,i,n){let a=await wj(e,St.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await kt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=vj(o),c=await kt.realpath(t);if(!_c(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Pc.O_RDONLY:Pc.O_RDONLY|Pc.O_NOFOLLOW|Pc.O_NONBLOCK,u;try{u=await kt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),kt.lstat(t),kt.realpath(t)]);if(await yy(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Rc(s,d)||!Rc(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await yj(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),kt.lstat(t),kt.realpath(t)]);if(await yy(a),!v.isFile()||v.isSymbolicLink()||g!==c||!Rc(s,h)||!Rc(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new mj("utf-8",{fatal:!0}).decode(m)}catch(S){throw new Error(`${i} is not valid UTF-8`,{cause:S})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Ny(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function Ff(e){return qf(e)}async function dn(e,t){let r=Ac(e,"stateRef"),i=await Ic(e,r,un.runStateBytes,"Native Run state",t);return i?qf(Ny(i.text,"Native Run state")):null}async function vi(e,t,r){let i=Ac(e,"trajectoryRef",t),n=await Ic(e,i,un.trajectoryBytes,"Native Run trajectory",r);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>un.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${un.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function by(e,t,r){return(await Ic(e,Ac(e,"trajectoryRef",t),un.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function jc(e,t,r){let i=await Ic(e,Ac(e,"checkpointRef",t),un.checkpointBytes,"Native Run checkpoint",r);return i?Ny(i.text,"Native Run checkpoint"):null}var kj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Lf(e){return Nj("sha256").update(e).digest("hex")}function Sj(e,t){if(!kj.test(t))throw new Error(`Invalid Native change name: ${t}`);return bj.join(K(e,t),"trajectory.jsonl")}function Ej(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function xj(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function Cj(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=Ej(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
168
- `)])}catch(d){if(!xj(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Lf(t),targetHash:Lf(l),tailHash:Lf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Pj(e,t){let r=Sj(e,t);await V(we(e,r),r);let i=K(e,t),n=await by(i,at.trajectoryRef);return n===null?{status:"clean",file:r}:Cj(r,Buffer.from(n))}async function ky(e,t){let r=await Pj(e,t);return"inspection"in r?r.inspection:r}import{createHash as Rj}from"node:crypto";import{promises as Tc}from"node:fs";import nr from"node:path";le();et();Ee();U();var Fa=/^[a-f0-9]{64}$/u,Sy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,_j=16*1024,Vf=process.platform,Aj=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function fn(e){return Aj.has(e)}function Py(e,t){let r=nr.relative(e,t);return nr.isAbsolute(r)||r===".."||r.startsWith(`..${nr.sep}`)?null:r.replaceAll("\\","/")||"."}function Ry(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function _y(e,t){if(e.length===0||Ry(e)||e.includes("\\")||nr.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=nr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Mf(e,t){return Rj("sha256").update(`${e}
169
- ${t}`).digest("hex")}async function Ey(e,t){let r=await Tc.realpath(t),i=await Tc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Vf==="win32"?nr.normalize(r).toLowerCase():r;return Mf(e,`${n}
179
+ ${Buffer.byteLength(i)}:${i}`)}function PN(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function _N(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!PN(r))return e.splice(t,1),r}return null}function Jr(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Fj(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await ne.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=ol("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Jr(r,c))return{status:"changed"};for(;;){if(!H(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Jr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function lt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ut(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Sn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Kt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=F.posix.normalize(e);if(r!==e||F.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Lj(e,t){let r=lt(e,`Native snapshot entry ${t}`);ut(r,pj,`Native snapshot entry ${t}`);let i=AN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!sl.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Kt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!wN.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function qj(e,t){let r=lt(e,`Native snapshot omission ${t}`);if(ut(r,fj,`Native snapshot omission ${t}`),!vj.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!gj.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:AN(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Kt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function Mj(e){let t=lt(e,"Native snapshot omission overflow");if(ut(t,hj,"Native snapshot omission overflow"),typeof t.hash!="string"||!sl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Sn(t.count,"Native snapshot omission overflow count")}}function kn(e,t){let r=lt(e,t);if(ut(r,lj,t),typeof r.hash!="string"||!sl.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Kt(r.recordCount,`${t} recordCount`),n=Kt(r.storedRecordCount,`${t} storedRecordCount`),a=Kt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function mN(e){let t=lt(e,"Native Git selection evidence");if(ut(t,cj,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=kn(t.stageBefore,"Native Git selection stageBefore"),i=kn(t.combined,"Native Git selection combined"),n=kn(t.stageAfter,"Native Git selection stageAfter"),a=kn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=kn(t.finalCombined,"Native Git selection finalCombined"),s=kn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Ur(r,n)||!Ur(n,a)||!Ur(i,o)||!Ur(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function vN(e,t){let r=lt(e,t);if(ut(r,dj,t),typeof r.hash!="string"||!sl.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Kt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Kt(r.recordCount,`${t} recordCount`),a=Kt(r.storedRecordCount,`${t} storedRecordCount`),o=Kt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function Vj(e){let t=lt(e,"Native physical selection evidence");if(ut(t,uj,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=vN(t.before,"Native physical selection before"),i=vN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!xN(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function _i(e){let t=lt(e,"Native content snapshot manifest");if(ut(t,ij,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!mj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let w=lt(t.capture,"Native content snapshot capture");if(ut(w,oj,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=w.gitSelection===void 0?void 0:mN(w.gitSelection),E=w.physicalSelection===void 0?void 0:Vj(w.physicalSelection),y=null;if(w.projection!==void 0){let C=lt(w.projection,"Native content snapshot projection");if(ut(C,sj,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:mN(C.selection)}}}if(w.provider==="git"){if(E||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(E&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...E?{physicalSelection:E}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=lt(t.limits,"Native content snapshot limits");ut(i,nj,"Native content snapshot limits");let n={maxFiles:Sn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Sn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Sn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Sn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Sn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=lt(t.policy,"Native snapshot policy");if(ut(w,aj,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=RN({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(Lj),s=t.omitted.map(qj),c=Kt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Mj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>n.maxFileBytes)||o.reduce((w,S)=>w+S.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Pf||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),p=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...p])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),g=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...g])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",N=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}async function IN(e,t,r={}){let i=_i(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=F.resolve(e.projectRoot),a=yN(r),o=NN(r.gitSelectionLimits),s=await SN(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(CN(s).filter(S=>lo(e,S))),l=[...s.gitlinks].filter(S=>c.has(S)),u=[...s.nestedRepositories].filter(S=>lo(e,S)),d=(S,E)=>E.some(y=>S===y||S.startsWith(`${y}/`)),p=S=>d(S,l),f=S=>d(S,u),m=[...i.entries.map(S=>S.path),...i.omitted.flatMap(S=>S.type==="directory"?[S.path,`${S.path}/`]:[S.path])].filter(S=>!c.has(S)&&!p(S)&&!f(S)),h=await xj(a,n,m),v=i.entries.filter(S=>!p(S.path)&&!f(S.path)&&lo(e,S.path)&&(c.has(S.path)||!h.has(S.path)));await EN(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let S of l)g.push({path:S,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((S,E)=>S.path.localeCompare(E.path,"en"));let b=i.omitted.filter(S=>p(S.path)||f(S.path)||!lo(e,S.path)?!1:h.has(S.path)?c.has(S.path)||[...c].some(E=>E.startsWith(`${S.path}/`)):!0);for(let S of g)b.some(E=>E.path===S.path&&E.reason===S.reason)||b.push(S);b.sort((S,E)=>S.path.localeCompare(E.path,"en"));let k=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??ee("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,N=al(N,"git-selection",{source:"git-selection",...s.overflow}));let x=S=>{k+=1,N=al(N,"omission",S)};for(;b.length>Pf;){let S=_N(b);if(S===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");x(S)}return _i({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+k===0,entries:v,omitted:b,omittedCount:b.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}})}function Wj(e,t){if(!rj.test(t))throw new Error(`Invalid Native change name: ${t}`);return F.join(Y(e,t),"baseline-manifest.json")}async function TN(e,t={}){let r={maxFiles:t.limits?.maxFiles??rl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??rl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??rl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??rl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=RN(t.policy),n=yN({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=NN(t.gitSelectionLimits,t.maxSelectionRecords),o=Sj(t.physicalSelectionLimits,t.maxSelectionRecords);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=F.resolve(e.projectRoot),c=await ne.realpath(s),l=F.resolve(e.nativeRoot),u=await ne.realpath(l),d=F.resolve(e.runtimeDir),p=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),m=Oj(s,t.denylist??[]),h=[],v=[],g=new Map,b=new Map,k=0,N=0,x=ee("comet.native.snapshot-omission-overflow.v1"),w=0,S=!1,E=null,y=_=>{N+=1,x=al(x,"omission",_)},C=_=>{if(k+=1,v.length<Pf){v.push(_);return}if(PN(_)){let A=_N(v);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),v.push(_);return}y(_)},O=_=>{k+=_.count,N+=_.count,x=al(x,"git-selection",{source:"git-selection",..._})},T=async(_,A)=>{h.push(_),w+=_.size,g.set(_.path,A),S||(S=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let $=h.findIndex(te=>te.path===_);if($<0)return;let[W]=h.splice($,1);w-=W.size,g.delete(_),C(A)},Te=async(_,A,$,W)=>{if(!$.isFile()||$.isSymbolicLink()||!H(n))return;let te;try{te=await ne.realpath(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n)||!q(c,te)||Pt(u,te))return;if(h.length>=r.maxFiles){C({path:A,size:$.size,type:"file",reason:"file-count"});return}if($.size>r.maxFileBytes){C({path:A,size:$.size,type:"file",reason:"file-size"});return}if(w+$.size>r.maxTotalBytes){C({path:A,size:$.size,type:"file",reason:"total-size"});return}let J,D,le;try{if(J=await Fj(te,$.size,$,n),J.status==="budget-exhausted"||!H(n))return;if(J.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(le=await ne.realpath(_),!H(n)))return;D=await ne.lstat(_)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:$.size,type:"file",reason:ve(P)?"changed-during-read":"unreadable"});return}if(H(n)){if(J.bytes!==$.size||le!==te||!Jr($,J.finalStat)||!Jr(J.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==$.size||D.mtimeMs!==$.mtimeMs||D.ctimeMs!==$.ctimeMs){C({path:A,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await T({path:A,hash:J.hash,size:D.size,type:"file",...W===void 0?{}:{gitObjectId:W}},{kind:"file",target:_,realTarget:te,stat:D})}},Z=async(_,A,$)=>{if(!H(n))return;let W,te,J;try{if(W=await ne.readlink(_,{encoding:"buffer"}),!H(n)||(J=await ne.lstat(_),!H(n)))return;te=await ne.readlink(_,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;C({path:A,size:null,type:"other",reason:ve(P)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!J.isSymbolicLink()||!Jr($,J)||J.mtimeMs!==$.mtimeMs||J.ctimeMs!==$.ctimeMs||!W.equals(te)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let D=W.byteLength;if(h.length>=r.maxFiles){C({path:A,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:A,size:D,type:"other",reason:"file-size"});return}if(w+D>r.maxTotalBytes){C({path:A,size:D,type:"other",reason:"total-size"});return}let le=ol("sha256").update("symlink\0").update(W).digest("hex");H(n)&&await T({path:A,hash:le,size:D,type:"file"},{kind:"symlink",target:_,rawTarget:W,stat:J})},Ot=async()=>{for(let[_,A]of[...g]){if(!H(n))return;if(A.kind==="file"){let D,le;try{if(D=await ne.realpath(A.target),!H(n))return;le=await ne.lstat(A.target)}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"file",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==A.realTarget||!le.isFile()||le.isSymbolicLink()||!Jr(A.stat,le)||le.size!==A.stat.size||le.mtimeMs!==A.stat.mtimeMs||le.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:le.isFile()?le.size:null,type:le.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let D,le;try{if(D=await ne.lstat(A.target),!H(n))return;le=await ne.readlink(A.target,{encoding:"buffer"})}catch(P){if(!H(n))return;if(!ge(P)&&!ve(P))throw P;Q(_,{path:_,size:null,type:"other",reason:ge(P)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Jr(A.stat,D)||D.mtimeMs!==A.stat.mtimeMs||D.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(le))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let $,W;try{if($=await ne.realpath(A.target),!H(n))return;W=await ne.lstat(A.target)}catch{if(!H(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!($===A.realTarget&&W.isDirectory()&&!W.isSymbolicLink()&&Jr(A.stat,W)&&q(c,$)&&!Pt(u,$))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!H(n))return;J=await pN(n,$)}catch(D){if(En(D))throw D;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;J.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of b){if(!H(n))return;try{let $=await ne.lstat(A);if(!H(n))return;C({path:_,size:$.isFile()?$.size:null,type:$.isFile()?"file":$.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch($){if(!H(n))return;if(ve($))continue;if(!ge($))throw $;C({path:_,size:null,type:"file",reason:"unreadable"})}}},ce=await SN(n,e,a,t.gitSelectionHooks,i?.manifest.exclude);if(ce===null){let _=await uN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let W of _.records){if(W.type!=="file"&&W.type!=="symlink"||g.has(W.path))continue;if(Rt(n)<1)break;if(!hN(i,W.path,n))continue;if(Rt(n)<1)break;let te=F.resolve(s,...W.path.split("/")),J;try{J=await ne.lstat(te)}catch(D){if(!H(n))break;if(!ge(D)&&!ve(D))throw D;C({path:W.path,size:null,type:"file",reason:ve(D)?"changed-during-read":"unreadable"});continue}if(Rt(n)<1)break;if(W.type==="symlink"&&J.isSymbolicLink()){if(await Z(te,W.path,J),Rt(n)<1)break;continue}if(W.type!=="file"||!J.isFile()||J.isSymbolicLink()){C({path:W.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Te(te,W.path,J),Rt(n)<1)break}Rt(n)>=1&&await Ot();let A=await uN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),$=jj(_.evidence,A.evidence);E=$.evidence;for(let W of[..._.omissions,...A.omissions,...$.omissions])v.some(te=>te.path===W.path&&te.reason===W.reason)||C(W)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,$=!1;if(_){let P=_i(_);for(let ae of P.entries)ae.gitObjectId!==void 0&&A.set(ae.path,ae);$=A.size>0}let W=new Set,te=!0;try{let P=await uo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)$=!1,te=!1,A.clear();else for(let ae of P.records){let ue=nl(ae),je=ue.indexOf(" "),Pe=je<0?null:xn(ue.slice(je+1));if(je!==1||Pe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ue[0]!=="H"&&W.add(Pe)}}catch(P){if(En(P))throw P;$=!1,te=!1,A.clear()}let J=new Set;try{let P=await il(n,s,["ls-files","--modified","-z"],Rf);for(let ae of P.toString("utf8").split("\0")){let ue=xn(ae);ue!==null&&J.add(ue)}}catch{$=!1,te=!1,A.clear()}let D=new Set,le=new Set;for(let P of CN(ce)){if(g.has(P)||!lo(e,P))continue;if(Rt(n)<1)break;if(!hN(i,P,n))continue;if(Rt(n)<1)break;let ae=F.resolve(s,...P.split("/"));if(ae===p||ae===f||Pt(d,ae)||m.some(Ye=>Pt(Ye,ae)))continue;if(ce.gitlinks.has(P)){if(h.length>=r.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Ye,as;try{[Ye,as]=await Promise.all([ne.realpath(ae),ne.lstat(ae)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(as.isSymbolicLink()||!as.isDirectory()||!q(c,Ye)||Pt(u,Ye)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Gi=await pN(n,Ye);if(Gi.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await T({path:P,hash:Gi.hash,size:0,type:"file"},{kind:"gitlink",target:ae,realTarget:Ye,stat:as,hash:Gi.hash})}catch(Gi){if(En(Gi))throw Gi;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ue;try{ue=await ne.lstat(ae)}catch(Ye){if(ve(Ye)&&ce.tracked.has(P)){b.set(P,ae);continue}if(!ge(Ye)&&!ve(Ye))throw Ye;C({path:P,size:null,type:"file",reason:ve(Ye)?"changed-during-read":"unreadable"});continue}if(ue.isSymbolicLink()){await Z(ae,P,ue);continue}if(!ue.isFile()){ce.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let je=ce.trackedObjectIds.get(P),Pe=je?A.get(P):void 0;if($&&Pe?.gitObjectId!==void 0&&Pe.gitObjectId===je&&!W.has(P)&&!J.has(P)){if(h.length>=r.maxFiles){C({path:P,size:Pe.size,type:"file",reason:"file-count"});continue}if(Pe.size>r.maxFileBytes){C({path:P,size:Pe.size,type:"file",reason:"file-size"});continue}if(w+Pe.size>r.maxTotalBytes){C({path:P,size:Pe.size,type:"file",reason:"total-size"});continue}h.push({...Pe}),w+=Pe.size,D.add(P);continue}let _m=te&&!W.has(P)&&!J.has(P)?je:void 0;await Te(ae,P,ue,_m),_m!==void 0&&le.add(P)}if(await Ot(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await EN(n,e,a,ce,t.gitSelectionHooks?.outputChunkBytes,i?.manifest.exclude),D.size>0||$&&le.size>0){let P=await il(n,s,["ls-files","--modified","-z"],Rf),ae=new Set;for(let ue of P.toString("utf8").split("\0")){let je=xn(ue);je!==null&&ae.add(je)}for(let ue of D){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);Q(ue,{path:ue,size:je?.size??null,type:"file",reason:"changed-during-read"})}for(let ue of le){if(!ae.has(ue))continue;let je=h.find(Pe=>Pe.path===ue);je&&delete je.gitObjectId}}for(let P of ce.omissions)C(P);ce.overflow&&O(ce.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),v.sort((_,A)=>_.path.localeCompare(A.path,"en"));let UE=ce===null?{provider:"physical-tree",...E?{physicalSelection:E}:{}}:{provider:"git",...ce.evidence?{gitSelection:ce.evidence}:{}};return{schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:UE,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:v,omittedCount:k,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${x}`,hash:x,count:N}}:{}}}async function If(e,t,r={}){let n=(await xe(e.projectRoot))?.native.snapshot??Tp;return TN(e,{...r,policy:t.policy,incrementalBaseline:t,maxSelectionRecords:n.max_selection_records,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function cl(e,t){let r=Wj(e,t),i=Ne(e,r);await V(i,r);try{let n=await eN({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return _i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var rl,Pf,rj,ij,nj,aj,oj,sj,cj,lj,uj,dj,pj,fj,hj,mj,vj,gj,sl,wN,wj,Cn,Rf,yj,Nj,bj,_f,kj,Ij,Rn=I(()=>{"use strict";Ji();oe();Qe();Ut();Lt();K();Ct();Da();rl={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},Pf=1e3,rj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ij=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),nj=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),aj=new Set(["schema","include","exclude","hash"]),oj=new Set(["provider","gitSelection","physicalSelection","projection"]),sj=new Set(["provider","selection"]),cj=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),lj=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),uj=new Set(["schema","status","before","after"]),dj=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),pj=new Set(["path","hash","size","type","gitObjectId"]),fj=new Set(["path","size","type","reason"]),hj=new Set(["ref","hash","count"]),mj=new Set(["change-created","legacy-migration","explicit"]),vj=new Set(["file","directory","other"]),gj=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),sl=/^[a-f0-9]{64}$/u,wN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,wj=new Set(["EACCES","EPERM"]),Cn=64*1024,Rf=64*1024,yj=6e4,Nj=1e3,bj=2,_f={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},kj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};Ij=(1n<<256n)-1n});import{execFileSync as J$}from"node:child_process";function Y$(e,t){try{return Zn(()=>J$("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:U$,maxBuffer:K$,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Gf(e,t,i)}}function Je(e,t){return Y$(e,t).trim()}var U$,K$,Gf,pt=I(()=>{"use strict";Ji();U$=3e4,K$=8*1024*1024,Gf=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 rO}from"node:fs";import iO from"node:path";function $l(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function jl(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 qb(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 lO(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 Mb(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Gb(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===dh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!Vb(e.children,l)),Wb(i)?i:null}if(e.schema===Oi&&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=>!Vb(e.children,a)),Wb(i)?i:null}return null}function Vb(e,t){return e.some(r=>r.covers.includes(t))}function Wb(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Zr(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 uO(e){let t=$l(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=$l(n,`Native children acceptance_index.${i}`);if(jl(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 dO(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let p=["source","text"].filter(f=>d[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${p.join(", ")} exactly from the current acceptance catalog`)}}}function Jb(e,t,r={}){let i=(0,zb.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=$l(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Oi&&a!==Qr)throw jl(n,Lb,"Native children contract"),new Error(`Native children schema must be ${Oi} or ${Qr}`);let o=a===Oi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(jl(n,o==="indexed-v2"?aO:Lb,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((p,f)=>{let m=$l(p,`Native child ${f}`);if(jl(m,o==="indexed-v2"?cO:o==="summary-v2"?sO:oO,`Native ${s} child fields (child ${f})`),typeof m.name!="string"||!nO.test(m.name))throw new Error(`Native child ${f} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:qb(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?qb(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:p})=>p);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let p of c){let f=p.depends_on.filter(m=>!u.has(m));if(f.length>0)throw new Error(`Native child ${p.name} depends on unknown child: ${f.join(", ")}`)}lO(c);let d=r.policy==="advisory";if(a===dh){if(o==="indexed-v2"){let p=uO(n.acceptance_index);d||dO(p,t,r);let f=Object.keys(p);return d||Mb(c,f,f),{schema:Qr,acceptance_index:p,children:c}}return{schema:Qr,children:c}}return t&&!d&&Mb(c,t),{schema:Oi,children:c}}async function Qt(e){let t=iO.join(e.changeDir,uh);try{await rO.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await re({root:e.changeDir,ref:uh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Jb(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Gb(a,e.acceptanceIds,e.validation??{}):null}}var zb,uh,Oi,Qr,dh,nO,Lb,aO,oO,sO,cO,Ol=I(()=>{"use strict";zb=ir(Bt(),1);at();uh="children.yaml",Oi="comet.native.children.v1",Qr="comet.native.children.v2",dh=Qr,nO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lb=new Set(["schema","children"]),aO=new Set(["schema","acceptance_index","children"]),oO=new Set(["name","depends_on","covers"]),sO=new Set(["name","summary","depends_on"]),cO=new Set(["name","depends_on","covers"])});var _o=I(()=>{"use strict"});var Hl=I(()=>{"use strict";Vc();_o()});function gr(e,t){if(!fO.test(e))throw new Error(`${t} must be a Git commit`)}function ph(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Bl(e){gr(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:fh(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:Ao,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 fh(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 Fl(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 fO,Ao,Dl,Hi=I(()=>{"use strict";de();Hl();fO=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Ao="comet.native.supervisor.v2",Dl=3});import Io from"node:path";import{promises as Kb}from"node:fs";function hh(e,t){return Io.join(Et(e,t),"supervisor")}function To(e,t){return Io.join(hh(e,t),"state.json")}function Yb(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!==Ao)throw new Error(`Native Supervisor state schema must be ${Ao}`);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(gr(t.integration.targetCommit,"Native Supervisor target commit"),gr(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");gr(n.candidateCommit,"Native Supervisor integration candidate commit"),gr(n.integrationCommit,"Native Supervisor integration check commit"),Ub(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&&gr(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(gr(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&&Ub(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 et(e,t,r={}){try{let i=await Kb.readFile(To(e,t),"utf8"),n=JSON.parse(i);if(Yb(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(()=>(xt(),hf)),c=await s(Io.join(o.changesDir,t,"comet-state.yaml")),l=await Qt({changeDir:Io.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:Zr(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=fh(l.contract,u.name),u.contractHash=j("comet.native.supervisor-contract.v1",l.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(()=>(xt(),hf)),s=await o(Io.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 ei(e,t){Yb(t),await Kb.mkdir(e.changesRuntimeDir,{recursive:!0}),await Oe(To(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Ub(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 ti=I(()=>{"use strict";oe();de();Ol();K();Hi()});var mh=I(()=>{"use strict"});function mt(e){return e.replace(hO,"$1 [REDACTED]").replace(mO,"[REDACTED PRIVATE KEY]").replace(vO,"$1[REDACTED]@").replace(gO,"[REDACTED TOKEN]").replace(wO,'$1"[REDACTED]"').replace(yO,"$1$2$1$3$4[REDACTED]$4").replace(NO,"$1$2[REDACTED]")}var hO,mO,vO,gO,wO,yO,NO,Di=I(()=>{"use strict";hO=/\b(Bearer|Basic)\s+[^\s"']+/giu,mO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,vO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,gO=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,wO=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,yO=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,NO=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{accessSync as JG,constants as UG,createWriteStream as KG,existsSync as YG,promises as XG,statSync as SO}from"node:fs";import Bi from"node:path";function EO(e,t){let r=Bi.relative(e,t);return r===""||!Bi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Bi.sep}`)}function Xb(e,t){if(t.length===0||t.includes("\\")||Bi.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Bi.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Bi.resolve(e),i=Bi.resolve(r,...t.split("/"));if(!EO(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=SO(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}var Ll=I(()=>{"use strict";ta();mh();Di()});var Qb=I(()=>{"use strict";pt();Ll();de()});var ql=I(()=>{"use strict";pt();oe()});import{createHash as dk}from"node:crypto";import nk from"path";function Ae(e,t){return e<t?-1:e>t?1:0}function bh(e){if(!Eh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function ZO(e,t){return e===t?0:e===null?-1:t===null?1:Ae(e,t)}function ii(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=nk.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||nk.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function hk(e,t){return e==="."?e:ii(e,t)}function Bn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function eH(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:ii(e.path,`${t} path`),hash:e.hash,size:Bn(e.size,`${t} size`),type:"file"}}function tH(e,t){return{path:hk(e.path,`${t} path`),size:e.size===null?null:Bn(e.size,`${t} size`),type:e.type,reason:e.reason}}function rH(e,t){return Ae(e.path,t.path)||Ae(e.hash,t.hash)||e.size-t.size}function iH(e,t){return Ae(e.path,t.path)||Ae(e.reason,t.reason)||Ae(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ho(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
180
+ `,"utf8")}function ri(e,t,r){let i=`${t}
181
+ ${oa(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function nH(e){if(Ho(e)<=Li)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=dk("sha256");a.update(`${YO}
182
+ `),e.omissionOverflow&&ri(a,"existing-overflow",e.omissionOverflow);let o=(p,f)=>{f||(i+=1),n+=1,ri(a,"omission",p)},s=p=>{i+=1,n+=1,ri(a,"entry",p)},c=()=>{for(let p=r.length-1;p>=0;p-=1){let f=r[p];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(p,1),f}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Ho(u)>Li;){if(r.filter(f=>f.reason!=="git-enumeration-limit"&&f.reason!=="git-selection-changed"&&f.reason!=="physical-enumeration-limit"&&f.reason!=="physical-selection-changed").length>0){let f=Math.max(1,Math.ceil(r.length/4));for(let m=0;m<f;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let f=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-f))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function kh(e){let t=_i(e),r=t.entries.map((n,a)=>eH(n,`Snapshot entry ${a}`));if(r.sort(rH),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>tH(n,`Snapshot omission ${a}`));return i.sort(iH),nH({schema:pk,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Do(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:ii(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>Ae(r.path,i.path)||Ae(r.kind,i.kind))}function Bo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function ak(e){return e?{hash:e.hash,size:e.size}:null}function xh(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ae(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:ak(c),after:ak(l)})}}function mk(e,t){return{...e,attributedTo:t.filter(r=>Bo(r,e.path))}}function Ch(e){let t=Do(e.declaredArtifacts),r=[];return xh(e.baseline,e.current,i=>{r.push(mk(i,t))}),r}function wr(e,t){return{id:`scope:${j(UO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function aH(e,t){let r=t.omitted.map(i=>wr({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(wr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(wr({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function ok(e,t){return aH(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Sh(e,t){return Ae(e.kind,t.kind)||Ae(e.source,t.source)||ZO(e.path,t.path)||Ae(e.id,t.id)}function oH(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Sh)}function vk(e){return[...new Set(e.map((t,r)=>ii(t,`Git path ${r}`)))].sort(Ae)}function sk(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function sH(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function gk(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=vk(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:sk(e.baseCommit,"Native external drift base commit"),targetBranch:sH(e.targetBranch,"Native external drift target branch"),targetCommit:sk(e.targetCommit,"Native external drift target commit"),paths:t}}function wk(e){if(typeof e.contractHash!="string"||!Eh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Do(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:vk(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:gk(e.externalDrift)}}}function cH(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,p=0;return xh(e,t,f=>{let m=r.some(h=>Bo(h,f.path));if(d+=1,c.push(f.path),!m&&!n?.has(f.path)&&(p+=1),o?.has(f.path)&&s.push(f.path),!u&&a.length<XO){let h=mk(f,r),v=Ho(h);l+v<=Li?(a.push(h),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:p}}function yk(e,t){return wr({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function lH(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:Bn(Number(t[1]),"Scope overflow change count"),unresolved:Bn(Number(t[2]),"Scope overflow unresolved count"),unattributed:Bn(Number(t[3]),"Scope overflow unattributed count")},i=Fi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(yk(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function uH(e){let t=dk("sha256");t.update(`${KO}
183
+ `);let r=0;xh(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){ri(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Bo(o,n.path)&&(a+=1,ri(t,"change-attribution",o));ri(t,"change-end",{attributionCount:a}),a===0&&ri(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&ri(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function Nk(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=cH(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let S=new Set(r.externalDrift.paths),E=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!E.has(C)||n.some(O=>Bo(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(S.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j($o,e),c=j($o,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[S,E]of[["baseline",e],["current",t]])for(let y of E.omitted){if(l.length>=QO)break;l.push(wr({kind:"snapshot-omission",source:S,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${S} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,p=[...ok("baseline",e),...ok("current",t),...o.totalChanges===0&&a===null?[wr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(r.gitChangedPaths===void 0)return;let S=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>S.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!S.has(E))}},m=S=>{let E=o.candidates.slice(0,S.detailedChangeCount),y=E.filter(ce=>ce.attributedTo.length===0&&!u.has(ce.path)),C=o.totalChanges-E.length,O=o.totalUnattributed-y.length,T=d-S.detailedOmissionCount,Q=O+T,Te=[...y.map(ce=>wr({kind:"unattributed-change",source:"implementation-scope",path:ce.path,evidence:{after:ce.after,before:ce.before,changeKind:ce.kind}},`Changed path is not covered by a declared artifact: ${ce.path}`)),...l.slice(0,S.detailedOmissionCount),...p,...Q>0?[yk(S.overflowHash,{changes:C,unattributed:O,unresolved:Q})]:[]],Z=oH(Te),Ot=S.includeGitAdvisory?f():void 0;return{schema:Nh,contractHash:i,baselineProjectionRef:bh(s),baselineProjectionHash:s,currentProjectionRef:bh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:E,unattributed:y,unresolvedScopes:Z,noCodeReason:a,...Ot?{gitAdvisory:Ot}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let S=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b});if(Ho({...S,scopeHash:b})<=Li)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>v?uH({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:v}):b,x=m({detailedChangeCount:h,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N}),w={...x,scopeHash:j(fk,x)};if(Ho(w)>Li)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return w}function Rh(e){let t=kh(e.baseline),r=kh(e.current),i=wk(e);return{authority:i,baseline:t,current:r,scope:Nk(t,r,i)}}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function er(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Fi(e,t){if(typeof e!="string"||!Eh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ck(e,t,r){let i=bh(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function Wl(e,t){let r=Zt(e,"Native snapshot projection");if(er(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==pk)throw new Error("Native snapshot projection schema is invalid");let i=_i({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=kh(i);if(j($o,r)!==j($o,n))throw new Error("Native snapshot projection is not canonical");let a=j($o,n);if(t!==void 0&&Fi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Ph(e,t){let r=Zt(e,`Declared artifact ${t}`);if(er(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ii(r.path,`Declared artifact ${t} path`),kind:r.kind}}function lk(e,t){if(e===null)return null;let r=Zt(e,t);return er(r,["hash","size"],[],t),{hash:Fi(r.hash,`${t} hash`),size:Bn(r.size,`${t} size`)}}function uk(e,t){let r=Zt(e,`Implementation change ${t}`);if(er(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Ph),n=Do(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=lk(r.before,`Implementation change ${t} before`),o=lk(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:ii(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function pH(e,t){let r=Zt(e,`Unresolved scope ${t}`);er(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?hk(r.path,`Unresolved scope ${t} path`):ii(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Oo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>ii(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ae);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function bk(e){let t=Zt(e,"Native implementation external drift");if(er(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=Oo(t.paths,"Native external drift paths");return gk({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function zl(e){let t=Zt(e,"Native implementation scope"),r=[...dH].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(er(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Nh)throw new Error("Native implementation scope schema is invalid");let i=Fi(t.contractHash,"Implementation scope contractHash"),n=Fi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=ck(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Fi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=ck(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Ph);if(JSON.stringify(c)!==JSON.stringify(Do(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(uk),u=[...l].sort((y,C)=>Ae(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>Bo(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let p=t.unattributed.map(uk),f=t.externalDrift===void 0?void 0:bk(t.externalDrift),m=new Set(f?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(p)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(pH),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:lH(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let k=t.noCodeReason,N=[...h.map(y=>wr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&k===null?[wr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],x=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(Sh))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(x)!==JSON.stringify(N.sort(Sh))||t.complete!==(v.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let w;if(t.gitAdvisory!==void 0){let y=Zt(t.gitAdvisory,"Implementation scope Git advisory");if(er(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Oo(y.changedPaths,"Git changed paths"),O=Oo(y.pathsPresentInSnapshotChanges,"Git present paths"),T=Oo(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...O,...T].sort(Ae);if(JSON.stringify(Q)!==JSON.stringify(C)||T.some(Te=>l.some(Z=>Z.path===Te)))throw new Error("Implementation scope Git advisory partition is invalid");w={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:T}}let S={schema:Nh,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:p,unresolvedScopes:v,noCodeReason:k,...w?{gitAdvisory:w}:{},...f?{externalDrift:f}:{}},E=Fi(t.scopeHash,"Implementation scope scopeHash");if(j(fk,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function fH(e){let t=Zt(e,"Native implementation scope authority");if(er(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(Ph);if(JSON.stringify(r)!==JSON.stringify(Do(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=Oo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:bk(t.externalDrift),a=wk({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Fo(e){let t=Zt(e,"Native implementation scope bundle");er(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=fH(t.authority),i=Wl(t.baseline),n=Wl(t.current),a=zl(t.scope),o=Nk(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function kk(e){let t=zl(e.scope);return Fo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var Nh,pk,$o,fk,UO,KO,YO,Eh,Li,XO,QO,dH,qi=I(()=>{"use strict";de();Rn();Nh="comet.native.implementation-scope.v2",pk="comet.native.content-snapshot-projection.v1",$o="comet.native.content-snapshot-projection.v1",fk="comet.native.implementation-scope.v2",UO="comet.native.unresolved-scope-id.v1",KO="comet.native.scope-detail-overflow.v1",YO="comet.native.snapshot-projection-overflow.v2",Eh=/^[a-f0-9]{64}$/u,Li=1024*1024,XO=128,QO=128;dH=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import Sk from"node:path";function yr(e,t){if(!xk.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ck(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Rk(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function _h(e,t,r=2e3){let i=mt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Lo(e,t){let r=Sk.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||Sk.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function gH(e,t,r){let i=Lo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ft(i),a=i.toLowerCase(),o=r?Lo(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function Ah(e){let t=Lo(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Fn(e,t){return e<t?-1:e>t?1:0}function Gl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Pk(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Ek(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function wH(e){let t=Gl(e,"Native acceptance trace");if(Jl(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!xk.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=Lo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Gl(o,`Native acceptance trace entry ${s}`);if(Jl(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Ah(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Fn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Lo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:_h(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Fn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=yr(t.traceHash,"Native acceptance trace hash");if(j(hH,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function _k(e){let t=Gl(e,"Native partial allowance");if(Jl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Fn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:Rk(t.change),scopeHash:yr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:_h(t.reason,"Partial allowance reason"),confirmedSummary:_h(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ck(t.sourceRevision),confirmedAt:Pk(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=yr(t.allowanceHash,"Native partial allowance hash");if(j(mH,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Ih(e){let t=Gl(e,"Native verification evidence");if(Jl(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=yr(t.implementationScopeHash,"Native verification implementation scope hash"),i=wH(t.acceptanceTrace),n=yr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:yr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(p=>Ah(p));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Fn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(p=>p.evidenceRefs))].sort(Fn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(p=>Ah(p));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Fn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Rk(t.change),sourceRevision:Ck(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:yr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Ek(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:gH(t.reportRef,"Native verification report ref"),reportHash:yr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:Ek(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Pk(t.createdAt,"Native verification timestamp")},d=yr(t.envelopeHash,"Native verification envelope hash");if(j(vH,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var xk,hH,mH,vH,Ul=I(()=>{"use strict";de();Di();Da();qi();xk=/^[a-f0-9]{64}$/u,hH="comet.native.acceptance-trace.v2",mH="comet.native.partial-allowance.v1",vH="comet.native.verification-evidence.v2"});import Ak from"node:path";function ni(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Nr(e,t){if(typeof e!="string"||!NH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hk(e,t){let r=tt(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function $k(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function RH(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>EH||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=Ak.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Ak.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function PH(e){let t=ni(e,"Native check receipt checker");ai(t,["policy","version","hash","limits"],"Native check receipt checker");let r=ni(t.limits,"Native check receipt limits");if(ai(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Ln||t.version!==Th||t.hash!==Tk||r.maxFiles!==Ue.maxFiles||r.maxFileBytes!==Ue.maxFileBytes||r.maxTotalBytes!==Ue.maxTotalBytes||r.maxIssues!==Ue.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Ln,version:Th,hash:Tk,limits:{...Ue}}}function _H(e){let t=ni(e,"Native check receipt contract");return ai(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Nr(t.expectedHash,"Native check expected contract hash"),beforeHash:Nr(t.beforeHash,"Native check before contract hash"),afterHash:Nr(t.afterHash,"Native check after contract hash")}}function AH(e){let t=ni(e,"Native check receipt implementation");return ai(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Nr(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Nr(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Nr(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Nr(t.afterSnapshotHash,"Native check after snapshot hash")}}function IH(e,t){let r=ni(e,`Native check batch ${t}`);ai(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:tt(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:tt(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:tt(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:tt(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:tt(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:tt(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Ue.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Ue.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function TH(e){let t=ni(e,"Native check receipt counts");ai(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:tt(t.filesSelected,"Native check filesSelected"),filesScanned:tt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:tt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:tt(t.bytesScanned,"Native check bytesScanned"),issueCount:tt(t.issueCount,"Native check issueCount"),recordedIssueCount:tt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(IH):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Ue.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Ue.maxFiles||r.bytesScanned>Ue.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function jH(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||jk.indexOf(e.kind)-jk.indexOf(t.kind)}function $H(e){if(!Array.isArray(e)||e.length>Ue.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=ni(i,`Native check issue ${n}`);if(ai(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!xH.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:RH(a.path,`Native check issue ${n} path`),line:Hk(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(jH);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function OH(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!CH.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=Ok.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function HH(e){return j(SH,e)}function Dk(e){let t=ni(e,"Native check receipt");if(ai(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Ik)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!bH.test(t.change))throw new Error("Native check receipt change name is invalid");let r=Hk(t.sourceRevision,"Native check source revision"),i=PH(t.checker),n=_H(t.contract),a=AH(t.implementation),o=HH({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Nr(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=$k(t.startedAt,"Native check receipt startedAt"),c=$k(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=TH(t.counts),u=$H(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=OH(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let p=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==p)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Ue.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Ue.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let f={schema:Ik,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=Nr(t.receiptHash,"Native check receipt content hash");if(j(yH,f)!==m)throw new Error("Native check receipt content hash mismatch");return{...f,receiptHash:m}}var Ik,yH,Ln,Th,Ue,NH,bH,kH,SH,EH,Tk,xH,jk,Ok,CH,jh=I(()=>{"use strict";de();Ik="comet.native.check-receipt.v1",yH="comet.native.check-receipt.v1",Ln="scoped-text-safety",Th=1,Ue=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),NH=/^[a-f0-9]{64}$/u,bH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kH="comet.native.checker-policy.v1",SH="comet.native.check-input.v1",EH=2048,Tk=j(kH,{policy:Ln,version:Th,limits:Ue,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),xH=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),jk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Ok=["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"],CH=new Set(Ok)});function qn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function oi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function br(e,t){if(typeof e!="string"||!FH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=mt(e).trim();if(!r||r.length>VH||r!==e.trim())throw new Error(`${t} is invalid`);return r}function $h(e,t){let r=jt(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function qo(e,t,r=jt,i=!1,n=WH){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function GH(e,t){if(typeof e!="string"||!LH.test(e))throw new Error(`${t} is invalid`);return e}function JH(e){let t=qn(e,"Native verification receipt bindings");if(oi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!qH.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:br(t.contractHash,"Native verification receipt contract hash"),scopeHash:br(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:br(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:br(t.artifactHash,"Native verification receipt artifact hash")}}function UH(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=MH.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function KH(e,t,r,i){let n=qn(t,`Native ${e} evidence`);if(e==="automated-check"){if(oi(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=$h(n.startedAt,"Native automated-check start time"),o=$h(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=qn(n.worktree,"Native automated-check worktree");if(oi(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=qn(n.afterFence,"Native automated-check after fence");if(oi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:jt(n.executable,"Native automated-check executable"),args:qo(n.args,"Native automated-check arguments",jt,!0),cwd:jt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:jt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:br(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:br(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:br(n.outputHash,"Native automated-check output hash"),outputSummary:jt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){oi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=UH(n.checkReceiptRef);if(br(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:qo(n.subjects,"Native static inspection subjects",jt,i==="required-check"),rule:jt(n.rule,"Native static inspection rule"),resultSummary:jt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return oi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:qo(n.steps,"Native manual evidence steps"),observations:qo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function YH(e){let t=qn(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=jt(t.actor,"Native verification receipt actor"),o=qo(t.acceptanceIds,"Native receipt acceptance IDs",GH,i==="required-check",zH).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Oh,kind:r,role:i,status:n,bindings:JH(t.bindings),acceptanceIds:o,actor:a,issuedAt:$h(t.issuedAt,"Native verification receipt issue time"),evidence:KH(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ln||s.actor!==`native-runtime:${Ln}`))throw new Error("Native required check policy identity is invalid");return s}function Bk(e){let t=qn(e,"Native verification receipt");if(oi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Oh)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=YH(i),a=br(t.receiptHash,"Native verification receipt hash");if(j(DH,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Hh(e){return j(BH,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Oh,DH,BH,FH,LH,qH,MH,VH,WH,zH,Mo=I(()=>{"use strict";de();jh();Di();Oh="comet.native.verification-receipt.v3",DH=Oh,BH="comet.native.declared-artifacts.v1",FH=/^[a-f0-9]{64}$/u,LH=/^acceptance-[a-f0-9]{64}$/u,qH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,VH=4096,WH=256,zH=1024});import{createHash as XH}from"node:crypto";import{promises as $t}from"node:fs";import tr from"node:path";function Dh(e,t){let r=tr.relative(e,t);return r===""||!tr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${tr.sep}`)}function QH(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Kl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Fk(e){let t=await $t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ZH(e,t){let r=tr.resolve(e),i=tr.resolve(t);if(!Dh(r,i))throw new Error("Native evidence path is outside its change");let n=[await Fk(r)],a=r;for(let o of tr.relative(r,i).split(tr.sep).filter(Boolean)){a=tr.join(a,o);let s=await Fk(a);if(!Dh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Lk(e){for(let t of e){let r=await $t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!QH(t,r)||await $t.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function eD(e,t,r={}){let i=await ZH(t,tr.dirname(e));await r.afterParentChainCaptured?.();let n=await $t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await $t.realpath(e);if(!Dh(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await $t.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await Lk(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Kl(s,n)||!Kl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Mn)throw new Error(`Native evidence document exceeds ${Mn} bytes`);await r.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(64*1024);for(;;){let v=Mn+1-d,g=await o.read(p,0,Math.min(p.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>Mn)throw new Error(`Native evidence document exceeds ${Mn} bytes`);u.push(Buffer.from(p.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,m,h]=await Promise.all([o.stat(),$t.lstat(e),$t.realpath(e)]);if(await Lk(i),!m.isFile()||m.isSymbolicLink()||h!==a||!Kl(s,f)||!Kl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Vk(e,t){if(!Mk.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function tD(e,t,r,i,n){if(!Mk.test(r))throw new Error("Native report evidence hash is invalid");let a=await Mi({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||XH("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Vn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function rD(e,t,r,i,n){let a=Vk(r,i);return n?tr.join(n,...a.split("/")):Mr(Y(e,t),a)}async function Mi(e){let t=rD(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ne(e.paths,t);return await V(r,t),eD(t,r,e.hooks)}function qk(e,t){return Wl(e,t)}function iD(e,t){let r=zl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function nD(e,t,r){let i=_k(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function aD(e,t,r){let i=Ih(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function oD(e,t,r,i=!1,n){let a=await Yl(e,t,r.implementationScopeRef,void 0,n);if(i&&await tD(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await Wk(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Vo(e,t,r,i,n){let a=Vn(r,"scopes"),o=iD(await Mi({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Vn(o.baselineProjectionRef,"snapshots"),c=Vn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Mi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>qk(d,s)),Mi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>qk(d,c))]);return kk({baseline:l,current:u,scope:o})}async function Yl(e,t,r,i,n){return(await Vo(e,t,r,i,n)).scope}async function Wk(e,t,r,i,n){let a=Vn(r,"allowances");return nD(await Mi({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Wo(e,t,r,i,n){let a=Vn(r,"receipts"),o=Bk(await Mi({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Wn(e,t,r,i,n){let a=Vn(r,"verifications"),o=aD(await Mi({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await oD(e,t,o,!1,n),o}var Mk,Mn,SK,si=I(()=>{"use strict";oe();K();Lt();qi();Ul();Mo();Mk=/^[a-f0-9]{64}$/u,Mn=Li,SK=3*Mn});import zi from"node:path";import{realpathSync as WF}from"node:fs";Ji();Ui();import{execFileSync as hx}from"child_process";import mx from"fs";import di from"path";import{AsyncLocalStorage as Tm}from"node:async_hooks";ta();var pi=new Tm,jm=new Tm;function $m(e){return pi.getStore()?e():pi.run(new Map,e)}function vx(e){let t=pi.getStore();for(let r of e)t?.set(xr(r.root),e);return e}function ia(e,t){return Zn(()=>hx("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function na(e,t){return xr(e)===xr(t)}function xr(e){let t=di.resolve(e);try{let r=mx.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function we(e){try{let t=jm.getStore()?.get(xr(e)),r=pi.getStore()?.get(t??xr(e));if(r){let c=aa(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=di.resolve(ia(e,["rev-parse","--show-toplevel"])),n=pi.getStore()?.get(xr(i))??Om(e),a=aa(i,n);if(pi.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=ia(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!na(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function us(e){try{let t=pi.getStore()?.get(jm.getStore()?.get(xr(e))??xr(e));return t?t.map(r=>({...r})):(ia(e,["rev-parse","--is-inside-work-tree"]),Om(e))}catch{return[]}}function Om(e){let t=gx(ia(e,["worktree","list","--porcelain","-z"]));return vx(t),t.map(r=>({...r}))}function gx(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:di.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 Cr(e){return us(e).map(t=>t.root)}function aa(e,t){let r=t.find(a=>na(di.resolve(a.root),di.resolve(e)));if(!r)return null;let i=di.resolve(t[0].root),n=di.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!na(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function nr(e,t){try{let r=ia(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}de();var Lf=ir(Bt(),1);import{promises as tb}from"fs";import Kr from"path";at();oe();Ni();Qe();Re();K();Ct();Rn();import{createHash as m$}from"crypto";import v$ from"path";var dt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});Re();K();import{constants as pl,promises as _t}from"node:fs";import At from"node:path";import{TextDecoder as u$}from"node:util";import o$ from"path";un();Fr();var Yj=ir(Bt(),1);un();Fr();cr();cr();ln();Rp();un();cr();var yW=4*1024*1024;import{AsyncLocalStorage as Xj}from"node:async_hooks";var Qj=new Xj;function Zj(){let e=Qj.getStore();return e?.active?e:null}function e$(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function jN(e,t){return(...r)=>{let i=Zj();if(i===null)return t(...r);let n=e$(`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}}ln();var xW=jN("hookWritePolicy",async e=>(await Sp(e))?.hook??{allow_paths:[]});Va();import{randomUUID as t$}from"node:crypto";import{promises as ll}from"node:fs";import ON from"node:path";var ul="comet.selection.v2",HN=16*1024;function dl(e){return ON.join(e,".comet","current-change.json")}function r$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $N(e){return e===null||typeof e=="string"}function DN(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(!r$(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&&!$N(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ul,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==ul)throw new Error(`current change selection schema must be ${ul}`);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(!$N(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 Tf(e){let t;try{let i=dl(e),{bytes:n}=await Si(i,HN,{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",...DN(t)}}async function jf(e,t){let r=DN(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=dl(e),n=`${i}.${t$()}.tmp`;await ll.mkdir(ON.dirname(i),{recursive:!0});try{await ll.writeFile(n,`${JSON.stringify(r.selection,null,2)}
184
+ `,"utf8"),await ll.rename(n,i)}catch(a){throw await ll.rm(n,{force:!0}),a}}Ep();Ba();var BN=(e,t)=>{let r=e[t];return r==null?null:String(r)};function fo(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function po(e,t){let r=fo(e,t);if(o$.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function s$(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function FN(e){if(!e.run_id)return null;let t=fo(e,"run_id"),r=fo(e,"skill"),i=fo(e,"skill_version"),n=fo(e,"skill_hash"),a=po(e,"pending_ref"),o=po(e,"trajectory_ref"),s=po(e,"context_ref"),c=po(e,"artifacts_ref"),l=po(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:BN(e,"current_step"),iteration:u,pending:BN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:s$(e)}}var Az=Number.MAX_SAFE_INTEGER;var c$=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function l$(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},r=FN(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function $f(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!c$.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return l$(t)}oe();Lt();var Pn={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};function hl(e,t){let r=At.relative(e,t);return r===""||!At.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${At.sep}`)}function d$(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function fl(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}function p$(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ml(e,t,r){let i=dt[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=At.resolve(e),a=At.resolve(n,...i.slice(8).split("/"));if(!hl(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function LN(e){let t=await _t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await _t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function f$(e,t){let r=At.resolve(e),i=At.resolve(t);if(!hl(r,i))throw new Error("Native Run path is outside its change");let n=[await LN(r)],a=r;for(let o of At.relative(r,i).split(At.sep).filter(Boolean)){a=At.join(a,o);let s;try{s=await LN(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!hl(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function qN(e){for(let t of e){let r=await _t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!p$(t,r)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function h$(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function vl(e,t,r,i,n){let a=await f$(e,At.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await _t.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=d$(o),c=await _t.realpath(t);if(!hl(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?pl.O_RDONLY:pl.O_RDONLY|pl.O_NOFOLLOW|pl.O_NONBLOCK,u;try{u=await _t.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,p,f]=await Promise.all([u.stat(),_t.lstat(t),_t.realpath(t)]);if(await qN(a),!d.isFile()||!p.isFile()||p.isSymbolicLink()||f!==c||!fl(s,d)||!fl(s,p))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await h$(u,r,i);await n?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([u.stat(),_t.lstat(t),_t.realpath(t)]);if(await qN(a),!v.isFile()||v.isSymbolicLink()||g!==c||!fl(s,h)||!fl(s,v))throw new Error(`${i} changed while reading`);let b;try{b=new u$("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${i} is not valid UTF-8`,{cause:k})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function MN(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function Of(e){return $f(e)}async function _n(e,t){let r=ml(e,"stateRef"),i=await vl(e,r,Pn.runStateBytes,"Native Run state",t);return i?$f(MN(i.text,"Native Run state")):null}async function Ai(e,t,r){let i=ml(e,"trajectoryRef",t),n=await vl(e,i,Pn.trajectoryBytes,"Native Run trajectory",r);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Pn.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Pn.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function VN(e,t,r){return(await vl(e,ml(e,"trajectoryRef",t),Pn.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function gl(e,t,r){let i=await vl(e,ml(e,"checkpointRef",t),Pn.checkpointBytes,"Native Run checkpoint",r);return i?MN(i.text,"Native Run checkpoint"):null}var g$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Hf(e){return m$("sha256").update(e).digest("hex")}function w$(e,t){if(!g$.test(t))throw new Error(`Invalid Native change name: ${t}`);return v$.join(Y(e,t),"trajectory.jsonl")}function y$(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function N$(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function b$(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=y$(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
185
+ `)])}catch(d){if(!N$(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Hf(t),targetHash:Hf(l),tailHash:Hf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function k$(e,t){let r=w$(e,t);await V(Ne(e,r),r);let i=Y(e,t),n=await VN(i,dt.trajectoryRef);return n===null?{status:"clean",file:r}:b$(r,Buffer.from(n))}async function WN(e,t){let r=await k$(e,t);return"inspection"in r?r.inspection:r}import{createHash as S$}from"node:crypto";import{promises as wl}from"node:fs";import hr from"node:path";oe();at();Re();K();var ho=/^[a-f0-9]{64}$/u,zN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,E$=16*1024,Bf=process.platform,x$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function An(e){return x$.has(e)}function KN(e,t){let r=hr.relative(e,t);return hr.isAbsolute(r)||r===".."||r.startsWith(`..${hr.sep}`)?null:r.replaceAll("\\","/")||"."}function YN(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function XN(e,t){if(e.length===0||YN(e)||e.includes("\\")||hr.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=hr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Ff(e,t){return S$("sha256").update(`${e}
186
+ ${t}`).digest("hex")}async function GN(e,t){let r=await wl.realpath(t),i=await wl.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Bf==="win32"?hr.normalize(r).toLowerCase():r;return Ff(e,`${n}
170
187
  ${i.dev}
171
188
  ${i.ino}
172
- ${i.birthtimeMs}`)}async function xy(e,t){let r=await Tc.realpath(t),i=await Tc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Vf==="win32"?nr.normalize(r).toLowerCase():r;return Mf(e,n)}function Ij(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 Bf(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ry(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ay(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Bf(e.changeBranch,"Native workspace change branch"),Bf(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 jj(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"||!Sy.test(t.baseCommit)||typeof t.targetCommit!="string"||!Sy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Bf(t.targetBranch,"Native workspace Git target branch")}function $c(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"||!Fa.test(String(t.projectRootId))||!Fa.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Ij(t.capturedAt),_y(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&&!Fa.test(String(t.projectRootPathId))||a&&!Fa.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Fa.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&jj(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(Ay(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 Tj(e,t){return nr.join(K(e,t),"workspace.json")}function $j(e,t){let r=Tj(e,t),i=we(e,r),n=Py(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:_y(n,"Native workspace file ref")}}async function Oj(e,t){try{let r=$j(e,t),i=await ee({root:r.root,ref:r.ref,maxBytes:_j});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function La(e,t){let r=ve(e.projectRoot),i={projectRoot:nr.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await ar(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await pn({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Hj(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Py(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ve(e.paths.projectRoot),i=r.isGitWorktree?Ut(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Ut(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Ey("comet.native.workspace-project-root.v2",e.paths.projectRoot),Ey("comet.native.workspace-native-root.v2",e.paths.nativeRoot),xy("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),xy("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&Ay(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Mf("comet.native.workspace-session.v2",`${s}
189
+ ${i.birthtimeMs}`)}async function JN(e,t){let r=await wl.realpath(t),i=await wl.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Bf==="win32"?hr.normalize(r).toLowerCase():r;return Ff(e,n)}function C$(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 Df(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||YN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function QN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Df(e.changeBranch,"Native workspace change branch"),Df(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 R$(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"||!zN.test(t.baseCommit)||typeof t.targetCommit!="string"||!zN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Df(t.targetBranch,"Native workspace Git target branch")}function yl(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"||!ho.test(String(t.projectRootId))||!ho.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");C$(t.capturedAt),XN(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&&!ho.test(String(t.projectRootPathId))||a&&!ho.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ho.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&R$(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(QN(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 P$(e,t){return hr.join(Y(e,t),"workspace.json")}function _$(e,t){let r=P$(e,t),i=Ne(e,r),n=KN(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:XN(n,"Native workspace file ref")}}async function A$(e,t){try{let r=_$(e,t),i=await re({root:r.root,ref:r.ref,maxBytes:E$});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function mo(e,t){let r=we(e.projectRoot),i={projectRoot:hr.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await mr(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await In({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function I$(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=KN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=we(e.paths.projectRoot),i=r.isGitWorktree?nr(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:nr(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([GN("comet.native.workspace-project-root.v2",e.paths.projectRoot),GN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),JN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),JN("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&QN(e.binding);let p={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Ff("comet.native.workspace-session.v2",`${s}
173
190
  ${c}
174
- ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return $c(p),p}async function ar(e,t){let r=await Oj(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:($c(r),r)}async function Oc(e){$c(e.identity);let t=await Hj({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Vf==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function pn(e){if($c(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Oc(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ve(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Iy(e,t){let r=await ar(e,t);if(r===null)return null;let i=await pn({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}xa();nc();nc();var Hc=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"},Ba=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"},Dc=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},f1=_s("en");function Ne(e,t){ui(t);let r=qr.join(e.changesDir,t);if(!B(e.changesDir,r))throw new Error("Native change path escaped");return r}async function qc(e,t){let r=K(e,t),i=qr.join(r,"schema-migration.json");await V(B(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ty.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function $y(e,t){let r=K(e,t),i=qr.join(r,"checkpoint-journal.json");await V(B(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ty.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Oy(e,t=qr.dirname(e)){let r=qr.relative(t,e).split(qr.sep).join("/"),i=await ee({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Wf.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 zf(e,t){let r=qr.join(Ne(e,t),Dt);await V(e.nativeRoot,r);let i=ic(await Oy(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await qc(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await Fj(e,i.state),i)}async function Hy(e,t){let r=qr.join(Ne(e,t),Dt);await V(e.nativeRoot,r);let i=ic(await Oy(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function Fj(e,t){if(await Sc(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Vt(e,t){let r=await zf(e,t);if(r.status==="migration-required")throw new Xi(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new tr(r.schema,r.minimumRuntimeVersion);return await Iy(e,t),r.state}Ge();import{promises as SH}from"fs";oi();import{promises as Jf}from"fs";import qy from"path";et();Lt();U();var Fy=["outcome","scope","nonGoals","acceptanceExamples"],Dy=[...Fy,"constraints","decisions","openQuestions","verificationExpectations"],Lj=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],Bj=new Set(["nonGoals","decisions","openQuestions"]),Ly={maxFileBytes:md};function By(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
175
- `).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}async function Vj(e,t){let r=qy.resolve(e,...t.split(/[\\/]/u));if(!B(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Jf.realpath(e),n=await Jf.realpath(r);if(!B(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Jf.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Va(e){return{valid:e.length===0,findings:e}}function Vy(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 Mj(e){return Vy(e).trim()}function Gf(e){let t=Mj(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(`
176
- `).trim()}function Wj(e){let t=Gf(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 zj(e){let t=Gf(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 My(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 Fc(e,t,r={}){let i=[],n;try{n=(await ee({root:e,ref:t,maxBytes:Ly.maxFileBytes})).text}catch(s){return Va([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of By(n))a.set(Rs(s)??s,c);for(let s of Dy)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?Dy:Fy;for(let s of o){let c=a.get(s)??"";Gf(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):zj(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!Bj.has(s)&&Wj(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return My(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Va(i)}async function Uf(e,t){let r=[],i;try{i=(await ee({root:e,ref:t,maxBytes:Ly.maxFileBytes})).text}catch(a){return Va([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of By(i))n.set(mg(a)??a,o);for(let a of Lj)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Va(r)}function Ma(e,t){return qy.join(e.specsDir,t,"spec.md")}async function Wy(e,t){let r=[],i=Ne(e,t.name);for(let n of t.spec_changes){let a=Ma(e,n.capability),o=null;try{await V(e.nativeRoot,a),o=await Pf(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await Vj(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Va(r)}_a();ce();et();_a();ce();import zy from"node:path";var Jj="comet.native.contract.v1",Gj="comet.native.acceptance-set.v1",Jy=/^[a-f0-9]{64}$/u,Wa={maxAcceptanceCriteria:Ra.maxCriteria};function Gy(e,t){let r=zy.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||zy.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Uy(e){return T("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
177
- `))}function Uj(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Jy))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Jy))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Gy(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Uy(e.markdown)},markdown:e.markdown}}function Kj(e,t){return Ky(e.id,t.id)}function Ky(e,t){return e<t?-1:e>t?1:0}function Yy(e){let t=Gy(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(Uj).sort((d,f)=>Ky(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=uf(e.briefMarkdown,t,Wa.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...df(f,d.source,Wa.maxAcceptanceCriteria-a.length)),a.push(...fw(f,d.source,Wa.maxAcceptanceCriteria-a.length)));if(a.sort(Kj),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Wa.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Wa.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Uy(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=T(Gj,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:T(Jj,u)}}var Yj={maxSpecs:64};async function hn(e){if(e.specChanges.length>Yj.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ee({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ee({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Yy({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Ge();Ee();import{promises as lT}from"node:fs";import Qf from"node:path";Et();import{promises as rT}from"node:fs";le();Aa();import Zy from"node:path";function za(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ja(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 Oe(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 mn(e,t){return e===null?null:Oe(e,t)}function vn(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 iT(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 nT(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function gn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Yf(e,t){if(e===null)return null;let r=Oe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function aT(e,t){let r=Oe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Xf(e,t){let r=Oe(e,t);if(!Zy.isAbsolute(r))throw new Error(`${t} must be absolute`);return Zy.resolve(r)}function oT(e,t){let r=`Native local checks[${t}]`,i=za(e,r);if(Ja(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>Oe(u,`${r}.argv[${d}]`,!0)),a=gn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Yf(i.startedAt,`${r}.startedAt`),s=Yf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=vn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=za(i.activeProcess,`${r}.activeProcess`),d=gn(u.status,["starting","running"],`${r}.activeProcess.status`);if(Ja(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:vn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:Oe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:Oe(i.id,`${r}.id`),name:Oe(i.name,`${r}.name`),operationId:Oe(i.operationId,`${r}.operationId`),status:a,repeatable:nT(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:vn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Xf(i.cwd,`${r}.cwd`),exitCode:iT(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Oe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:gn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Oe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function sT(e){let t="Native local execution state",r=za(e,t);if(Ja(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==oc)throw new Error(`Native local execution schema must be ${oc}`);let i=za(r.workspace,"Native local workspace");Ja(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=za(r.execution,"Native local execution");Ja(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Yf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Oe(o.operationId,"Native local execution.operationId"),stage:gn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:gn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:mn(o.executionId,"Native local execution.executionId"),status:gn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:vn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:aT(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:vn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:Oe(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(oT);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:oc,change:Oe(r.change,"Native local change"),basedOnStateVersion:vn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:mn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:mn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:mn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:mn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Xf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Xf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:mn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Oe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function Lc(e){let t;try{t=await rT.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 sT(r)}function eN(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}wt();U();var tN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rN="comet-state.yaml",iN="state.json";function gi(e,t){if(!tN.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Qf.join(e.changesDir,t);if(!B(e.changesDir,r))throw new Error("Native change path escaped");return r}function Bc(e,t){return Qf.join(gi(e,t),rN)}function Fr(e,t){return Qf.join(vt(e,t),iN)}async function Ga(e,t){try{let r=await lT.readFile(Bc(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function ot(e,t){return jr(Bc(e,t))}async function Zf(e){let t=await ot(e.paths,e.name),r=Fr(e.paths,e.name);try{let i=await Lc(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}le();et();ce();var bN=Gt(It(),1);import{promises as zT}from"node:fs";import xt from"node:path";Et();et();ce();Ge();U();wt();Wc();Wc();yi();Mr();Et();Ks();le();ce();Yc();Ee();U();vN();yi();Mr();Xc();Et();Ge();Xc();ka();U();var Qc=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function sp(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`}import VT from"node:path";Et();Ge();Ee();yi();Mr();async function Zc(e){let t=sp(e.parent),r=Ut(e.paths.projectRoot,t);if(!r)return null;let i=Ut(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=hr(e.paths.projectRoot).map(o=>VT.resolve(o)).find(o=>ve(o).currentBranch===t);if(!n)return null;let a=Uc({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 ip(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function cp(e,t){let r=xt.normalize(xt.resolve(e)),i=xt.normalize(xt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function JT(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 GT(e){let t=JT(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 lp(e){try{let t=await ee({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return GT(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function up(e){return T("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 UT(e){let t=hr(e.projectRoot);t.some(i=>cp(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>xt.resolve(n)))]){let n=await ke(i);n&&r.push({projectRoot:i,paths:await Ot(i,n.native.artifact_root),parent:cp(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function KT(e,t){let r=xt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await jr(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function YT(e,t){let r;try{r=await zT.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=xt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await jr(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function XT(e,t,r){let i=xt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${xt.sep}`))return null;let n=i.split(xt.sep).join("/");try{let a=(0,bN.parseDocument)(Ue(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Be(a.toJS({mapAsMap:!1}))}catch{return null}}function QT(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 NN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Qa(e){let t=xt.join(e.paths.changesDir,e.state.name),r=await lp(t),i=null,n;try{n=await Mt({changeDir:t,validation:Br(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 Ke(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Kc(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,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=up({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===Lr){let g=await Ke(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await Zc({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await Vr(e.paths,x))}}if(g){let N=Kc(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),S=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of S){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:S,readyChildren:S.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await UT(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let S of await YT(g,l)){let N={...S,source:g,committedState:XT(g,S.file,b)};u.set(S.state.name,[...u.get(S.state.name)??[],N])}for(let S of l){let N=await KT(g,S);N&&d.set(S,[...d.get(S)??[],{source:g,state:N}])}}let f=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&NN(w,o));if(b){f.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let S=u.get(g.name)?.[0];if(S){f.set(g.name,{kind:"blocked",phase:S.state.phase,projectRoot:S.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&f.set(g.name,QT(N[0].state,N[0].source,o))}let p=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let S=p.get(g),x=S.depends_on.map(h).every(({status:O})=>O==="done"),w=f.get(g),k=w?.kind==="active"&&x?S.depends_on.filter(O=>!(u.get(O)??[]).some(({source:j,committedState:Y})=>cp(j.projectRoot,w.projectRoot)&&Y?.name===O&&NN(Y,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&k.length===0?"active":"blocked",x?k.length>0&&(y=`Native child ${g} does not include merged dependencies: ${k.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:S.summary,dependsOn:[...S.depends_on],covers:[...S.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(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")}}wt();hi();Ua();Jc();Ee();ff();tf();wt();hi();le();oi();Ua();U();oi();Kr();Ge();var lb=Gt(It(),1);_r();var X2=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 iJ=256*1024;wt();hi();Mr();var wO=_s("en");Ge();Ee();yi();Mr();wt();hi();Et();Ks();ce();Yc();import xn from"node:path";Ee();hi();U();function bO(e,t){let r=xn.relative(xn.resolve(e),xn.resolve(t));if(xn.isAbsolute(r)||r===".."||r.startsWith(`..${xn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(xn.sep).join("/");return mN(e,i),i}function pb(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:bO(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var TG=1024*1024*1024;Ee();Jc();Ua();Mr();Ee();Mr();Ee();bf();var SK=16*1024;async function hb(e){let t=await Hf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(ui(t.selection.change),t.selection)}async function mb(e,t){return Se(e,`select change ${t}`,async()=>{ui(t),await Ga(e,t)?await ot(e,t):await Vt(e,t),await Df(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}U();async function vb(e,t){let r=[],i=K(e,t.name),n=Ir(i,at.stateRef),a;try{a=await dn(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Ir(i,a.trajectoryRef),s=await ky(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await vi(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Ir(i,a.checkpointRef);try{let u=await jc(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}ln();import VO from"path";import{isDeepStrictEqual as Dp}from"util";le();Lt();ka();Ee();U();yt();Ni();ce();ce();var Cn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var kO=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function SO(e,t){return e<t?-1:e>t?1:0}function EO(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!kO.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(SO)}function Ap(e=[]){return EO(e,"Native repair failed check IDs",Cn.maxFailedCheckIds,!0)}function gb(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function xO(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:gb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&gb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ip(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(xO(i,a))break;r+=1,i=a}return r}nl();Ei();function jp(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var wb="repairStagnation",Xe={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},PO=/^[a-f0-9]{64}$/u;var RO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),_O=["data","runId","sequence","timestamp","type"],yb=["disposition","overrideSummaryHash","signatureHash"],AO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Nb=12;function $p(e,t){return e<t?-1:e>t?1:0}function bb(e,t,r){let i=Object.keys(e).sort($p);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function cl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function mo(e,t){if(typeof e!="string"||!PO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function IO(e){if(!Array.isArray(e)||e.length>Cn.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort($p)}function kb(e){if(typeof e!="string"||e.length===0||e.length>Xe.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Tp(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Xe.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xe.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Xe.maxTextCharacters&&(!n||e.length>Xe.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Xe.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Xe.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Tp(s,t+1,r,`${i}[${c}]`));return}let a=cl(e,i),o=Object.keys(a);if(o.length>Xe.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xe.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Xe.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Tp(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function jO(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function TO(e,t,r){let i=cl(e,`Native repair trajectory event ${t+1}`);if(bb(i,_O,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(jO(i.timestamp),typeof i.type!="string"||!RO.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(kb(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Tp(i.data,0,n,"Native trajectory event data"),cl(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Op(e){let t=cl(e,"Native repair trajectory projection"),r=Object.keys(t).sort($p),i=r.length===yb.length&&r.every((l,u)=>l===yb[u]);i||bb(t,AO,"Native repair trajectory projection");let n=mo(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:mo(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=mo(t.contractHash,"Native repair trajectory contract hash"),s=IO(t.failedAcceptanceIds),c=Ap(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function $O(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function OO(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??Nb;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ip({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<Cn.warningAtConsecutiveFailures?"continue":a<Cn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function HO(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??Nb;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Sb(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xe.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=kb(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=TO(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Xe.maxTotalDataNodes||c>Xe.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?mo(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?mo(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,wb)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Op(f[wb]);if($O(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),OO(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");HO(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>Cn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function Eb(e){return Sb(e).history}function xb(e){let t=Sb(e).latestProjection;return t?{...t}:null}Lt();var Pn={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:[]},Hp=Q("comet-native-runtime:v3:scope-reopen"),DO=[{skillVersion:"3",skillHash:Q("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Q("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Q("comet-native-runtime:v1")}];function Cb(e){return e.skillVersion===Pn.definition.metadata.version&&e.skillHash===Hp||DO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Lt();Lt();function Pb(e){return Q(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}xa();var jb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],MO=new Set(jb),Tb=new Set([...jb,"minimum_runtime_version","revision"]),WO=new Set([...Tb,"operation"]),qp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),zO=new Set([...qp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Fp=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Bp(e,t){return VO.join(K(e,t),"transition.json")}function ul(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Vp(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function ll(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!zO.has(u)),a=[...qp].find(u=>!Object.hasOwn(r,u)),o=qp.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(jp(r.summary,"Native transition journal event summary"),st(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(r.noCodeReason!==null&&(jp(r.noCodeReason,"Native transition journal event no-code reason"),st(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Op(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function JO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Lp({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Lp(e,t)}function Mp(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?JO(e.eventData,e.evidenceHash):Lp(e.eventData,e.evidenceHash),n=Ff(e.nextRun),a=e.previousRun===null?null:Ff(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function Rb(e,t,r=!1){if(e.skill!==Pn.definition.metadata.name||(r?!Cb(e):e.skillVersion!==Pn.definition.metadata.version||e.skillHash!==Hp)||e.orchestration!==Pn.definition.orchestration.mode||e.pendingRef!==at.pendingRef||e.trajectoryRef!==at.trajectoryRef||e.contextRef!==at.contextRef||e.artifactsRef!==at.artifactsRef||e.checkpointRef!==at.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function _b(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ab(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Wp(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(Rb(o,"next Run",i||a!==null),Ab(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Rb(a,"previous Run",!0),Ab(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Dp(_b(a),_b(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function GO(e,t,r){return Q(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function $b(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function Ib(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function zp(e,t,r,i,n=!1){let a=r.eventData,o=Ib(e),s=Ib(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Dp(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Dp(e.spec_changes,t.spec_changes),l=Pb({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(i==="spec-rebase"){let c=GO(e.name,a.summary,t.spec_changes),l=Q(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function UO(e,t){let r=ul(e);if(Vp(r,WO),r.schema!==Ki)throw new Error(`Expected Native transition schema ${Ki}`);let i=ll(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Ki} minimum_runtime_version must be ${3}`);let n=ll(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Mp(r,t),o=qt(r.previousState),s=qt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(zp(o,s,a,r.operation),Wp(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Ki,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function KO(e,t){let r=ul(e);if(Vp(r,MO),r.schema!==Ea)throw new Error(`Expected Native transition schema ${Ea}`);let i=Mp(r,t,!0),n=di(r.previousState),a=di(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return zp(n,a,i,$b(n,a,i.eventData),!0),Wp(n,a,i,!0),{schema:Ea,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function YO(e,t){let r=ul(e);if(Vp(r,Tb),r.schema!==Yi)throw new Error(`Expected Native transition schema ${Yi}`);if(ll(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Yi} minimum_runtime_version must be 2`);let n=ll(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Mp(r,t,!0),o=fi(r.previousState),s=fi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(zp(o,s,a,$b(o,s,a.eventData),!0),Wp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Yi,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function XO(e,t){let r=ul(e);if(r.schema===Ki)return{status:"current",journal:UO(r,t)};if(r.schema===Ea)return{status:"migration-required",journal:KO(r,t)};if(r.schema===Yi)return{status:"migration-required",journal:YO(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function QO(e,t){let r=Bp(e,t),i=we(e,r);await V(i,r);try{let n=await Or({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return XO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ob(e,t){let r=await QO(e,t);if(!r)return null;if(r.status==="migration-required")throw new Fp(t);return r.journal}var ZO=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function e0(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function t0(e){return e?e.map(e0).join(" "):null}function r0(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function ct(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function i0(e){return e.map(t=>ct(t,[],null))}function n0(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[ct("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(ct("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(ct("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),ct("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(ct("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(ct("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),ct("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Pe(e,t){let r=t.commandArgs===void 0?r0(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?t0(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??i0(t.requiredInputs??[])}}function dl(e){let r=(e.findings??[]).filter(d=>!fn(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||ZO.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Pe(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Pe(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[ct("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Pe(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Pe(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Pe(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Pe(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[ct("summary",["--summary"],"<summary>")]});if(n)return Pe(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Pe(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[ct("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Pe(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Pe(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Pe(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Pe(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Pe(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[ct("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Pe(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Pe(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=n0(e.state);return Pe(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import vo from"path";U();var Hb=8,a0={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function o0(e){let t=a0[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:fn(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function s0(e,t,r){if(!r.path)return null;let i;if(vo.isAbsolute(r.path)?i=vo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=vo.resolve(Ne(e,t.name),...r.path.split(/[\\/]/u)):i=vo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!B(e.projectRoot,i))return null;let n=vo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function c0(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Jp(e){return e.findings.map(t=>{let r=o0(t.code);return{code:t.code,message:t.message,severity:r.severity,path:s0(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:c0(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function Gp(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,Hb),truncated:t.length>Hb}}le();import Rn from"path";Lt();U();yt();ua();Ni();var go={maxArtifacts:128},_n=/^[a-f0-9]{64}$/u;function fl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pl(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Yr(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function Db(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Up(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function l0(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Rn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Rn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function qb(e,t){return Rn.join(K(e,t),"checkpoints","progress.json")}function wo(e,t){return Rn.join(K(e,t),"checkpoint-journal.json")}function Fb(e,t,r){if(!_n.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Rn.join(K(e,t),"checkpoints","manifests",`${r}.json`)}function u0(e){if(!_n.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Kp(e,t,r){let i=await Or({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function d0(e,t){let r=fl(e,`checkpoint manifest artifact ${t}`);pl(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=l0(Yr(r.path,`checkpoint artifact ${t} path`,4096)),n=jt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!_n.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Up(r.size,`checkpoint artifact ${t} size`)}}function Yp(e,t){let r=fl(e,"Native checkpoint manifest");if(pl(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>go.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(d0),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Up(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Lb(e){return Q(JSON.stringify(Yp(e,e.change)))}function Bb(e,t){let r=fl(e,"Native progress checkpoint");if(pl(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Db(r.previousRevision,"Native checkpoint previousRevision"),a=Db(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Yr(r.manifestHash,"Native checkpoint manifestHash",64);if(!_n.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=u0(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Yr(r.inputHash,"Native checkpoint inputHash",64);if(!_n.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Yr(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Up(r.artifactCount,"Native checkpoint artifactCount");if(u>go.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Yr(r.summary,"Native checkpoint summary"),f=Yr(r.nextAction,"Native checkpoint nextAction");if(st(d)!==d||st(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Yr(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function f0(e,t){let r=fl(e,"Native checkpoint journal");if(pl(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=qt(r.previousState),n=qt(r.nextState),a=Bb(r.checkpoint,t),o=Yp(r.manifest,t),s=Yr(r.inputHash,"Native checkpoint journal inputHash",64),c=Q(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!_n.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Lb(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function p0(e,t,r){let i=Rn.resolve(e.projectRoot,...t.split("/"));if(!B(e.projectRoot,i)||B(e.nativeRoot,i)||B(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=pd(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await kf({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function h0(e,t){let r=qb(e,t),i=we(e,r);await V(i,r);try{return Bb(await Kp(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function m0(e,t,r){let i=Fb(e,t,r),n=we(e,i);await V(n,i);let a=await Kp(n,i,"Native checkpoint manifest"),o=Yp(a,t);if(Vb(e,o),Lb(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Xp(e,t){let r=wo(e,t),i=we(e,r);await V(i,r);try{let n=f0(await Kp(i,r,"Native checkpoint journal"),t);return Vb(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Vb(e,t){for(let r of t.artifacts){let i=pd(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function Mb(e){let t;try{t=await h0(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:qb(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await m0(e.paths,e.name,t.manifestHash);let a=Q(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await p0(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Fb(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var Wb=240,zb=8,hl=50;function Jb(e){let t=Array.from(e);return t.length<=Wb?e:`${t.slice(0,Wb-1).join("")}…`}function v0(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function g0(e){let t=[...new Set(e.map(v0))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,zb),reasonCount:e.length,codesTruncated:t.length>zb};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,hl),reasonsTruncated:e.length>hl}}}async function Gb(e){let t=null;try{let s=await Xp(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:wo(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:wo(e.paths,e.state.name)}}let r=await Mb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=g0(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:go.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:Jb(r.checkpoint.summary),nextAction:Jb(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:go.maxArtifacts}}import{promises as vH}from"node:fs";import fk from"node:path";ce();import Ub from"node:path";var w0="comet.native.archive-preflight.v1",y0="comet.native.archive-preflight.v1",N0="comet.native.archive-operation.v1",b0=/^[a-f0-9]{64}$/u,Kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,k0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ml(e,t){return e<t?-1:e>t?1:0}function S0(e,t){if(typeof e!="string"||!b0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function dr(e,t){return e===null?null:S0(e,t)}function E0(e,t){let r=Ub.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Ub.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function x0(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function C0(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function P0(e,t){if(!Kb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=dr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=dr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=dr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function R0(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:dr(e.contractHash,"Native archive contract hash"),acceptanceHash:dr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:dr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:dr(e.reportHash,"Native archive report hash"),envelopeHash:dr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:dr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function _0(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!k0.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(ml);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function A0(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ml)}function Yb(e){if(!Kb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(P0).sort((l,u)=>ml(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:T(N0,l)})),i=R0(e.evidence),n=C0(e.workspace),a=[...new Set([..._0(e.findingCodes??[]),...A0({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(ml),o=x0(e.revision),s=E0(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:w0,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:T(y0,c)}}et();ce();import{createHash as I0}from"node:crypto";import Xb from"node:path";var j0="comet.native.conflict-radar.v1",We=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}),T0="comet.native.conflict-radar.v1",$0="comet.native.conflict-radar-signals.v1",O0=/^[a-f0-9]{64}$/u,ek=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,H0=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),D0=new Set(["capability","operation","baseHash"]),q0=new Set(["path","kind"]);function An(e,t){return e<t?-1:e>t?1:0}function Qp(e){return Buffer.byteLength(e,"utf8")}function Zp(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function eh(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Qp(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function F0(e,t){let r=eh(e,t,We.maxArtifactPathBytes),i=Xb.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||Xb.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function tk(e,t){if(typeof e!="string"||!O0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function L0(e,t){let r=Zp(e,D0,t),i=eh(r.capability,`${t} capability`,We.maxCapabilityBytes);if(!ek.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:tk(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function B0(e,t){let r=Zp(e,q0,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:F0(r.path,`${t} path`),kind:r.kind}}function V0(e,t){let r=Zp(e,H0,`Conflict radar change ${t}`),i=eh(r.name,`Conflict radar change ${t} name`,We.maxNameBytes);if(!ek.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>We.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>We.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>L0(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>An(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>B0(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>An(c.path,l.path)||An(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:tk(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function M0(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>We.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(V0).sort((n,a)=>An(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>We.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>We.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function W0(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function z0(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function J0(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function G0(e,t){let r=[],i=I0("sha256").update(`${$0}
178
- [`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Tn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<We.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(W0(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=z0(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:J0(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function Qb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function U0(e,t){return Qb(e.classification)-Qb(t.classification)||An(e.left,t.left)||An(e.right,t.right)}function Zb(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:j0,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function rk(e){let t=M0(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(G0(t[s],t[c]));r.sort(U0);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=T(T0,{changes:t,relationships:i}),a=r.slice(0,We.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Zb(t,r,a,n);for(;a.length>0&&Qp(JSON.stringify(o))>We.maxSerializedBytes;)a=a.slice(0,-1),o=Zb(t,r,a,n);if(Qp(JSON.stringify(o))>We.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}Kr();yt();var K0=4096;async function Y0(e,t=We.maxChanges){try{let r=await $a({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function ik(e,t){let r=await Vt(e,t),[i,n]=await Promise.all([r.implementation_scope?ol(e,t,r.implementation_scope):null,ar(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function vl(e,t,r={}){let n=(await Y0(e,K0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await ik(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await ik(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=rk([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}Ge();U();_a();et();Kr();ln();Ei();nl();import{execFile as sH}from"node:child_process";Js();op();import{promisify as cH}from"node:util";Ee();le();Ep();U();Tt();import{constants as th,promises as lt}from"node:fs";import In from"node:path";var Q0=/^[a-f0-9]{64}$/u,Z0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function eH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function gl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?z(r,i):z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function tH(e,t){let r=In.resolve(e),i=In.resolve(t);if(!B(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...In.relative(r,i).split(In.sep).filter(Boolean)]){o&&(a=In.join(a,o));let s=await lt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await lt.realpath(a);if(n.length>0&&!B(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function ak(e){for(let t of e){let r=await lt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!eH(t,r)||await lt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function rH(e){if(!Q0.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function iH(e){let t=Z0.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function nH(e,t,r){return Ir(K(e,t),rH(r))}async function aH(e,t,r){let i=await tH(r,In.dirname(e)),n=await lt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([lt.realpath(t),lt.realpath(e)]);if(!B(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":th.O_RDONLY|th.O_NOFOLLOW|th.O_NONBLOCK,c=await lt.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),lt.lstat(e),lt.realpath(e)]);if(await ak(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!gl(n,l)||!gl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;p+=b.bytesRead,f.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),lt.lstat(e),lt.realpath(e)]);if(await ak(i),!v.isFile()||v.isSymbolicLink()||g!==o||!B(a,g)||!gl(l,h)||!gl(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ok(e,t,r){let i=iH(r),n=K(e,t),a=nH(e,t,i),o=we(e,a);await V(o,a);let s=tb(await aH(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}Kr();Ee();Ni();var yo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};ln();so();Ei();var $6=64*1024;var O6=3600*1e3;var H6=cH(sH);var lH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function sk(e,t){let r=[];for(let i of lH){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function ck(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ok(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}so();var Xr=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}};function uH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function dH(e){let t=uH(e.bundle.baseline),r=await Of(e.paths,t,{origin:"explicit",now:e.now});return wp({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function uk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await co(e.paths,e.state.name,e.state.implementation_scope),r=await hn({changeDir:Ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await dH({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function dk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await uk(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function fH(e){let t=await ee({root:Ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:hw(t.text)}}function pH(e){let{receipt:t,implementationScope:r}=e,i=[],n=gp({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function hH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Pp(e.implementationScope.scope.declaredArtifacts)}}async function lk(e){let t=await lo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=sk(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new Xr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await ck({paths:e.paths,state:e.state,receipt:t});if(n){let a=pH({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function mH(e){let t=hH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await lk({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Xr)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await lk({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Xr)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new Xr(r)}function rh(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function ih(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:rh(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([uk(e),En(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:rh(e.state.verification_result,"stale"),envelope:null};let i=await fH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await mH({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:rh(e.state.verification_result,"invalid"),envelope:null}}}function gH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function pk(e){try{return await vH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wH(e,t){try{return(await ee({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function yH(e,t,r){let i=Ma(e,r.capability);if(!B(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=fk.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await wH(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await ee({root:Ne(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function NH(e,t){return pk(Bp(e,t))}async function nh(e){let t=e.now??new Date,r=await Vt(e.paths,e.name),i=await ar(e.paths,e.name),n=await ke(e.paths.projectRoot),a=gH(r.name,t),o=fk.resolve(e.paths.nativeRoot,...a.split("/"));if(!B(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(r.spec_changes.map(m=>yH(e.paths,r.name,m))),ih({paths:e.paths,state:r,now:t}),vl(e.paths,r.name),qc(e.paths,r.name),$y(e.paths,r.name),NH(e.paths,r.name),pk(o)]);return Yb({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}U();Kr();so();Ei();async function bH(e,t){let r=K(e,t.name),i=await dn(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await jc(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await vi(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function kH(e,t){let r=await bH(e,t);return{committed:r,latest:xb(r),history:Eb(r)}}async function hk(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await kH(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}Kr();yt();U();function No(e,t){try{return ya(e,t)}catch{return}}var bo=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function EH(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function xH(e){return(await hb(e))?.change??null}function CH(e,t,r=!1,i){return dl({state:e,archiveReady:t,evidenceRetreat:r}).command}async function PH(e,t){let r=Ne(e,t.name),i=[...(await Fc(r,t.brief)).findings,...(await Wy(e,t)).findings,...await vb(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Sc(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await ly(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await hn({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ob(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await Uf(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function ah(e,t,r){let i=await xH(e)===t,n=await qd(e,t),a=await La(e,t),o;try{let y=await zf(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:No(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:No(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:No(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Jp({paths:e,state:o,findings:[y]}),O=dl({state:o,findings:C});return{name:o.name,artifacts:No(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:Gp(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await Gb({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await hk(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await hn({changeDir:Ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Y=await En(e,o.name,o.verification_evidence);for(let Re of Y.acceptanceTrace.entries)C.set(Re.acceptanceId,Re.status==="failed"?"failed":Re.status==="missing"?"missing":"satisfied")}let O=dw({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),j=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...j?{nextPageCommand:EH(j),nextPageArgs:j}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await vl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let y=await ar(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await pn({paths:e,identity:y});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Oc({paths:e,identity:y});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],m=!1;if(o.phase==="verify"){let y=await dk({paths:e,state:o});m=y.freshness!=="fresh",p.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await nh({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await PH(e,o),...s.findings,...d,...f,...p,...l,...v].filter((y,C,O)=>O.findIndex(j=>j.code===y.code&&j.path===y.path)===C),b=Jp({paths:e,state:o,findings:g}),S=b.filter(y=>!fn(y.code)),N=o.phase==="archive"&&h?.ready===!0&&S.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),k=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:No(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||k?null:CH(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:Gp(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:dl({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:hl,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function mk(e){let t;try{t=await Sf({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await SH.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>bo.maxChanges))throw new Error(`Native status exceeds ${bo.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}U();var sh=Gt(It(),1);Et();ce();et();wt();import{promises as RH}from"node:fs";import oh from"node:path";var wl=class extends Error{};async function ch(e,t){let r=await ee({root:e.nativeRoot,ref:oh.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,sh.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new wl("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:Be(i)}}async function gk(e,t,r){let i;try{i=await RH.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=oh.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await ch(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof wl)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function yl(e){return T("comet.native.status-record.v1",e)}function vk(e){let t=oh.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Ue(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=Be((0,sh.parse)(Ue(e.projectRoot,["show",`${r}:${t}`])));return yl(i)===yl(e.state)?r:null}catch{return null}}function wk(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=vk(e),i=vk(t);if(!r||!i)return!1;try{return Ue(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function yk(e,t){return e.state.archived&&t.state.archived&&yl(e.state)===yl(t.state)}import Rk from"node:path";import{promises as Nk}from"node:fs";import _H from"node:path";ce();var AH=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),IH=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),jH=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),TH=new Set(["status","summary"]);function Nl(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function bl(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 $H(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 OH(e,t,r,i){let n=Nl(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=bl(n,AH,"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=Nl(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=bl(o,IH,"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 c=Nl(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=bl(c,TH,"Native Supervisor finalVerification");if(l)return l;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=Nl(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:m,...h}=f,v=bl(h,jH,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(b)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!$H(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let S=g.depends_on.length===0?"ready":"pending";if(f.status!==S)return`Native Supervisor child ${g.name} has progressed beyond its initial ${S} 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 ${g.name} contains execution progress`;if((f.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function bk(e){let t=Xa(e.paths,e.state.name),r;try{let c=await Nk.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Ci(t,"","Native Supervisor overlay is not a regular file");r=await Nk.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Ci(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Ci(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=_H.join(e.paths.changesDir,e.state.name),a;try{a=await Mt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Ci(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.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 Ke(e.paths,e.state.name)}catch(c){return Ci(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Ci(t,r,"Native Supervisor overlay disappeared during inspection");let s=OH(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}}Aa();yi();function He(e,t,r){return e.language==="zh-CN"?r:t}function HH(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:He(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:He(e,"Reply A or B","回复 A 或 B"),agentInstruction:He(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(He(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(He(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:He(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:He(e,"Accept the result","接受结果"),agentInstruction:He(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:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=Gc)??!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(He(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(He(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 DH(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 qH(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:He(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:He(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function xk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Pi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function kk(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function FH(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Sk(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function LH(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function BH(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 Qr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:xk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Pi("summary","--summary"),FH(e.name,e.flag)]}}function Ek(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:He(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function VH(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function kl(e){return[Qr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Qr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function MH(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 ko(e,t,r={}){let i=LH(t)&&e.coordination_mode===void 0,n=HH(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:[Pi("summary","--summary")],commandAlternatives:[Qr({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:[Pi("summary","--summary")],commandAlternatives:[Qr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...kl({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:[Pi("summary","--summary")],commandAlternatives:[Qr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Qr({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:[Pi("summary","--summary")],commandAlternatives:[Qr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...kl({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:[Pi("summary","--summary")],commandAlternatives:kl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:kl({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?xk({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:BH({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?[Sk("coordination-mode","--coordination-mode",mw)]:[]],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:[kk()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Gc)??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:He(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&f===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:f!==null?[f]:[Pi("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",c=!!e.children_contract_hash,l=kk();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${He(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:MH([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Ek(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>VH(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:Ek(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Sk("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...qH(e)],userCommunication:DH(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Qr({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 Ck from"node:path";function Pk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function lh(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:Pk(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:Pk(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>Ck.relative(t.projectRoot,Ck.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}U();function _k(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function Ak(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function Ik(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:JH(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:GH(i,r)}))]:[]]}function jk(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function WH(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=i!==null||r.requestCheckRounds>0;return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:n?"confirmed":"unconfirmed",...n?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function Sl(e,t,r=ve(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:Rk.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function uh(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=lh(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...ko(t),disposition:"blocked",action:"archive",commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the reported Git blocker; do not treat this archived change as complete until it succeeds."},runnerAction:{...ko(t).runnerAction,kind:"none"}}:ko(t),c=e.details?Ik(t,null,[]):[],l=Ak(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?_k(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:ya(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:Rk.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:jk(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function zH(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function El(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function JH(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:El(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function GH(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:El(e.summary,t)??""}}async function Tk(e){let t=await Zf(e),r=lh(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Qa({paths:e.paths,state:t.state}),a=await bk({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ke(e.paths,e.name,{diagnostics:!0}),s=o?{...Sl(e.paths,t.state,e.gitContext),projectRoot:"."}:Sl(e.paths,t.state,e.gitContext),c=ko(t.state,n,{verifierExecutionRef:eN(t.state,t.local),...t.local?{verificationCheckPlans:pb(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?zH(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,S=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:El(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let k=El(w,u);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:S,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":S>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let m=o?.stateVersion??0,h=Ik(t.state,o,u),v=Ak(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?_k(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:ya(e.paths,t.state.name),phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:jk(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=WH(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}le();Gs();Et();import{accessSync as _4,constants as A4,promises as dh}from"node:fs";import Ok from"node:path";Xc();Gs();var $k="comet.native.workspace-finish.v1",Hk="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Dk=new RegExp(`^${Hk}$`,"u"),UH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function KH(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==$k||typeof t.name!="string"||!Dk.test(t.name)||typeof t.transactionId!="string"||!UH.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Ok.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:$k,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function YH(e,t){if(!Dk.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Ok.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function fh(e,t,r={}){let i=YH(e,t);try{let n=await dh.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=KH(JSON.parse(await dh.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 qk(e,t={}){let r;try{r=await dh.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${Hk})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await fh(e,a[1],t);o&&i.push(o)}return i}function xl(e,t){let r=Ri.normalize(ph(e)),i=Ri.normalize(ph(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ph(e){let t=Ri.resolve(e);try{return XH.native(t)}catch{return t}}async function Fk(e,t){let r=[];for(let i of await mk(e))t!==void 0&&i!==t||r.push({name:i,kind:await Ga(e,i)?"portable":"legacy"});return r}async function QH(e,t){let r=Ri.resolve(e),i=Co(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>xl(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>Ri.resolve(l)).sort()){let l=xl(c,r)?r:c,u=ph(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let f=await ke(l);if(!f)continue;let p=await Ot(l,f.native.artifact_root);o.push({projectRoot:l,config:f,paths:p,gitContext:Al(l,i)??ve(l),changes:await Fk(p,t)})}if(o.length===0){let c=await ke(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Ot(e,c.native.artifact_root);o.push({projectRoot:Ri.resolve(e),config:c,paths:l,gitContext:Al(e,i)??ve(e),changes:await Fk(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await gk(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await fh(c.paths,t,{onError:l})].filter(u=>u!==null):await qk(c.paths,{onError:l})}return o}function Lk(e,t){return e.workspace.bindingState==="aligned"?0:xl(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function ZH(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:f})=>{let p=d.finishJournalErrors?.find(({name:m})=>m===n);if(f==="portable")try{let m=await ot(d.paths,n);return{source:d,name:n,kind:f,workspace:Sl(d.paths,m,d.gitContext),portableStatus:null,inspectionError:p?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:f,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:f,workspace:a.length>1?await La(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:p?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:f})=>f.name===n).map(f=>{let p=uh({paths:d.paths,...f,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:p.workspace,portableStatus:p,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:f,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(p=>p.finishJournals?.some(({name:m})=>m===n)),f=d?.finishJournals?.find(({name:p})=>p===n);if(d&&f){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:f.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:f.result?.message??"Native workspace finish record is orphaned."},finishJournal:f});continue}}if(s.length>0){for(let f of o)if(f.kind==="portable")try{f.record=await ch(f.source.paths,Ri.join(f.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(f=>[...o,...s.filter(p=>!yk(f.record,p.record))].every(p=>p.record&&wk(f.record,p.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,f)=>Lk(d,e)-Lk(f,e)||d.source.projectRoot.localeCompare(f.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>bo.maxChanges)throw new Error(`Native status discovery exceeds ${bo.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function eD(e,t,r){let i=await La(e.source.paths,e.name),n=null;try{n=await Hy(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:ah(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function Bk(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return uh({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await Tk({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return Bk({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return eD(e,t,r)}async function Vk(e){let{sources:t,candidates:r}=await tD(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>xl(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),ah(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),Bk(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function tD(e,t){let r=await QH(e,t),i=(await ZH(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}va();import So from"path";import{realpathSync as yD}from"fs";function Mk(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),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var fr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Wk(e){return e?e.command?`${fr.next} ${e.command}`:e.ask_user?`${fr.next} ${e.ask_user}`:null:null}function zk(e,t){let r=[e.summary],i=Wk(e.next);return i&&r.push(i),e.user_message&&r.push("",fr.relay,e.user_message),t!==void 0&&r.push("",fr.details,JSON.stringify(t,null,2)),`${r.join(`
191
+ ${e.sessionId}`)}:{}},f=e.binding?{schema:"comet.native.workspace.v3",...p,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...p};return yl(f),f}async function mr(e,t){let r=await A$(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(yl(r),r)}async function Nl(e){yl(e.identity);let t=await I$({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Bf==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function In(e){if(yl(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Nl(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=we(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function ZN(e,t){let r=await mr(e,t);if(r===null)return null;let i=await In({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}Qa();qc();qc();var bl=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"},vo=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"},kl=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},A2=fc("en");function ke(e,t){Ei(t);let r=Kr.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Sl(e,t){let r=Y(e,t),i=Kr.join(r,"schema-migration.json");await V(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await tb.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function rb(e,t){let r=Y(e,t),i=Kr.join(r,"checkpoint-journal.json");await V(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await tb.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ib(e,t=Kr.dirname(e)){let r=Kr.relative(t,e).split(Kr.sep).join("/"),i=await re({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Lf.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 qf(e,t){let r=Kr.join(ke(e,t),zt);await V(e.nativeRoot,r);let i=Lc(await ib(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Sl(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await $$(e,i.state),i)}async function nb(e,t){let r=Kr.join(ke(e,t),zt);await V(e.nativeRoot,r);let i=Lc(await ib(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function $$(e,t){if(await cl(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Yt(e,t){let r=await qf(e,t);if(r.status==="migration-required")throw new mn(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new dr(r.schema,r.minimumRuntimeVersion);return await ZN(e,t),r.state}Qe();import{promises as mF}from"fs";Ni();import{promises as Mf}from"fs";import ob from"path";at();Ut();K();var Vf=["outcome","scope","nonGoals","acceptanceExamples"],ab=[...Vf,"constraints","decisions","openQuestions","verificationExpectations"],O$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],H$=new Set(["nonGoals","decisions","openQuestions"]),go=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},sb={maxFileBytes:sp};function cb(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
192
+ `).trim())};for(let o of e.split(/\r?\n/u)){let c=yo(o,n)===null&&n.marker===null?/^# ([^#].*)$/u.exec(o):null;c?(a(),r=c[1].trim(),i=[]):r!==null&&i.push(o)}return a(),t}async function D$(e,t){let r=ob.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Mf.realpath(e),n=await Mf.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Mf.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function wo(e){return{valid:e.length===0,findings:e}}function lb(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 Wf(e){return lb(e).trim()}function El(e){let t=Wf(e).split(/\r?\n/u),r=[],i={marker:null,length:0};for(let n of t)yo(n,i)===null&&(i.marker===null&&/^\s*#{1,6}\s*$/u.test(n)||i.marker===null&&/^\s*#{1,6}\s+/u.test(n)||i.marker===null&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n));return r.join(`
193
+ `).trim()}function B$(e){let t=El(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 ub(e){let t=El(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 db(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let i of e.split(/\r?\n/u)){if(yo(i,r)!==null||r.marker!==null)continue;let n=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(n)||n.includes("|")&&n.split("|").some(o=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(o)))return!0;let a=n.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(a){let o=a[1]?.toLocaleLowerCase("en-US")??"";if(t.has(o)||/[./_-]/u.test(o))return!0}}return!1}function yo(e,t){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(e);if(r===null)return null;let i=r[1]??"",n=i[0];return t.marker===null?(t.marker=n,t.length=i.length,"opened"):n===t.marker&&i.length>=t.length&&e.trim()===i?(t.marker=null,t.length=0,"closed"):null}function F$(e){let t=Wf(e).split(/\r?\n/u),r={marker:null,length:0},i=-1;for(let n=0;n<t.length;n+=1){let a=t[n]??"";if(yo(a,r)!==null||r.marker!==null)continue;let o=/^##\s+(.+)$/u.exec(a);if(o!==null){if(i===-1){jw(o[1]??"")&&(i=n+1);continue}return t.slice(i,n).join(`
194
+ `)}}return i===-1?null:t.slice(i).join(`
195
+ `)}function L$(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
196
+ `).trim())};for(let o of Wf(e).split(/\r?\n/u)){if(yo(o,n)!==null){r!==null&&i.push(o);continue}let s=n.marker===null?/^###\s+(.+)$/u.exec(o):null;s!==null?(a(),r=$w(s[1]??""),i=[]):r!==null&&i.push(o)}return a(),t}function q$(e,t){let r=[],i=F$(e);if(i===null)return r.push({code:"brief-structure-missing",message:'Brief scope must include a "## Directory structure"/「## 目录结构」 section with the subsections Created/新建, Modified/修改, Deleted/删除, and Not created/明确不建',path:t}),r;let n=L$(i),a=[];for(let o of gp){let s=n.get(o);(s===void 0||El(s).length===0||ub(s))&&a.push(Tw(o))}return a.length>0&&r.push({code:"brief-structure-subsection-missing",message:`Brief directory structure subsections are missing or empty: ${a.join(", ")}. Keep every heading and write "None"/「无」 when there is no content`,path:t}),r}async function xl(e,t,r={}){let i=[],n;try{n=(await re({root:e,ref:t,maxBytes:sb.maxFileBytes})).text}catch(s){return wo([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of cb(n))a.set(pc(s)??s,c);for(let s of r.compact?Vf:ab)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?ab.filter(s=>!r.compact||a.has(s)):Vf;for(let s of o){let c=a.get(s)??"";El(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):ub(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!H$.has(s)&&B$(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return r.strict&&r.structure&&i.push(...q$(a.get("scope")??"",t)),db(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),wo(i)}async function zf(e,t){let r=[],i;try{i=(await re({root:e,ref:t,maxBytes:sb.maxFileBytes})).text}catch(a){return wo([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of cb(i))n.set(Iw(a)??a,o);for(let a of O$)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return wo(r)}function No(e,t){return ob.join(e.specsDir,t,"spec.md")}async function pb(e,t){let r=[],i=ke(e,t.name);for(let n of t.spec_changes){let a=No(e,n.capability),o=null;try{await V(e.nativeRoot,a),o=await Sf(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await D$(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return wo(r)}ro();de();at();ro();de();import fb from"node:path";var M$="comet.native.contract.v1",V$="comet.native.acceptance-set.v1",hb=/^[a-f0-9]{64}$/u,bo={maxAcceptanceCriteria:to.maxCriteria};function mb(e,t){let r=fb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||fb.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function vb(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
197
+ `))}function W$(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(hb))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(hb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=mb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:vb(e.markdown)},markdown:e.markdown}}function z$(e,t){return gb(e.id,t.id)}function gb(e,t){return e<t?-1:e>t?1:0}function wb(e){let t=mb(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(W$).sort((d,p)=>gb(d.snapshot.capability,p.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=tf(e.briefMarkdown,t,bo.maxAcceptanceCriteria);for(let{snapshot:d,markdown:p}of r)p===null||d.source===null||(a.push(...rf(p,d.source,bo.maxAcceptanceCriteria-a.length)),a.push(...jy(p,d.source,bo.maxAcceptanceCriteria-a.length)));if(a.sort(z$),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>bo.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${bo.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:vb(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(V$,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(M$,u)}}var G$={maxSpecs:64};async function Tn(e){if(e.specChanges.length>G$.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:null}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:wb({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Qe();Re();import{promises as n0}from"node:fs";import Xf from"node:path";pt();import{promises as X$}from"node:fs";oe();no();import yb from"node:path";function ko(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function So(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 Le(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 jn(e,t){return e===null?null:Le(e,t)}function $n(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 Q$(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 Z$(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function On(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Jf(e,t){if(e===null)return null;let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function e0(e,t){let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Uf(e,t){let r=Le(e,t);if(!yb.isAbsolute(r))throw new Error(`${t} must be absolute`);return yb.resolve(r)}function t0(e,t){let r=`Native local checks[${t}]`,i=ko(e,r);if(So(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)=>Le(u,`${r}.argv[${d}]`,!0)),a=On(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Jf(i.startedAt,`${r}.startedAt`),s=Jf(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=$n(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=ko(i.activeProcess,`${r}.activeProcess`),d=On(u.status,["starting","running"],`${r}.activeProcess.status`);if(So(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:$n(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:Le(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:Le(i.id,`${r}.id`),name:Le(i.name,`${r}.name`),operationId:Le(i.operationId,`${r}.operationId`),status:a,repeatable:Z$(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:$n(i.executionCount,`${r}.executionCount`),argv:n,cwd:Uf(i.cwd,`${r}.cwd`),exitCode:Q$(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Le(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:On(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:Le(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function r0(e){let t="Native local execution state",r=ko(e,t);if(So(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==zc)throw new Error(`Native local execution schema must be ${zc}`);let i=ko(r.workspace,"Native local workspace");So(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ko(r.execution,"Native local execution");So(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Jf(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Le(o.operationId,"Native local execution.operationId"),stage:On(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:On(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:jn(o.executionId,"Native local execution.executionId"),status:On(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:$n(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:e0(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:$n(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:Le(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(t0);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:zc,change:Le(r.change,"Native local change"),basedOnStateVersion:$n(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:jn(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:jn(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:jn(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:jn(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Uf(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Uf(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:jn(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:Le(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}async function Cl(e){let t;try{t=await X$.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 r0(r)}function Kf(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}function Yf(e,t){if(Kf(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}xt();K();var Nb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bb="comet-state.yaml",kb="state.json";function Ii(e,t){if(!Nb.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Xf.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function Rl(e,t){return Xf.join(Ii(e,t),bb)}function Yr(e,t){return Xf.join(Et(e,t),kb)}async function Eo(e,t){try{let r=await n0.readFile(Rl(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function ft(e,t){return Vr(Rl(e,t))}async function Qf(e){let t=await ft(e.paths,e.name),r=Yr(e.paths,e.name);try{let i=await Cl(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}function rh(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var $i=rh();function Ab(e){$i=e}var Ti={exec:()=>null};function Hn(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 M(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(_e.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var a0=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),_e={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:Hn(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Hn(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Hn(e=>new RegExp(`^ {0,${e}}>`))},o0=/^(?:[ \t]*(?:\n|$))+/,s0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,c0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ro=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,l0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ih=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ib=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Tb=M(Ib).replace(/bull/g,ih).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(),u0=M(Ib).replace(/bull/g,ih).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(),nh=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,d0=/^[^\n]+/,ah=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,p0=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ah).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),f0=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ih).getRegex(),Tl="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",oh=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,h0=M("^ {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",oh).replace("tag",Tl).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),jb=e=>M(nh).replace("hr",Ro).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",Tl).getRegex(),m0=jb(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),v0=jb(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),g0=M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",v0).getRegex(),sh={blockquote:g0,code:s0,def:p0,fences:c0,heading:l0,hr:Ro,html:h0,lheading:Tb,list:f0,newline:o0,paragraph:m0,table:Ti,text:d0},Sb=M("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ro).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",Tl).getRegex(),w0={...sh,lheading:u0,table:Sb,paragraph:M(nh).replace("hr",Ro).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Sb).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",Tl).getRegex()},y0={...sh,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",oh).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:Ti,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(nh).replace("hr",Ro).replace("heading",` *#{1,6} *[^
198
+ ]`).replace("lheading",Tb).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},N0=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,b0=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,$b=/^( {2,}|\\)\n(?!\s*$)/,k0=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,vr=/[\p{P}\p{S}]/u,Dn=/[\s\p{P}\p{S}]/u,Po=/[^\s\p{P}\p{S}]/u,S0=M(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Dn).getRegex(),E0=/[\p{Pi}\p{Ps}"']/u,Ob=/(?!~)[\p{P}\p{S}]/u,x0=/(?!~)[\s\p{P}\p{S}]/u,C0=/(?:[^\s\p{P}\p{S}]|~)/u,R0=M(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",a0?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Hb=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,P0=M(Hb,"u").replace(/punct/g,vr).getRegex(),_0=M(Hb,"u").replace(/punct/g,Ob).getRegex(),A0=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,I0=M(A0,"u").replace(/openQuote/g,E0).replace(/punct/g,vr).getRegex(),Db="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",T0=M(Db,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),j0=M(Db,"gu").replace(/notPunctSpace/g,C0).replace(/punctSpace/g,x0).replace(/punct/g,Ob).getRegex(),$0="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",O0=M($0,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),H0=M("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),D0="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",B0=M(D0,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),F0=M(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,vr).getRegex(),L0="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",q0=M(L0,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Dn).replace(/punct/g,vr).getRegex(),M0=M(/\\(punct)/,"gu").replace(/punct/g,vr).getRegex(),V0=M(/^<(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(),W0=M(oh).replace("(?:-->|$)","-->").getRegex(),z0=M("^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",W0).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_l=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,G0=M(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",_l).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Bb=M(/^!?\[(label)\]\[(ref)\]/).replace("label",_l).replace("ref",ah).getRegex(),Fb=M(/^!?\[(ref)\](?:\[\])?/).replace("ref",ah).getRegex(),J0=M("reflink|nolink(?!\\()","g").replace("reflink",Bb).replace("nolink",Fb).getRegex(),Eb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ch={_backpedal:Ti,anyPunctuation:M0,autolink:V0,blockSkip:R0,br:$b,code:b0,del:Ti,delLDelim:Ti,delRDelim:Ti,emStrongLDelim:P0,emStrongRDelimAst:T0,emStrongRDelimUnd:H0,escape:N0,link:G0,nolink:Fb,punctuation:S0,reflink:Bb,reflinkSearch:J0,tag:z0,text:k0,url:Ti},U0={...ch,emStrongLDelim:I0,emStrongRDelimAst:O0,emStrongRDelimUnd:B0,link:M(/^!?\[(label)\]\((.*?)\)/).replace("label",_l).getRegex(),reflink:M(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_l).getRegex()},Zf={...ch,emStrongRDelimAst:j0,emStrongLDelim:_0,delLDelim:F0,delRDelim:q0,url:M(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Eb).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:M(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Eb).getRegex()},K0={...Zf,br:M($b).replace("{2,}","*").getRegex(),text:M(Zf.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Pl={normal:sh,gfm:w0,pedantic:y0},xo={normal:ch,gfm:Zf,breaks:K0,pedantic:U0},Y0={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},xb=e=>Y0[e];function Xt(e,t){if(t){if(_e.escapeTest.test(e))return e.replace(_e.escapeReplace,xb)}else if(_e.escapeTestNoEncode.test(e))return e.replace(_e.escapeReplaceNoEncode,xb);return e}function Cb(e){try{e=encodeURI(e).replace(_e.percentDecode,"%")}catch{return null}return e}function Rb(e,t){let r=e.replace(_e.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(_e.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(_e.slashPipe,"|");return i}function Xr(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 Pb(e){let t=e.split(`
199
+ `),r=t.length-1;for(;r>=0&&_e.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
200
+ `)}function X0(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 Q0(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 _b(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),p=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(p){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function Z0(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
201
+ `).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(`
202
+ `)}var Al=class{options;rules;lexer;constructor(e){this.options=e||$i}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]:Pb(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=Z0(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=Xr(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:Xr(t[0],`
203
+ `),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:Xr(t[0],`
204
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Xr(t[0],`
205
+ `).split(`
206
+ `),i="",n="",a=[];for(;r.length>0;){let o=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),o=!0;else if(!o)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
207
+ `),u=l.replace(this.rules.other.blockquoteSetextReplace,`
208
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
209
+ ${l}`:l,n=n?`${n}
210
+ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=d,r.length===0)break;let p=a.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let f=p,m=r.join(`
211
+ `),h=f.raw+`
212
+ `+m.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(h);a[a.length-1]=v,i=`${i}
213
+ ${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="list"){let f=p,m=f.raw+`
214
+ `+r.join(`
215
+ `),h=this.list(m);a[a.length-1]=h,i=i.substring(0,i.length-p.raw.length)+h.raw,n=n.substring(0,n.length-f.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
216
+ `);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 c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=Q0(t[2].split(`
217
+ `,1)[0],t[1].length),p=e.split(`
218
+ `,1)[0],f=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):f?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=t[1].length),f&&this.rules.other.blankLine.test(p)&&(l+=p+`
219
+ `,e=e.substring(p.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),v=this.rules.other.hrRegex(m),g=this.rules.other.fencesBeginRegex(m),b=this.rules.other.headingBeginRegex(m),k=this.rules.other.htmlBeginRegex(m),N=this.rules.other.blockquoteBeginRegex(m);for(;e;){let x=e.split(`
220
+ `,1)[0],w;if(p=x,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),w=p):w=p.replace(this.rules.other.tabCharGlobal," "),g.test(p)||b.test(p)||k.test(p)||N.test(p)||h.test(p)||v.test(p))break;if(w.search(this.rules.other.nonSpaceChar)>=m||!p.trim())u+=`
221
+ `+w.slice(m);else{if(f||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(d)||b.test(d)||v.test(d))break;u+=`
222
+ `+p}f=!p.trim(),l+=x+`
223
+ `,e=e.substring(x.length+1),d=w.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=Pb(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:Xr(t[0],`
224
+ `),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=Rb(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
225
+ `):[],a={type:"table",raw:Xr(t[0],`
226
+ `),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(Rb(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Xr(t[0],`
227
+ `),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)===`
228
+ `?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=Xr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=X0(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)),_b(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 _b(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,c=0,l=i[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+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)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let p=[...i[0]][0].length,f=e.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(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,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(i=c.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 l=[...i[0]][0].length,u=e.slice(0,n+i.index+l+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(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}}}},ht=class eh{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||$i,this.options.tokenizer=this.options.tokenizer||new Al,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:_e,block:Pl.normal,inline:xo.normal};this.options.pedantic?(r.block=Pl.pedantic,r.inline=xo.pedantic):this.options.gfm&&(r.block=Pl.gfm,this.options.breaks?r.inline=xo.breaks:r.inline=xo.gfm),this.tokenizer.rules=r}static get rules(){return{block:Pl,inline:xo}}static lex(t,r){return new eh(r).lex(t)}static lexInline(t,r){return new eh(r).inlineTokens(t)}lex(t){t=t.replace(_e.carriageReturn,`
229
+ `),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(_e.tabCharGlobal," ").replace(_e.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+=`
230
+ `: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(`
231
+ `)?"":`
232
+ `)+a.raw,s.text+=`
233
+ `+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(`
234
+ `)?"":`
235
+ `)+a.raw,s.text+=`
236
+ `+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),r.push(a);continue}let o=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(o=t.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
237
+ `)?"":`
238
+ `)+a.raw,s.text+=`
239
+ `+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(`
240
+ `)?"":`
241
+ `)+a.raw,s.text+=`
242
+ `+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,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;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(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,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 c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},Il=class{options;parser;constructor(e){this.options=e||$i}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(_e.notSpaceStart)?.[0],n=e.replace(_e.endingNewline,"")+`
243
+ `;return i?'<pre><code class="language-'+Xt(i)+'">'+(r?n:Xt(n,!0))+`</code></pre>
244
+ `:"<pre><code>"+(r?n:Xt(n,!0))+`</code></pre>
245
+ `}blockquote({tokens:e}){return`<blockquote>
246
+ ${this.parser.parse(e)}</blockquote>
247
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
248
+ `}hr(e){return`<hr>
249
+ `}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+`>
250
+ `+i+"</"+n+`>
251
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
252
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
253
+ `}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>
254
+ <thead>
255
+ `+t+`</thead>
256
+ `+i+`</table>
257
+ `}tablerow({text:e}){return`<tr>
258
+ ${e}</tr>
259
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
260
+ `}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>${Xt(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=Cb(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+Xt(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=Cb(e);if(n===null)return Xt(r);e=n;let a=`<img src="${e}" alt="${Xt(r)}"`;return t&&(a+=` title="${Xt(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Xt(e.text)}},lh=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}},It=class th{options;renderer;textRenderer;constructor(t){this.options=t||$i,this.options.renderer=this.options.renderer||new Il,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new lh}static parse(t,r){return new th(r).parse(t)}static parseInline(t,r){return new th(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}},Co=class{options;block;constructor(e){this.options=e||$i}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?ht.lex:ht.lexInline}provideParser(e=this.block){return e?It.parse:It.parseInline}},eO=class{defaults=rh();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=It;Renderer=Il;TextRenderer=lh;Lexer=ht;Tokenizer=Al;Hooks=Co;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 Il(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new Al(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new Co;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=n[o];Co.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&Co.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,l);return c.call(n,d)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,l);return d===!1&&(d=await c.apply(n,l)),d})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ht.lex(e,t??this.defaults)}parser(e,t){return It.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?ht.lex:ht.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(e):e?It.parse:It.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?ht.lex:ht.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?It.parse:It.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+=`
261
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+Xt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},ji=new eO;function X(e,t){return ji.parse(e,t)}X.options=X.setOptions=function(e){return ji.setOptions(e),X.defaults=ji.defaults,Ab(X.defaults),X};X.getDefaults=rh;X.defaults=$i;function tO(...e){return ji.use(...e),X.defaults=ji.defaults,Ab(X.defaults),X}X.use=tO;X.walkTokens=function(e,t){return ji.walkTokens(e,t)};X.parseInline=ji.parseInline;X.Parser=It;X.parser=It.parse;X.Renderer=Il;X.TextRenderer=lh;X.Lexer=ht;X.lexer=ht.lex;X.Tokenizer=Al;X.Hooks=Co;X.parse=X;var dG=X.options,pG=X.setOptions,fG=X.walkTokens,hG=X.parseInline;var mG=It.parse,vG=ht.lex;oe();at();de();var ik=ir(Bt(),1);import{promises as DO}from"node:fs";import Tt from"node:path";pt();at();de();Qe();K();xt();Ol();Ol();Hi();ti();pt();jc();oe();de();Ll();Re();K();Qb();Hi();ti();ql();pt();Qe();ql();Ka();K();var Ml=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function vh(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`}import $O from"node:path";pt();Qe();Re();Hi();ti();async function Vl(e){let t=vh(e.parent),r=nr(e.paths.projectRoot,t);if(!r)return null;let i=nr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Cr(e.paths.projectRoot).map(o=>$O.resolve(o)).find(o=>we(o).currentBranch===t);if(!n)return null;let a=Bl({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 ph(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function gh(e,t){let r=Tt.normalize(Tt.resolve(e)),i=Tt.normalize(Tt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function BO(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 FO(e){let t=BO(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 wh(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return FO(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function yh(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 LO(e){let t=Cr(e.projectRoot);t.some(i=>gh(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Tt.resolve(n)))]){let n=await xe(i);n&&r.push({projectRoot:i,paths:await Vt(i,n.native.artifact_root),parent:gh(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function qO(e,t){let r=Tt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Vr(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function MO(e,t){let r;try{r=await DO.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=Tt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Vr(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function VO(e,t,r){let i=Tt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Tt.sep}`))return null;let n=i.split(Tt.sep).join("/");try{let a=(0,ik.parseDocument)(Je(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ze(a.toJS({mapAsMap:!1}))}catch{return null}}function WO(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 rk(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function jo(e){let t=Tt.join(e.paths.changesDir,e.state.name),r=await wh(t),i=null,n;try{n=await Qt({changeDir:t,validation:Zr(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 et(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Fl(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(k=>({...k,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=yh({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===Qr){let g=await et(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let x=await Vl({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});x&&(g=x,await ei(e.paths,x))}}if(g){let N=Fl(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(x=>({...x,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let b=new Map(n.contract.children.map(N=>[N.name,N])),k=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(x=>n.contract.children.filter(({name:w})=>w!==N.name).every(({name:w})=>w!==x))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of k){if(N.status!=="ready")continue;b.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:k,readyChildren:k.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await LO(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let k of await MO(g,l)){let N={...k,source:g,committedState:VO(g,k.file,b)};u.set(k.state.name,[...u.get(k.state.name)??[],N])}for(let k of l){let N=await qO(g,k);N&&d.set(k,[...d.get(k)??[],{source:g,state:N}])}}let p=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:x,committedState:w})=>x.parent&&w?.name===g.name&&rk(w,o));if(b){p.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let k=u.get(g.name)?.[0];if(k){p.set(g.name,{kind:"blocked",phase:k.state.phase,projectRoot:k.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?p.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&p.set(g.name,WO(N[0].state,N[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,h=g=>{let b=m.get(g);if(b)return b;let k=f.get(g),x=k.depends_on.map(h).every(({status:O})=>O==="done"),w=p.get(g),S=w?.kind==="active"&&x?k.depends_on.filter(O=>!(u.get(O)??[]).some(({source:T,committedState:Q})=>gh(T.projectRoot,w.projectRoot)&&Q?.name===O&&rk(Q,o))):[],E,y=w?.message??null;w?.kind==="done"?(E=x?"done":"blocked",x||(y=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(E=x&&S.length===0?"active":"blocked",x?S.length>0&&(y=`Native child ${g} does not include merged dependencies: ${S.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?E="blocked":(E=s&&x?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:k.summary,dependsOn:[...k.depends_on],covers:[...k.covers],status:E,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:y};return m.set(g,C),C},v=n.contract.children.map(({name:g})=>h(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")}}Wc();xt();Pi();_o();Hl();Re();nf();Jp();xt();Pi();oe();Ni();_o();K();Ni();si();Qe();var zk=ir(Bt(),1);cr();var xK=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 IK=256*1024;xt();Pi();ti();var uD=fc("en",{compact:!0});Qe();Re();Hi();ti();xt();Pi();pt();jc();de();import zn from"node:path";pt();cr();oe();var G6=8*1024*1024;Ll();Re();Pi();K();function fD(e,t){let r=zn.relative(zn.resolve(e),zn.resolve(t));if(zn.isAbsolute(r)||r===".."||r.startsWith(`..${zn.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(zn.sep).join("/");return Xb(e,i),i}function Kk(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:fD(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}var mY=1024*1024*1024;Re();Hl();_o();ti();Re();ti();Re();gf();var o4=16*1024;async function Yk(e){let t=await Tf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Ei(t.selection.change),t.selection)}async function Xk(e,t){return Ce(e,`select change ${t}`,async()=>{Ei(t),await Eo(e,t)?await ft(e,t):await Yt(e,t),await jf(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}K();async function Qk(e,t){let r=[],i=Y(e,t.name),n=Mr(i,dt.stateRef),a;try{a=await _n(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Mr(i,a.trajectoryRef),s=await WN(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await Ai(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Mr(i,a.checkpointRef);try{let u=await gl(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Rn();import $D from"path";import{isDeepStrictEqual as Gh}from"util";oe();Ut();Ka();Re();K();Ct();Di();de();de();var Gn={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var hD=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function mD(e,t){return e<t?-1:e>t?1:0}function vD(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!hD.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(mD)}function Fh(e=[]){return vD(e,"Native repair failed check IDs",Gn.maxFailedCheckIds,!0)}function Zk(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function gD(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Zk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Zk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Lh(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(gD(i,a))break;r+=1,i=a}return r}Ul();qi();function qh(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var eS="repairStagnation",rt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},yD=/^[a-f0-9]{64}$/u;var ND=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),bD=["data","runId","sequence","timestamp","type"],tS=["disposition","overrideSummaryHash","signatureHash"],kD=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],rS=12;function Vh(e,t){return e<t?-1:e>t?1:0}function iS(e,t,r){let i=Object.keys(e).sort(Vh);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function Ql(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Ko(e,t){if(typeof e!="string"||!yD.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function SD(e){if(!Array.isArray(e)||e.length>Gn.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Vh)}function nS(e){if(typeof e!="string"||e.length===0||e.length>rt.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Mh(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>rt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>rt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>rt.maxTextCharacters&&(!n||e.length>rt.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>rt.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Mh(s,t+1,r,`${i}[${c}]`));return}let a=Ql(e,i),o=Object.keys(a);if(o.length>rt.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>rt.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>rt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Mh(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function ED(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function xD(e,t,r){let i=Ql(e,`Native repair trajectory event ${t+1}`);if(iS(i,bD,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(ED(i.timestamp),typeof i.type!="string"||!ND.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(nS(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Mh(i.data,0,n,"Native trajectory event data"),Ql(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Wh(e){let t=Ql(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Vh),i=r.length===tS.length&&r.every((l,u)=>l===tS[u]);i||iS(t,kD,"Native repair trajectory projection");let n=Ko(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Ko(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Ko(t.contractHash,"Native repair trajectory contract hash"),s=SD(t.failedAcceptanceIds),c=Fh(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function CD(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function RD(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??rS;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Lh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<Gn.warningAtConsecutiveFailures?"continue":a<Gn.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function PD(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??rS;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function aS(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>rt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=nS(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=xD(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>rt.maxTotalDataNodes||c>rt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let p=d.data,f=Object.hasOwn(p,"repairScopeHash")?Ko(p.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(p,"implementationScopeHash")?Ko(p.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(p,eS)){if(i?.contractHash===null&&d.type==="state_transitioned"&&p.previousPhase==="build"&&p.nextPhase==="verify"&&(f!==null&&n!==null&&f!==n||f===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=f,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=Wh(p[eS]);if(CD(p,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&f!==null&&n!==null&&f!==n&&(r.length=0,o=0),f!==null&&(n=f),RD(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&f!==null&&n!==null&&f!==n)throw new Error("Native repair override cannot cross implementation scope progress");PD(m,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>Gn.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function oS(e){return aS(e).history}function sS(e){let t=aS(e).latestProjection;return t?{...t}:null}Ut();var Jn={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:[]},zh=ee("comet-native-runtime:v3:scope-reopen"),_D=[{skillVersion:"3",skillHash:ee("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ee("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ee("comet-native-runtime:v1")}];function cS(e){return e.skillVersion===Jn.definition.metadata.version&&e.skillHash===zh||_D.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Ut();Ut();function lS(e){return ee(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}Qa();var hS=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],OD=new Set(hS),mS=new Set([...hS,"minimum_runtime_version","revision"]),HD=new Set([...mS,"operation"]),Jh=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),DD=new Set([...Jh,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Uh=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Yh(e,t){return $D.join(Y(e,t),"transition.json")}function eu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Xh(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function Zl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Kh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!DD.has(u)),a=[...Jh].find(u=>!Object.hasOwn(r,u)),o=Jh.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(qh(r.summary,"Native transition journal event summary"),mt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(r.noCodeReason!==null&&(qh(r.noCodeReason,"Native transition journal event no-code reason"),mt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Wh(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function BD(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Kh({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Kh(e,t)}function Qh(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?BD(e.eventData,e.evidenceHash):Kh(e.eventData,e.evidenceHash),n=Of(e.nextRun),a=e.previousRun===null?null:Of(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function uS(e,t,r=!1){if(e.skill!==Jn.definition.metadata.name||(r?!cS(e):e.skillVersion!==Jn.definition.metadata.version||e.skillHash!==zh)||e.orchestration!==Jn.definition.orchestration.mode||e.pendingRef!==dt.pendingRef||e.trajectoryRef!==dt.trajectoryRef||e.contextRef!==dt.contextRef||e.artifactsRef!==dt.artifactsRef||e.checkpointRef!==dt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function dS(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function pS(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Zh(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(uS(o,"next Run",i||a!==null),pS(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(uS(a,"previous Run",!0),pS(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Gh(dS(a),dS(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function FD(e,t,r){return ee(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function vS(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function fS(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function em(e,t,r,i,n=!1){let a=r.eventData,o=fS(e),s=fS(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Gh(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Gh(e.spec_changes,t.spec_changes),l=lS({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(i==="spec-rebase"){let c=FD(e.name,a.summary,t.spec_changes),l=ee(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function LD(e,t){let r=eu(e);if(Xh(r,HD),r.schema!==fn)throw new Error(`Expected Native transition schema ${fn}`);let i=Zl(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${fn} minimum_runtime_version must be ${3}`);let n=Zl(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Qh(r,t),o=Gt(r.previousState),s=Gt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(em(o,s,a,r.operation),Zh(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:fn,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function qD(e,t){let r=eu(e);if(Xh(r,OD),r.schema!==Xa)throw new Error(`Expected Native transition schema ${Xa}`);let i=Qh(r,t,!0),n=xi(r.previousState),a=xi(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return em(n,a,i,vS(n,a,i.eventData),!0),Zh(n,a,i,!0),{schema:Xa,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function MD(e,t){let r=eu(e);if(Xh(r,mS),r.schema!==hn)throw new Error(`Expected Native transition schema ${hn}`);if(Zl(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${hn} minimum_runtime_version must be 2`);let n=Zl(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Qh(r,t,!0),o=Ci(r.previousState),s=Ci(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(em(o,s,a,vS(o,s,a.eventData),!0),Zh(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:hn,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function VD(e,t){let r=eu(e);if(r.schema===fn)return{status:"current",journal:LD(r,t)};if(r.schema===Xa)return{status:"migration-required",journal:qD(r,t)};if(r.schema===hn)return{status:"migration-required",journal:MD(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function WD(e,t){let r=Yh(e,t),i=Ne(e,r);await V(i,r);try{let n=await Gr({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return VD(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function gS(e,t){let r=await WD(e,t);if(!r)return null;if(r.status==="migration-required")throw new Uh(t);return r.journal}var zD=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function GD(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function JD(e){return e?e.map(GD).join(" "):null}function UD(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function vt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function KD(e){return e.map(t=>vt(t,[],null))}function YD(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[vt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(vt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),vt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(vt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(vt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),vt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ie(e,t){let r=t.commandArgs===void 0?UD(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?JD(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??KD(t.requiredInputs??[])}}function tu(e){let r=(e.findings??[]).filter(d=>!An(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||zD.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Ie(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[vt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Ie(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ie(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]});if(n)return Ie(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[vt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Ie(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ie(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ie(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[vt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ie(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ie(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=YD(e.state);return Ie(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Yo from"path";K();var wS=8,XD={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function QD(e){let t=XD[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:An(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function ZD(e,t,r){if(!r.path)return null;let i;if(Yo.isAbsolute(r.path)?i=Yo.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Yo.resolve(ke(e,t.name),...r.path.split(/[\\/]/u)):i=Yo.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Yo.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function eB(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function tm(e){return e.findings.map(t=>{let r=QD(t.code);return{code:t.code,message:t.message,severity:r.severity,path:ZD(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:eB(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function rm(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,wS),truncated:t.length>wS}}oe();import Un from"path";Ut();K();Ct();Da();Di();var Xo={maxArtifacts:128},Kn=/^[a-f0-9]{64}$/u;function ru(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function iu(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function ci(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function yS(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function im(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function tB(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Un.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Un.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function NS(e,t){return Un.join(Y(e,t),"checkpoints","progress.json")}function Qo(e,t){return Un.join(Y(e,t),"checkpoint-journal.json")}function bS(e,t,r){if(!Kn.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Un.join(Y(e,t),"checkpoints","manifests",`${r}.json`)}function rB(e){if(!Kn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function nm(e,t,r){let i=await Gr({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function iB(e,t){let r=ru(e,`checkpoint manifest artifact ${t}`);iu(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=tB(ci(r.path,`checkpoint artifact ${t} path`,4096)),n=Ft(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!Kn.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:im(r.size,`checkpoint artifact ${t} size`)}}function am(e,t){let r=ru(e,"Native checkpoint manifest");if(iu(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Xo.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(iB),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=im(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function kS(e){return ee(JSON.stringify(am(e,e.change)))}function SS(e,t){let r=ru(e,"Native progress checkpoint");if(iu(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=yS(r.previousRevision,"Native checkpoint previousRevision"),a=yS(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ci(r.manifestHash,"Native checkpoint manifestHash",64);if(!Kn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=rB(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ci(r.inputHash,"Native checkpoint inputHash",64);if(!Kn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ci(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=im(r.artifactCount,"Native checkpoint artifactCount");if(u>Xo.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ci(r.summary,"Native checkpoint summary"),p=ci(r.nextAction,"Native checkpoint nextAction");if(mt(d)!==d||mt(p)!==p)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ci(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:p,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function nB(e,t){let r=ru(e,"Native checkpoint journal");if(iu(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Gt(r.previousState),n=Gt(r.nextState),a=SS(r.checkpoint,t),o=am(r.manifest,t),s=ci(r.inputHash,"Native checkpoint journal inputHash",64),c=ee(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Kn.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==kS(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function aB(e,t,r){let i=Un.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=ap(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await wf({root:e.projectRoot,file:i,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function oB(e,t){let r=NS(e,t),i=Ne(e,r);await V(i,r);try{return SS(await nm(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function sB(e,t,r){let i=bS(e,t,r),n=Ne(e,i);await V(n,i);let a=await nm(n,i,"Native checkpoint manifest"),o=am(a,t);if(ES(e,o),kS(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function om(e,t){let r=Qo(e,t),i=Ne(e,r);await V(i,r);try{let n=nB(await nm(i,r,"Native checkpoint journal"),t);return ES(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function ES(e,t){for(let r of t.artifacts){let i=ap(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function xS(e){let t;try{t=await oB(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:NS(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await sB(e.paths,e.name,t.manifestHash);let a=ee(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await aB(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:bS(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var CS=240,RS=8,nu=50;function PS(e){let t=Array.from(e);return t.length<=CS?e:`${t.slice(0,CS-1).join("")}…`}function cB(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function lB(e){let t=[...new Set(e.map(cB))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,RS),reasonCount:e.length,codesTruncated:t.length>RS};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,nu),reasonsTruncated:e.length>nu}}}async function _S(e){let t=null;try{let s=await om(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Qo(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Qo(e.paths,e.state.name)}}let r=await xS({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=lB(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Xo.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:PS(r.checkpoint.summary),nextAction:PS(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Xo.maxArtifacts}}import{promises as cF}from"node:fs";import US from"node:path";de();import AS from"node:path";var uB="comet.native.archive-preflight.v1",dB="comet.native.archive-preflight.v1",pB="comet.native.archive-operation.v1",fB=/^[a-f0-9]{64}$/u,IS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function au(e,t){return e<t?-1:e>t?1:0}function mB(e,t){if(typeof e!="string"||!fB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kr(e,t){return e===null?null:mB(e,t)}function vB(e,t){let r=AS.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||AS.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function gB(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function wB(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function yB(e,t){if(!IS.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=kr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=kr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=kr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function NB(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:kr(e.contractHash,"Native archive contract hash"),acceptanceHash:kr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:kr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:kr(e.reportHash,"Native archive report hash"),envelopeHash:kr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:kr(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function bB(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!hB.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(au);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function kB(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(au)}function TS(e){if(!IS.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(yB).sort((l,u)=>au(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:j(pB,l)})),i=NB(e.evidence),n=wB(e.workspace),a=[...new Set([...bB(e.findingCodes??[]),...kB({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(au),o=gB(e.revision),s=vB(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:uB,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:j(dB,c)}}at();de();import{createHash as SB}from"node:crypto";import jS from"node:path";var EB="comet.native.conflict-radar.v1",Ke=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}),xB="comet.native.conflict-radar.v1",CB="comet.native.conflict-radar-signals.v1",RB=/^[a-f0-9]{64}$/u,HS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PB=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),_B=new Set(["capability","operation","baseHash"]),AB=new Set(["path","kind"]);function Yn(e,t){return e<t?-1:e>t?1:0}function sm(e){return Buffer.byteLength(e,"utf8")}function cm(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function lm(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(sm(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function IB(e,t){let r=lm(e,t,Ke.maxArtifactPathBytes),i=jS.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||jS.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function DS(e,t){if(typeof e!="string"||!RB.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function TB(e,t){let r=cm(e,_B,t),i=lm(r.capability,`${t} capability`,Ke.maxCapabilityBytes);if(!HS.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:DS(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function jB(e,t){let r=cm(e,AB,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:IB(r.path,`${t} path`),kind:r.kind}}function $B(e,t){let r=cm(e,PB,`Conflict radar change ${t}`),i=lm(r.name,`Conflict radar change ${t} name`,Ke.maxNameBytes);if(!HS.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>Ke.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>Ke.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>TB(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>Yn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>jB(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>Yn(c.path,l.path)||Yn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:DS(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function OB(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ke.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map($B).sort((n,a)=>Yn(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>Ke.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ke.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function HB(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function DB(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function BB(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function FB(e,t){let r=[],i=SB("sha256").update(`${CB}
262
+ [`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(oa(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Ke.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(HB(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=DB(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:BB(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function $S(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function LB(e,t){return $S(e.classification)-$S(t.classification)||Yn(e.left,t.left)||Yn(e.right,t.right)}function OS(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:EB,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function BS(e){let t=OB(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(FB(t[s],t[c]));r.sort(LB);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(xB,{changes:t,relationships:i}),a=r.slice(0,Ke.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=OS(t,r,a,n);for(;a.length>0&&sm(JSON.stringify(o))>Ke.maxSerializedBytes;)a=a.slice(0,-1),o=OS(t,r,a,n);if(sm(JSON.stringify(o))>Ke.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}si();Ct();var qB=4096;async function MB(e,t=Ke.maxChanges){try{let r=await co({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function FS(e,t){let r=await Yt(e,t),[i,n]=await Promise.all([r.implementation_scope?Yl(e,t,r.implementation_scope):null,mr(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ou(e,t,r={}){let n=(await MB(e,qB)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await FS(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await FS(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=BS([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}Qe();K();ro();at();si();Rn();qi();Ul();import{execFile as ZB}from"node:child_process";Ji();ta();mh();import{promisify as eF}from"node:util";Re();oe();jh();K();Lt();import{constants as um,promises as gt}from"node:fs";import Xn from"node:path";var WB=/^[a-f0-9]{64}$/u,zB=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function GB(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function su(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Xe(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function JB(e,t){let r=Xn.resolve(e),i=Xn.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...Xn.relative(r,i).split(Xn.sep).filter(Boolean)]){o&&(a=Xn.join(a,o));let s=await gt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await gt.realpath(a);if(n.length>0&&!q(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function qS(e){for(let t of e){let r=await gt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!GB(t,r)||await gt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function UB(e){if(!WB.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function KB(e){let t=zB.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function YB(e,t,r){return Mr(Y(e,t),UB(r))}async function XB(e,t,r){let i=await JB(r,Xn.dirname(e)),n=await gt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([gt.realpath(t),gt.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":um.O_RDONLY|um.O_NOFOLLOW|um.O_NONBLOCK,c=await gt.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),gt.lstat(e),gt.realpath(e)]);if(await qS(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!su(n,l)||!su(l,u))throw new Error("Native check receipt changed while opening");let p=[],f=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=await c.read(m,0,m.length,null);if(b.bytesRead===0)break;f+=b.bytesRead,p.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,g]=await Promise.all([c.stat(),gt.lstat(e),gt.realpath(e)]);if(await qS(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!su(l,h)||!su(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(p,f).toString("utf8"))}finally{await c.close()}}async function MS(e,t,r){let i=KB(r),n=Y(e,t),a=YB(e,t,i),o=Ne(e,a);await V(o,a);let s=Dk(await XB(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}si();Re();Di();var Zo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Rn();Mo();qi();var w5=64*1024;var y5=3600*1e3;var N5=eF(ZB);var tF=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function VS(e,t){let r=[];for(let i of tF){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function WS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await MS(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}Mo();var li=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}};function rF(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function iF(e){let t=rF(e.bundle.baseline),r=await If(e.paths,t,{origin:"explicit",now:e.now});return Rh({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function GS(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Vo(e.paths,e.state.name,e.state.implementation_scope),r=await Tn({changeDir:ke(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await iF({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function JS(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await GS(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function nF(e){let t=await re({root:ke(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Oy(t.text)}}function aF(e){let{receipt:t,implementationScope:r}=e,i=[],n=Ch({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function oF(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Hh(e.implementationScope.scope.declaredArtifacts)}}async function zS(e){let t=await Wo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=VS(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new li([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await WS({paths:e.paths,state:e.state,receipt:t});if(n){let a=aF({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function sF(e){let t=oF({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await zS({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof li)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await zS({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof li)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new li(r)}function dm(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function pm(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:dm(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([GS(e),Wn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:dm(e.state.verification_result,"stale"),envelope:null};let i=await nF({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await sF({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:dm(e.state.verification_result,"invalid"),envelope:null}}}function lF(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function KS(e){try{return await cF.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uF(e,t){try{return(await re({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function dF(e,t,r){let i=No(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=US.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await uF(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await re({root:ke(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function pF(e,t){return KS(Yh(e,t))}async function fm(e){let t=e.now??new Date,r=await Yt(e.paths,e.name),i=await mr(e.paths,e.name),n=await xe(e.paths.projectRoot),a=lF(r.name,t),o=US.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,p,f]=await Promise.all([Promise.all(r.spec_changes.map(m=>dF(e.paths,r.name,m))),pm({paths:e.paths,state:r,now:t}),ou(e.paths,r.name),Sl(e.paths,r.name),rb(e.paths,r.name),pF(e.paths,r.name),KS(o)]);return TS({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||p,targetRef:a,targetExists:f,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}K();si();Mo();qi();async function fF(e,t){let r=Y(e,t.name),i=await _n(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await gl(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ai(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function hF(e,t){let r=await fF(e,t);return{committed:r,latest:sS(r),history:oS(r)}}async function YS(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await hF(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}si();Ct();K();function es(e,t){try{return Ga(e,t)}catch{return}}var ts=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function vF(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function gF(e){return(await Yk(e))?.change??null}function wF(e,t,r=!1,i){return tu({state:e,archiveReady:t,evidenceRetreat:r}).command}async function yF(e,t){let r=ke(e,t.name),i=[...(await xl(r,t.brief)).findings,...(await pb(e,t)).findings,...await Qk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await cl(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await IN(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Tn({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await gS(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await zf(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function hm(e,t,r){let i=await gF(e)===t,n=await Ip(e,t),a=await mo(e,t),o;try{let y=await qf(e,t);if(y.status==="migration-required"&&y.state)return{name:t,artifacts:es(e,t),phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,artifacts:es(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,artifacts:es(e,t),phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=tm({paths:e,state:o,findings:[y]}),O=tu({state:o,findings:C});return{name:o.name,artifacts:es(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:rm(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await _S({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await YS(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await Tn({changeDir:ke(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Q=await Wn(e,o.name,o.verification_evidence);for(let Te of Q.acceptanceTrace.entries)C.set(Te.acceptanceId,Te.status==="failed"?"failed":Te.status==="missing"?"missing":"satisfied")}let O=Ty({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),T=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...T?{nextPageCommand:vF(T),nextPageArgs:T}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await ou(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let p=[];try{let y=await mr(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await In({paths:e,identity:y});C.state==="drifted"&&C.code&&p.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Nl({paths:e,identity:y});p.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{p.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let f=[],m=!1;if(o.phase==="verify"){let y=await JS({paths:e,state:o});m=y.freshness!=="fresh",f.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,v=[];if(o.phase==="archive")try{h=await fm({paths:e,name:o.name}),v.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await yF(e,o),...s.findings,...d,...p,...f,...l,...v].filter((y,C,O)=>O.findIndex(T=>T.code===y.code&&T.path===y.path)===C),b=tm({paths:e,state:o,findings:g}),k=b.filter(y=>!An(y.code)),N=o.phase==="archive"&&h?.ready===!0&&k.length===0,x=m||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),w=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=b.find(y=>y.severity==="error");return{name:o.name,artifacts:es(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:w||S?null:wF(o,N,x,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:rm(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:tu({state:o,findings:b,archiveReady:N,evidenceRetreat:x,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:nu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function XS(e){let t;try{t=await yf({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await mF.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>ts.maxChanges))throw new Error(`Native status exceeds ${ts.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}K();var vm=ir(Bt(),1);pt();de();at();xt();import{promises as NF}from"node:fs";import mm from"node:path";var cu=class extends Error{};async function uu(e,t){let r=await re({root:e.nativeRoot,ref:mm.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,vm.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new cu("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:ze(i)}}async function ZS(e,t,r){let i;try{i=await NF.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=mm.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await uu(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof cu)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function lu(e){return j("comet.native.status-record.v1",e)}function QS(e){let t=mm.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Je(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=ze((0,vm.parse)(Je(e.projectRoot,["show",`${r}:${t}`])));return lu(i)===lu(e.state)?r:null}catch{return null}}function eE(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=QS(e),i=QS(t);if(!r||!i)return!1;try{return Je(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function tE(e,t){return e.state.archived&&t.state.archived&&lu(e.state)===lu(t.state)}import uE from"node:path";import{promises as rE}from"node:fs";import bF from"node:path";de();var kF=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),SF=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),EF=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),xF=new Set(["status","summary"]);function du(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function pu(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 CF(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Vi(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function RF(e,t,r,i){let n=du(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=pu(n,kF,"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=du(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=pu(o,SF,"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 c=du(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=pu(c,xF,"Native Supervisor finalVerification");if(l)return l;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 p=du(d,`Native Supervisor child ${u}`);if(!p)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:m,...h}=p,v=pu(h,EF,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],b=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(b)||m!==void 0&&m!==j("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(p.name!==g.name||p.summary!==g.summary||!CF(p.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(p.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} status`;if(p.baseCommit!==null||p.candidateCommit!==null||p.verifiedCommit!==null||p.integrationCommit!==null||p.verification!==null||p.blocker!==null||p.projectRoot!==null||p.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((p.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(p.checks)||p.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function iE(e){let t=To(e.paths,e.state.name),r;try{let c=await rE.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Vi(t,"","Native Supervisor overlay is not a regular file");r=await rE.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Vi(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Vi(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=bF.join(e.paths.changesDir,e.state.name),a;try{a=await Qt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Vi(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.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 et(e.paths,e.state.name)}catch(c){return Vi(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Vi(t,r,"Native Supervisor overlay disappeared during inspection");let s=RF(i,e.state,a.contract,o);return s?Vi(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}}no();Hi();function Se(e,t,r){return e.language==="zh-CN"?r:t}function PF(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:Se(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:Se(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Se(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(Se(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(Se(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"?Se(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Se(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} ${Se(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:Se(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:Se(e,"Accept the result","接受结果"),agentInstruction:Se(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=Dl)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(Se(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(Se(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 _F(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 AF(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:Se(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Se(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function sE(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Wi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function nE(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function IF(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function aE(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function TF(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jF(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function rr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:sE({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Wi("summary","--summary"),IF(e.name,e.flag)]}}function oE(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:Se(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function $F(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function fu(e){return[rr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),rr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function OF(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 rs(e,t,r={}){let i=TF(t)&&e.coordination_mode===void 0,n=PF(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:[Wi("summary","--summary")],commandAlternatives:i?Hy.map(s=>{let c=rr({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,aE("coordination-mode","--coordination-mode",[s])]}}):[rr({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:[Wi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=rr({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],rr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...fu({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:[Wi("summary","--summary")],commandAlternatives:[rr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),rr({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:[Wi("summary","--summary")],commandAlternatives:[rr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...fu({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:[Wi("summary","--summary")],commandAlternatives:fu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:fu({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?sE({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:jF({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[nE()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Dl)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:Se(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[Wi("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=nE();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Se(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:OF([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=oE(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>$F(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:oE(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[aE("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...AF(e)],userCommunication:_F(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[rr({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 cE from"node:path";function lE(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function gm(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:lE(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:lE(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>cE.relative(t.projectRoot,cE.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}K();function dE(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function pE(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function fE(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:BF(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:FF(i,r)}))]:[]]}function hE(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function HF(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=Yf(e,t??null);if(n===void 0)return;let a=n==="confirmed";return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:a?"confirmed":"unconfirmed",...a?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function hu(e,t,r=we(e.projectRoot)){let i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:uE.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function wm(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=gm(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...rs(t),status:"blocked",disposition:"blocked",action:"archive",requiresUserDecision:!1,commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:null,agentInstruction:"Report the Git blocker and resolve it within the recorded delivery authorization, then retry the recorded Native workspace finish command. Ask the user only when new information or authorization is required; keep delivery pending until it succeeds."},runnerAction:{...rs(t).runnerAction,kind:"none"}}:rs(t),c=e.details?fE(t,null,[]):[],l=pE(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?dE(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:Ga(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:uE.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:hE(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function DF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function mu(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function BF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:mu(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function FF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:mu(e.summary,t)??""}}async function mE(e){let t=await Qf(e),r=gm(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await jo({paths:e.paths,state:t.state}),a=await iE({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await et(e.paths,e.name,{diagnostics:!0}),s=o?{...hu(e.paths,t.state,e.gitContext),projectRoot:"."}:hu(e.paths,t.state,e.gitContext),c=rs(t.state,n,{verifierExecutionRef:Kf(t.state,t.local),verifierStartup:Yf(t.state,t.localStatus==="available"?t.local:null),...t.local?{verificationCheckPlans:Kk(t.local,t.local.workspace.projectRoot)}:{}}),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?DF(e.paths,o):[],d=o?(()=>{let m=new Map(n?.children.map(w=>[w.name,w.status])??[]),h=w=>m.get(w.name)??w.status,v=o.children.filter(w=>h(w)==="pending"||h(w)==="ready").length,g=o.children.filter(w=>h(w)==="active"||h(w)==="verified").length,b=o.children.filter(w=>h(w)==="integrated"||h(w)==="archived").length,k=o.children.filter(w=>h(w)==="blocked"||h(w)==="needs-reverify").length,N=o.children.filter(w=>h(w)==="active"||h(w)==="blocked"||h(w)==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:mu(w.blocker,u)})),x=o.children.flatMap(({blocker:w})=>{let S=mu(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:b,blocked:k,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:b},risks:x,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&b===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,p=e.details?(()=>{let m=o?.stateVersion??0,h=fE(t.state,o,u),v=pE(e.cursor,t.state.state_version,m),g=h.slice(v,v+32),b=v+g.length<h.length?dE(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:m}})():null,f=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,artifacts:Ga(e.paths,t.state.name),phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:hE(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let m=HF(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...m?{verifierStartup:m}:{}}})(),...n?{childSummary:n.children.reduce((m,h)=>({...m,[h.status]:(m[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:p.supervisorStateVersion}:{},items:p.items,nextCursor:p.nextCursor,nextPageArgs:p.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",p.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}import{accessSync as fX,constants as hX,promises as ym}from"node:fs";import Qn from"node:path";oe();Ui();pt();ql();Ui();var vE="comet.native.workspace-finish.v1",wE="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",yE=new RegExp(`^${wE}$`,"u"),qF=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,is=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function gE(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function MF(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==vE||typeof t.name!="string"||!yE.test(t.name)||typeof t.transactionId!="string"||!qF.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Qn.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"&&Qn.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!Qn.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");gE(r.commitMessage,"commit-message"),r.mergeMessage!==null&&gE(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||!is.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!Qn.posix.isAbsolute(i)&&!Qn.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!is.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!is.test(r.target)||!is.test(r.source)||r.sha!==null&&!is.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:vE,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 VF(e,t){if(!yE.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Qn.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function Nm(e,t,r={}){let i=VF(e,t);try{let n=await ym.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=MF(JSON.parse(await ym.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 NE(e,t={}){let r;try{r=await ym.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${wE})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await Nm(e,a[1],t);o&&i.push(o)}return i}function vu(e,t){let r=zi.normalize(bm(e)),i=zi.normalize(bm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bm(e){let t=zi.resolve(e);try{return WF.native(t)}catch{return t}}async function bE(e,t){let r=[];for(let i of await XS(e))t!==void 0&&i!==t||r.push({name:i,kind:await Eo(e,i)?"portable":"legacy"});return r}async function zF(e,t){let r=zi.resolve(e),i=us(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>vu(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>zi.resolve(l)).sort()){let l=vu(c,r)?r:c,u=bm(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let p=await xe(l);if(!p)continue;let f=await Vt(l,p.native.artifact_root);o.push({projectRoot:l,config:p,paths:f,gitContext:aa(l,i)??we(l),changes:await bE(f,t)})}if(o.length===0){let c=await xe(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Vt(e,c.native.artifact_root);o.push({projectRoot:zi.resolve(e),config:c,paths:l,gitContext:aa(e,i)??we(e),changes:await bE(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await ZS(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await Nm(c.paths,t,{onError:l})].filter(u=>u!==null):await NE(c.paths,{onError:l})}return o}function kE(e,t){return e.workspace.bindingState==="aligned"?0:vu(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function GF(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:d,kind:p})=>{let f=d.finishJournalErrors?.find(({name:m})=>m===n);if(p==="portable")try{let m=await ft(d.paths,n);return{source:d,name:n,kind:p,workspace:hu(d.paths,m,d.gitContext),portableStatus:null,inspectionError:f?.message??null,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}}catch(m){return{source:d,name:n,kind:p,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:m instanceof Error?m.message:String(m)}}return{source:d,name:n,kind:p,workspace:a.length>1?await mo(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:f?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:p})=>p.name===n).map(p=>{let f=wm({paths:d.paths,...p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null});return{source:d,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:d.finishJournalErrors?.find(({name:m})=>m===n)?.message??null,record:p,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(p=>p.name===n).map(p=>({source:d,error:p})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(f=>f.finishJournals?.some(({name:m})=>m===n)),p=d?.finishJournals?.find(({name:f})=>f===n);if(d&&p){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:p.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:p.result?.message??"Native workspace finish record is orphaned."},finishJournal:p});continue}}if(s.length>0){for(let p of o)if(p.kind==="portable")try{p.record=await uu(p.source.paths,zi.join(p.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(p=>[...o,...s.filter(f=>!tE(p.record,f.record))].every(f=>f.record&&eE(p.record,f.record)));if(d){i.push(d);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((d,p)=>kE(d,e)-kE(p,e)||d.source.projectRoot.localeCompare(p.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>ts.maxChanges)throw new Error(`Native status discovery exceeds ${ts.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}async function JF(e,t,r){let i=await mo(e.source.paths,e.name),n=null;try{n=await nb(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:hm(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function SE(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return wm({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await mE({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return SE({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return JF(e,t,r)}async function EE(e){let{sources:t,candidates:r}=await UF(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>vu(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),hm(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}return e.onSelectedRoot?.(r[0].source.projectRoot),SE(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function UF(e,t){let r=await zF(e,t),i=(await GF(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}Va();import ns from"path";import{realpathSync as pL}from"fs";function xE(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),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var Sr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function CE(e){return e?e.command?`${Sr.next} ${e.command}`:e.ask_user?`${Sr.next} ${e.ask_user}`:null:null}function RE(e,t){let r=[e.summary],i=CE(e.next);return i&&r.push(i),e.user_message&&r.push("",Sr.relay,e.user_message),t!==void 0&&r.push("",Sr.details,JSON.stringify(t,null,2)),`${r.join(`
179
263
  `)}
180
- `}function Jk(e,t,r){let i=[e.summary],n=Wk(e.next);return n&&i.push(n),e.user_message&&i.push("",fr.relay,e.user_message),i.push("",`${fr.detail} ${t}`),r!==void 0&&i.push("",fr.details,JSON.stringify(r,null,2)),i.join(`
181
- `)}Lt();yt();le();Tt();U();yt();vc();le();oi();Kr();var _3=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Lt();ka();Ee();U();yt();vc();var Cl=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"},Pl=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"};U();Ge();function L(e,t,r){return e==="zh-CN"?r:t}var hh={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Gk(e,t){return typeof e=="string"&&hh[e]?L(t,hh[e].en,hh[e].zh):typeof e=="string"?e:""}function mh(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 nD(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 Uk(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Kk(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 vh(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function aD(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function oD(e,t,r){let i=vh(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=Gk(e.phase,i),s=aD(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Uk(t,i));let c=e.userCommunication,l=Yk(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Yk(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(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:L(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:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function sD(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function cD(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Gk(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=mh(e.acceptance)?`${L(t,", ",",")}${Uk(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function lD(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 uD(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 dD(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=fD(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("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:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function fD(e){return Kk(e)?Yk(e,vh(e)):void 0}function Xk(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(uD(t))return dD(t);if(sD(t)){let i=lD(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>cD(a,i))].join(`
182
- `)}}let r=t.continuation;if(Kk(r)){let i=vh(r),n=oD(r,pD(t),mD(t,i));return hD(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(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:L(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 pD(e){if(mh(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(mh(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return nD(r.acceptance)}return null}function hD(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 mD(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Qk(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:L("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:L("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:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("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:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("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:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}rp();var Zk=["--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."],gh=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:Zk,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
264
+ `}function PE(e,t,r){let i=[e.summary],n=CE(e.next);return n&&i.push(n),e.user_message&&i.push("",Sr.relay,e.user_message),i.push("",`${Sr.detail} ${t}`),r!==void 0&&i.push("",Sr.details,JSON.stringify(r,null,2)),i.join(`
265
+ `)}Ut();Ct();oe();Lt();K();Ct();tl();oe();Ni();si();var hQ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ut();Ka();Re();K();Ct();tl();var gu=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"},wu=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"};K();Qe();function L(e,t,r){return e==="zh-CN"?r:t}var km={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function _E(e,t){return typeof e=="string"&&km[e]?L(t,km[e].en,km[e].zh):typeof e=="string"?e:""}function Sm(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 XF(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 AE(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function IE(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 Em(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function QF(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function ZF(e,t,r){let i=Em(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=_E(e.phase,i),s=QF(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(AE(t,i));let c=e.userCommunication,l=TE(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function TE(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(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:L(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:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function eL(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function tL(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=_E(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=Sm(e.acceptance)?`${L(t,", ",",")}${AE(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function rL(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 iL(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 nL(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=aL(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("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:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function aL(e){return IE(e)?TE(e,Em(e)):void 0}function jE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(iL(t))return nL(t);if(eL(t)){let i=rL(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>tL(a,i))].join(`
266
+ `)}}let r=t.continuation;if(IE(r)){let i=Em(r),n=ZF(r,oL(t),cL(t,i));return sL(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(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:L(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 oL(e){if(Sm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Sm(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return XF(r.acceptance)}return null}function sL(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 cL(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function $E(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:L("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:L("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:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("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:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("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:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Vc();Wc();var OE=["--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."],xm=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:OE,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
183
267
  comet native spec remove <change-name> <capability>
184
268
  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>]
185
269
  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>]
186
- 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]
187
- 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 Rl(e,t){return`${e}:
270
+ 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>]
271
+ 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 yu(e,t){return`${e}:
188
272
  ${t.map(r=>` ${r}`).join(`
189
- `)}`}function vD(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return gh[r]||t.length>1&&gh[t[0]]?.subcommands?r:t[0]}function gD(e=[]){let t=vD(e),r=gh[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Rl("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Rl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Zk];return n&&n.length>0&&i.push("",Rl("Options",n)),i.push("",`Output:
190
- ${r.output}`),r.examples&&i.push("",Rl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
273
+ `)}`}function lL(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return xm[r]||t.length>1&&xm[t[0]]?.subcommands?r:t[0]}function uL(e=[]){let t=lL(e),r=xm[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",yu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",yu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...OE];return n&&n.length>0&&i.push("",yu("Options",n)),i.push("",`Output:
274
+ ${r.output}`),r.examples&&i.push("",yu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
191
275
  `)}
192
- `}}var wD=gD().usage;var $8=10*1024*1024,Zr=class extends Error{};function yh(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Zr(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function tS(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Zr(`${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 Zr(`${t} requires a value`);return e.splice(i,2),n}function rS(e){if(e.length>0)throw new Zr(`Unexpected argument: ${e[0]}`)}function iS(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Zr(`${t} is required`);return r}function wh(e,t){let r=So.normalize(eS(e)),i=So.normalize(eS(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function eS(e){let t=So.resolve(e);try{return yD.native(t)}catch{return t}}function ND(e){let t=So.resolve(e),r=ve(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=ve(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!wh(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||wh(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:wh(process.cwd(),r.currentWorktreeRoot)?So.resolve(process.cwd()):r.currentWorktreeRoot}async function nS(e){return e?ND(e):Vs(process.cwd())}async function Nh(e){let t=await jg({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function aS(e){return JSON.stringify(e,null,2)+`
193
- `}function oS(e,t,r){return{command:e,exitCode:0,data:t,text:r??aS(t)}}function bD(e,t){if(t instanceof zc)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Zr)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Cl)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 Pl)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Hc)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 Ba)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 Qc)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Dc)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 Xr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof yo)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 sS(e,t){let r=bD(e,t),i=r.error;if(!i)return r;let n=Qk({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function kD(e,t,r=!1){let i=e.envelope??Xk(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:Mk(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}})+`
194
- `}:e.error?{exitCode:e.exitCode,stderr:i?Jk(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:zk(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==aS(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
195
- ${fr.details}
276
+ `}}var dL=uL().usage;var bZ=10*1024*1024,ui=class extends Error{};function Rm(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new ui(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function DE(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new ui(`${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 ui(`${t} requires a value`);return e.splice(i,2),n}function BE(e){if(e.length>0)throw new ui(`Unexpected argument: ${e[0]}`)}function FE(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new ui(`${t} is required`);return r}function Cm(e,t){let r=ns.normalize(HE(e)),i=ns.normalize(HE(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function HE(e){let t=ns.resolve(e);try{return pL.native(t)}catch{return t}}function fL(e,t){let r=ns.resolve(t,e),i=we(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=we(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!Cm(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||Cm(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:Cm(t,i.currentWorktreeRoot)?ns.resolve(t):i.currentWorktreeRoot}async function LE(e,t=process.cwd()){return e?fL(e,t):Cc(t)}function qE(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function Pm(e){let t=await Xw({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ME(e){return JSON.stringify(e,null,2)+`
277
+ `}function VE(e,t,r){return{command:e,exitCode:0,data:t,text:r??ME(t)}}function hL(e,t){if(t instanceof go)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof gn)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 io)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof ui)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof gu)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 wu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof bl)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 vo)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 Ml)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof kl)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 li)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Zo)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 WE(e,t){let r=hL(e,t),i=r.error;if(!i)return r;let n=$E({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function mL(e,t,r=!1){let i=e.envelope??jE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:xE(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}})+`
278
+ `}:e.error?{exitCode:e.exitCode,stderr:i?PE(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:RE(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==ME(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
279
+ ${Sr.details}
196
280
  ${JSON.stringify(e.data,null,2)}
197
- `}:{exitCode:e.exitCode,stdout:e.text}}function SD(e,t,r=!1){let i=kD(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 cS(e,t,r=!1){return SD(e,t,r).output}async function lS(e,t){let r=iS(e,"change name");rS(e),await Nh(t);let i=t,n=await Vk({projectRoot:t,name:r,onSelectedRoot:a=>{i=a}});return await mb((await Nh(i)).paths,r),{...oS("select",{selected:r,...n}),executionCwd:i}}async function uS(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{yh(n,"--json"),yh(n,"--verbose"),c=tS(n,"--project-root");let d=[...n,...a],f=await nS(c);l={executionCwd:f,...await t(d,f)}}catch(d){l=sS(e,d)}let u=cS(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
281
+ `}:{exitCode:e.exitCode,stdout:e.text}}function vL(e,t,r=!1){let i=mL(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 zE(e,t,r=!1){return vL(e,t,r).output}async function GE(e,t){let r=FE(e,"change name");BE(e),await Pm(t);let i=t,n=await EE({projectRoot:t,name:r,onSelectedRoot:a=>{i=a}});return await Xk((await Pm(i)).paths,r),{...VE("select",{selected:r,...n}),executionCwd:i}}async function JE(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Rm(n,"--json"),Rm(n,"--verbose"),c=DE(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await LE(c);return{executionCwd:f,...await t(d,f)}};l=qE(e,d)?await $m(p):await p()}catch(d){l=WE(e,d)}let u=zE(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
198
282
  `)?"":`
199
- `)),u.exitCode}process.exitCode=await uS("select",lS);
283
+ `)),u.exitCode}process.exitCode=await JE("select",GE);