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

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 (572) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.html +8 -0
  4. package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.json +286 -0
  5. package/assets/manifest.json +25 -17
  6. package/assets/skills/comet/SKILL.md +1 -1
  7. package/assets/skills/comet/agents/openai.yaml +3 -0
  8. package/assets/skills/comet/rules/comet-phase-guard.en.md +1 -1
  9. package/assets/skills/comet/rules/comet-phase-guard.md +1 -1
  10. package/assets/skills/comet/rules/comet-workflow-guard.en.md +2 -2
  11. package/assets/skills/comet/rules/comet-workflow-guard.md +2 -2
  12. package/assets/skills/comet/scripts/comet-archive.mjs +65 -65
  13. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +47 -47
  14. package/assets/skills/comet/scripts/comet-guard.mjs +105 -105
  15. package/assets/skills/comet/scripts/comet-handoff.mjs +74 -74
  16. package/assets/skills/comet/scripts/comet-hook-guard.mjs +75 -75
  17. package/assets/skills/comet/scripts/comet-hook-router.mjs +142 -140
  18. package/assets/skills/comet/scripts/comet-resume-probe.mjs +87 -87
  19. package/assets/skills/comet/scripts/comet-runtime.mjs +145 -145
  20. package/assets/skills/comet/scripts/comet-state.mjs +69 -69
  21. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +89 -89
  22. package/assets/skills/comet-any/SKILL.md +2 -1
  23. package/assets/skills/comet-any/agents/openai.yaml +5 -0
  24. package/assets/skills/comet-archive/SKILL.md +7 -6
  25. package/assets/skills/comet-archive/agents/openai.yaml +5 -0
  26. package/assets/skills/comet-build/SKILL.md +14 -13
  27. package/assets/skills/comet-build/agents/openai.yaml +5 -0
  28. package/assets/skills/comet-classic/SKILL.md +14 -14
  29. package/assets/skills/comet-classic/agents/openai.yaml +3 -0
  30. package/assets/skills/{comet → comet-classic}/reference/auto-transition.md +1 -1
  31. package/assets/skills/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
  32. package/assets/skills/{comet → comet-classic}/reference/context-recovery.md +5 -5
  33. package/assets/skills/{comet → comet-classic}/reference/debug-gate.md +2 -2
  34. package/assets/skills/{comet → comet-classic}/reference/decision-point.md +1 -1
  35. package/assets/skills/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
  36. package/assets/skills/{comet → comet-classic}/reference/file-structure.md +1 -1
  37. package/assets/skills/{comet → comet-classic}/reference/intent-frame.md +1 -1
  38. package/assets/skills/{comet → comet-classic}/reference/scripts.md +1 -1
  39. package/assets/skills/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  40. package/assets/skills/comet-design/SKILL.md +7 -6
  41. package/assets/skills/comet-design/agents/openai.yaml +5 -0
  42. package/assets/skills/comet-hotfix/SKILL.md +10 -9
  43. package/assets/skills/comet-hotfix/agents/openai.yaml +5 -0
  44. package/assets/skills/comet-native/SKILL.md +54 -168
  45. package/assets/skills/comet-native/agents/openai.yaml +3 -0
  46. package/assets/skills/comet-native/reference/artifacts.md +23 -89
  47. package/assets/skills/comet-native/reference/clarification.md +54 -29
  48. package/assets/skills/comet-native/reference/commands.md +30 -173
  49. package/assets/skills/comet-native/reference/recovery.md +38 -88
  50. package/assets/skills/comet-native/reference/workspace.md +23 -0
  51. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +184 -152
  52. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +219 -163
  53. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +126 -117
  54. package/assets/skills/comet-native/scripts/comet-native-init.mjs +134 -124
  55. package/assets/skills/comet-native/scripts/comet-native-new.mjs +170 -163
  56. package/assets/skills/comet-native/scripts/comet-native-next.mjs +179 -148
  57. package/assets/skills/comet-native/scripts/comet-native-root.mjs +152 -147
  58. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +247 -202
  59. package/assets/skills/comet-native/scripts/comet-native-select.mjs +153 -146
  60. package/assets/skills/comet-native/scripts/comet-native-show.mjs +117 -110
  61. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +133 -151
  62. package/assets/skills/comet-native/scripts/comet-native-status.mjs +146 -139
  63. package/assets/skills/comet-open/SKILL.md +7 -6
  64. package/assets/skills/comet-open/agents/openai.yaml +5 -0
  65. package/assets/skills/comet-tweak/SKILL.md +11 -10
  66. package/assets/skills/comet-tweak/agents/openai.yaml +5 -0
  67. package/assets/skills/comet-verify/SKILL.md +9 -8
  68. package/assets/skills/comet-verify/agents/openai.yaml +5 -0
  69. package/assets/skills-zh/comet/SKILL.md +1 -1
  70. package/assets/skills-zh/comet/agents/openai.yaml +3 -0
  71. package/assets/skills-zh/comet-any/SKILL.md +2 -1
  72. package/assets/skills-zh/comet-any/agents/openai.yaml +5 -0
  73. package/assets/skills-zh/comet-archive/SKILL.md +7 -6
  74. package/assets/skills-zh/comet-archive/agents/openai.yaml +5 -0
  75. package/assets/skills-zh/comet-build/SKILL.md +14 -13
  76. package/assets/skills-zh/comet-build/agents/openai.yaml +5 -0
  77. package/assets/skills-zh/comet-classic/SKILL.md +15 -15
  78. package/assets/skills-zh/comet-classic/agents/openai.yaml +3 -0
  79. package/assets/skills-zh/{comet → comet-classic}/reference/auto-transition.md +1 -1
  80. package/assets/skills-zh/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
  81. package/assets/skills-zh/{comet → comet-classic}/reference/context-recovery.md +5 -5
  82. package/assets/skills-zh/{comet → comet-classic}/reference/debug-gate.md +2 -2
  83. package/assets/skills-zh/{comet → comet-classic}/reference/decision-point.md +1 -1
  84. package/assets/skills-zh/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
  85. package/assets/skills-zh/{comet → comet-classic}/reference/file-structure.md +1 -1
  86. package/assets/skills-zh/{comet → comet-classic}/reference/intent-frame.md +1 -1
  87. package/assets/skills-zh/{comet → comet-classic}/reference/scripts.md +1 -1
  88. package/assets/skills-zh/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  89. package/assets/skills-zh/comet-design/SKILL.md +7 -6
  90. package/assets/skills-zh/comet-design/agents/openai.yaml +5 -0
  91. package/assets/skills-zh/comet-hotfix/SKILL.md +10 -9
  92. package/assets/skills-zh/comet-hotfix/agents/openai.yaml +5 -0
  93. package/assets/skills-zh/comet-native/SKILL.md +54 -168
  94. package/assets/skills-zh/comet-native/agents/openai.yaml +3 -0
  95. package/assets/skills-zh/comet-native/reference/artifacts.md +23 -89
  96. package/assets/skills-zh/comet-native/reference/clarification.md +40 -15
  97. package/assets/skills-zh/comet-native/reference/commands.md +30 -173
  98. package/assets/skills-zh/comet-native/reference/recovery.md +36 -86
  99. package/assets/skills-zh/comet-native/reference/workspace.md +23 -0
  100. package/assets/skills-zh/comet-open/SKILL.md +7 -6
  101. package/assets/skills-zh/comet-open/agents/openai.yaml +5 -0
  102. package/assets/skills-zh/comet-tweak/SKILL.md +11 -10
  103. package/assets/skills-zh/comet-tweak/agents/openai.yaml +5 -0
  104. package/assets/skills-zh/comet-verify/SKILL.md +9 -8
  105. package/assets/skills-zh/comet-verify/agents/openai.yaml +5 -0
  106. package/bin/fast-runtime-router.js +0 -4
  107. package/dist/app/commands/doctor.d.ts.map +1 -1
  108. package/dist/app/commands/doctor.js +8 -0
  109. package/dist/app/commands/doctor.js.map +1 -1
  110. package/dist/app/commands/init.d.ts.map +1 -1
  111. package/dist/app/commands/init.js +9 -1
  112. package/dist/app/commands/init.js.map +1 -1
  113. package/dist/app/commands/update.d.ts.map +1 -1
  114. package/dist/app/commands/update.js +9 -2
  115. package/dist/app/commands/update.js.map +1 -1
  116. package/dist/config/repository-layout.json +0 -8
  117. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  118. package/dist/domains/bundle/bundle-platform.js +8 -0
  119. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  120. package/dist/domains/bundle/types.d.ts +1 -1
  121. package/dist/domains/bundle/types.d.ts.map +1 -1
  122. package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
  123. package/dist/domains/comet-entry/hook-adapter.js +2 -0
  124. package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
  125. package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
  126. package/dist/domains/comet-entry/hook-router-entry.js +11 -2
  127. package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
  128. package/dist/domains/comet-entry/project-activation.d.ts.map +1 -1
  129. package/dist/domains/comet-entry/project-activation.js +2 -1
  130. package/dist/domains/comet-entry/project-activation.js.map +1 -1
  131. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  132. package/dist/domains/comet-entry/resume-probe.js +48 -4
  133. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  134. package/dist/domains/comet-native/native-acceptance.d.ts +4 -3
  135. package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
  136. package/dist/domains/comet-native/native-acceptance.js +23 -18
  137. package/dist/domains/comet-native/native-acceptance.js.map +1 -1
  138. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  139. package/dist/domains/comet-native/native-archive-command.js +204 -61
  140. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  141. package/dist/domains/comet-native/native-archive-transaction.d.ts.map +1 -1
  142. package/dist/domains/comet-native/native-archive-transaction.js +28 -23
  143. package/dist/domains/comet-native/native-archive-transaction.js.map +1 -1
  144. package/dist/domains/comet-native/native-archive.d.ts +1 -0
  145. package/dist/domains/comet-native/native-archive.d.ts.map +1 -1
  146. package/dist/domains/comet-native/native-archive.js +56 -12
  147. package/dist/domains/comet-native/native-archive.js.map +1 -1
  148. package/dist/domains/comet-native/native-bounded-file.d.ts +32 -2
  149. package/dist/domains/comet-native/native-bounded-file.d.ts.map +1 -1
  150. package/dist/domains/comet-native/native-bounded-file.js +87 -6
  151. package/dist/domains/comet-native/native-bounded-file.js.map +1 -1
  152. package/dist/domains/comet-native/native-build-evidence.d.ts.map +1 -1
  153. package/dist/domains/comet-native/native-build-evidence.js +23 -1
  154. package/dist/domains/comet-native/native-build-evidence.js.map +1 -1
  155. package/dist/domains/comet-native/native-change.d.ts +1 -0
  156. package/dist/domains/comet-native/native-change.d.ts.map +1 -1
  157. package/dist/domains/comet-native/native-change.js +96 -8
  158. package/dist/domains/comet-native/native-change.js.map +1 -1
  159. package/dist/domains/comet-native/native-check-executor.d.ts +36 -0
  160. package/dist/domains/comet-native/native-check-executor.d.ts.map +1 -0
  161. package/dist/domains/comet-native/native-check-executor.js +132 -0
  162. package/dist/domains/comet-native/native-check-executor.js.map +1 -0
  163. package/dist/domains/comet-native/native-check-receipt-model.d.ts +9 -0
  164. package/dist/domains/comet-native/native-check-receipt-model.d.ts.map +1 -1
  165. package/dist/domains/comet-native/native-check-receipt-model.js +70 -8
  166. package/dist/domains/comet-native/native-check-receipt-model.js.map +1 -1
  167. package/dist/domains/comet-native/native-check-receipt-storage.d.ts.map +1 -1
  168. package/dist/domains/comet-native/native-check-receipt-storage.js +9 -8
  169. package/dist/domains/comet-native/native-check-receipt-storage.js.map +1 -1
  170. package/dist/domains/comet-native/native-check-receipt.d.ts.map +1 -1
  171. package/dist/domains/comet-native/native-check-receipt.js +123 -60
  172. package/dist/domains/comet-native/native-check-receipt.js.map +1 -1
  173. package/dist/domains/comet-native/native-checkpoint-command.d.ts.map +1 -1
  174. package/dist/domains/comet-native/native-checkpoint-command.js +0 -6
  175. package/dist/domains/comet-native/native-checkpoint-command.js.map +1 -1
  176. package/dist/domains/comet-native/native-checkpoint-storage.d.ts.map +1 -1
  177. package/dist/domains/comet-native/native-checkpoint-storage.js +27 -19
  178. package/dist/domains/comet-native/native-checkpoint-storage.js.map +1 -1
  179. package/dist/domains/comet-native/native-cli-help.d.ts +6 -0
  180. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -0
  181. package/dist/domains/comet-native/native-cli-help.js +192 -0
  182. package/dist/domains/comet-native/native-cli-help.js.map +1 -0
  183. package/dist/domains/comet-native/native-cli-shared.d.ts +2 -2
  184. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  185. package/dist/domains/comet-native/native-cli-shared.js +46 -24
  186. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  187. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  188. package/dist/domains/comet-native/native-cli.js +18 -11
  189. package/dist/domains/comet-native/native-cli.js.map +1 -1
  190. package/dist/domains/comet-native/native-config.d.ts +2 -1
  191. package/dist/domains/comet-native/native-config.d.ts.map +1 -1
  192. package/dist/domains/comet-native/native-config.js +2 -1
  193. package/dist/domains/comet-native/native-config.js.map +1 -1
  194. package/dist/domains/comet-native/native-continuation.d.ts.map +1 -1
  195. package/dist/domains/comet-native/native-continuation.js +175 -147
  196. package/dist/domains/comet-native/native-continuation.js.map +1 -1
  197. package/dist/domains/comet-native/native-diagnostics.d.ts.map +1 -1
  198. package/dist/domains/comet-native/native-diagnostics.js +96 -13
  199. package/dist/domains/comet-native/native-diagnostics.js.map +1 -1
  200. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  201. package/dist/domains/comet-native/native-doctor-command.js +327 -0
  202. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  203. package/dist/domains/comet-native/native-doctor.d.ts +1 -0
  204. package/dist/domains/comet-native/native-doctor.d.ts.map +1 -1
  205. package/dist/domains/comet-native/native-doctor.js +116 -22
  206. package/dist/domains/comet-native/native-doctor.js.map +1 -1
  207. package/dist/domains/comet-native/native-evidence-projection.d.ts +50 -0
  208. package/dist/domains/comet-native/native-evidence-projection.d.ts.map +1 -0
  209. package/dist/domains/comet-native/native-evidence-projection.js +284 -0
  210. package/dist/domains/comet-native/native-evidence-projection.js.map +1 -0
  211. package/dist/domains/comet-native/native-evidence-retention.d.ts.map +1 -1
  212. package/dist/domains/comet-native/native-evidence-retention.js +14 -12
  213. package/dist/domains/comet-native/native-evidence-retention.js.map +1 -1
  214. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  215. package/dist/domains/comet-native/native-evidence-storage.js +14 -11
  216. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  217. package/dist/domains/comet-native/native-findings.d.ts.map +1 -1
  218. package/dist/domains/comet-native/native-findings.js +18 -0
  219. package/dist/domains/comet-native/native-findings.js.map +1 -1
  220. package/dist/domains/comet-native/native-git-provenance.d.ts +16 -0
  221. package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -0
  222. package/dist/domains/comet-native/native-git-provenance.js +171 -0
  223. package/dist/domains/comet-native/native-git-provenance.js.map +1 -0
  224. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  225. package/dist/domains/comet-native/native-hook-guard.js +159 -18
  226. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  227. package/dist/domains/comet-native/native-init-command.d.ts.map +1 -1
  228. package/dist/domains/comet-native/native-init-command.js +14 -2
  229. package/dist/domains/comet-native/native-init-command.js.map +1 -1
  230. package/dist/domains/comet-native/native-local-execution.d.ts +25 -0
  231. package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -0
  232. package/dist/domains/comet-native/native-local-execution.js +241 -0
  233. package/dist/domains/comet-native/native-local-execution.js.map +1 -0
  234. package/dist/domains/comet-native/native-lock.d.ts +1 -1
  235. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  236. package/dist/domains/comet-native/native-lock.js +9 -9
  237. package/dist/domains/comet-native/native-lock.js.map +1 -1
  238. package/dist/domains/comet-native/native-loop-runtime.d.ts +63 -0
  239. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -0
  240. package/dist/domains/comet-native/native-loop-runtime.js +580 -0
  241. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -0
  242. package/dist/domains/comet-native/native-mutation-lock.d.ts +2 -0
  243. package/dist/domains/comet-native/native-mutation-lock.d.ts.map +1 -1
  244. package/dist/domains/comet-native/native-mutation-lock.js +23 -2
  245. package/dist/domains/comet-native/native-mutation-lock.js.map +1 -1
  246. package/dist/domains/comet-native/native-new-command.d.ts.map +1 -1
  247. package/dist/domains/comet-native/native-new-command.js +27 -20
  248. package/dist/domains/comet-native/native-new-command.js.map +1 -1
  249. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  250. package/dist/domains/comet-native/native-next-command.js +114 -63
  251. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  252. package/dist/domains/comet-native/native-paths.d.ts +18 -0
  253. package/dist/domains/comet-native/native-paths.d.ts.map +1 -1
  254. package/dist/domains/comet-native/native-paths.js +125 -13
  255. package/dist/domains/comet-native/native-paths.js.map +1 -1
  256. package/dist/domains/comet-native/native-portable-acceptance.d.ts +28 -0
  257. package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -0
  258. package/dist/domains/comet-native/native-portable-acceptance.js +73 -0
  259. package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -0
  260. package/dist/domains/comet-native/native-portable-archive.d.ts +37 -0
  261. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -0
  262. package/dist/domains/comet-native/native-portable-archive.js +492 -0
  263. package/dist/domains/comet-native/native-portable-archive.js.map +1 -0
  264. package/dist/domains/comet-native/native-portable-continuation.d.ts +29 -0
  265. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -0
  266. package/dist/domains/comet-native/native-portable-continuation.js +341 -0
  267. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -0
  268. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts +9 -0
  269. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -0
  270. package/dist/domains/comet-native/native-portable-migration-runtime.js +213 -0
  271. package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -0
  272. package/dist/domains/comet-native/native-portable-migration.d.ts +42 -0
  273. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -0
  274. package/dist/domains/comet-native/native-portable-migration.js +212 -0
  275. package/dist/domains/comet-native/native-portable-migration.js.map +1 -0
  276. package/dist/domains/comet-native/native-portable-recovery.d.ts +15 -0
  277. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -0
  278. package/dist/domains/comet-native/native-portable-recovery.js +203 -0
  279. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -0
  280. package/dist/domains/comet-native/native-portable-runtime.d.ts +150 -0
  281. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -0
  282. package/dist/domains/comet-native/native-portable-runtime.js +1444 -0
  283. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -0
  284. package/dist/domains/comet-native/native-portable-state.d.ts +30 -0
  285. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -0
  286. package/dist/domains/comet-native/native-portable-state.js +688 -0
  287. package/dist/domains/comet-native/native-portable-state.js.map +1 -0
  288. package/dist/domains/comet-native/native-portable-status.d.ts +62 -0
  289. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -0
  290. package/dist/domains/comet-native/native-portable-status.js +125 -0
  291. package/dist/domains/comet-native/native-portable-status.js.map +1 -0
  292. package/dist/domains/comet-native/native-portable-text.d.ts +8 -0
  293. package/dist/domains/comet-native/native-portable-text.d.ts.map +1 -0
  294. package/dist/domains/comet-native/native-portable-text.js +28 -0
  295. package/dist/domains/comet-native/native-portable-text.js.map +1 -0
  296. package/dist/domains/comet-native/native-portable-transactions.d.ts +41 -0
  297. package/dist/domains/comet-native/native-portable-transactions.d.ts.map +1 -0
  298. package/dist/domains/comet-native/native-portable-transactions.js +204 -0
  299. package/dist/domains/comet-native/native-portable-transactions.js.map +1 -0
  300. package/dist/domains/comet-native/native-portable-types.d.ts +165 -0
  301. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -0
  302. package/dist/domains/comet-native/native-portable-types.js +18 -0
  303. package/dist/domains/comet-native/native-portable-types.js.map +1 -0
  304. package/dist/domains/comet-native/native-repair-integration.js +5 -5
  305. package/dist/domains/comet-native/native-repair-integration.js.map +1 -1
  306. package/dist/domains/comet-native/native-resume-view.d.ts.map +1 -1
  307. package/dist/domains/comet-native/native-resume-view.js +1 -5
  308. package/dist/domains/comet-native/native-resume-view.js.map +1 -1
  309. package/dist/domains/comet-native/native-root-move.d.ts.map +1 -1
  310. package/dist/domains/comet-native/native-root-move.js +4 -20
  311. package/dist/domains/comet-native/native-root-move.js.map +1 -1
  312. package/dist/domains/comet-native/native-run-consistency.d.ts.map +1 -1
  313. package/dist/domains/comet-native/native-run-consistency.js +8 -12
  314. package/dist/domains/comet-native/native-run-consistency.js.map +1 -1
  315. package/dist/domains/comet-native/native-run-store.js +4 -4
  316. package/dist/domains/comet-native/native-run-store.js.map +1 -1
  317. package/dist/domains/comet-native/native-runner-input.d.ts +160 -0
  318. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -0
  319. package/dist/domains/comet-native/native-runner-input.js +347 -0
  320. package/dist/domains/comet-native/native-runner-input.js.map +1 -0
  321. package/dist/domains/comet-native/native-runner-protocol.d.ts +40 -0
  322. package/dist/domains/comet-native/native-runner-protocol.d.ts.map +1 -0
  323. package/dist/domains/comet-native/native-runner-protocol.js +55 -0
  324. package/dist/domains/comet-native/native-runner-protocol.js.map +1 -0
  325. package/dist/domains/comet-native/native-runtime-package.d.ts +3 -0
  326. package/dist/domains/comet-native/native-runtime-package.d.ts.map +1 -1
  327. package/dist/domains/comet-native/native-runtime-package.js +5 -1
  328. package/dist/domains/comet-native/native-runtime-package.js.map +1 -1
  329. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  330. package/dist/domains/comet-native/native-schema-migration.js +30 -27
  331. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  332. package/dist/domains/comet-native/native-select-command.d.ts.map +1 -1
  333. package/dist/domains/comet-native/native-select-command.js +8 -4
  334. package/dist/domains/comet-native/native-select-command.js.map +1 -1
  335. package/dist/domains/comet-native/native-selection.d.ts.map +1 -1
  336. package/dist/domains/comet-native/native-selection.js +11 -2
  337. package/dist/domains/comet-native/native-selection.js.map +1 -1
  338. package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
  339. package/dist/domains/comet-native/native-show-command.js +36 -0
  340. package/dist/domains/comet-native/native-show-command.js.map +1 -1
  341. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  342. package/dist/domains/comet-native/native-snapshot.js +13 -10
  343. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  344. package/dist/domains/comet-native/native-spec-command.d.ts.map +1 -1
  345. package/dist/domains/comet-native/native-spec-command.js +14 -28
  346. package/dist/domains/comet-native/native-spec-command.js.map +1 -1
  347. package/dist/domains/comet-native/native-specs.js +3 -3
  348. package/dist/domains/comet-native/native-specs.js.map +1 -1
  349. package/dist/domains/comet-native/native-status-command.d.ts.map +1 -1
  350. package/dist/domains/comet-native/native-status-command.js +7 -17
  351. package/dist/domains/comet-native/native-status-command.js.map +1 -1
  352. package/dist/domains/comet-native/native-status-discovery.d.ts +51 -0
  353. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -0
  354. package/dist/domains/comet-native/native-status-discovery.js +299 -0
  355. package/dist/domains/comet-native/native-status-discovery.js.map +1 -0
  356. package/dist/domains/comet-native/native-trajectory-recovery.d.ts.map +1 -1
  357. package/dist/domains/comet-native/native-trajectory-recovery.js +6 -9
  358. package/dist/domains/comet-native/native-trajectory-recovery.js.map +1 -1
  359. package/dist/domains/comet-native/native-transaction.d.ts.map +1 -1
  360. package/dist/domains/comet-native/native-transaction.js +31 -20
  361. package/dist/domains/comet-native/native-transaction.js.map +1 -1
  362. package/dist/domains/comet-native/native-transition-evidence.d.ts.map +1 -1
  363. package/dist/domains/comet-native/native-transition-evidence.js +1 -0
  364. package/dist/domains/comet-native/native-transition-evidence.js.map +1 -1
  365. package/dist/domains/comet-native/native-transition-journal.d.ts.map +1 -1
  366. package/dist/domains/comet-native/native-transition-journal.js +71 -22
  367. package/dist/domains/comet-native/native-transition-journal.js.map +1 -1
  368. package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
  369. package/dist/domains/comet-native/native-transitions.js +167 -15
  370. package/dist/domains/comet-native/native-transitions.js.map +1 -1
  371. package/dist/domains/comet-native/native-types.d.ts +36 -1
  372. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  373. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  374. package/dist/domains/comet-native/native-verification-receipt-runtime.js +18 -100
  375. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  376. package/dist/domains/comet-native/native-verification-report-v2.d.ts +12 -0
  377. package/dist/domains/comet-native/native-verification-report-v2.d.ts.map +1 -0
  378. package/dist/domains/comet-native/native-verification-report-v2.js +141 -0
  379. package/dist/domains/comet-native/native-verification-report-v2.js.map +1 -0
  380. package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
  381. package/dist/domains/comet-native/native-verification-runtime.js +7 -2
  382. package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
  383. package/dist/domains/comet-native/native-verification-scope.d.ts +23 -0
  384. package/dist/domains/comet-native/native-verification-scope.d.ts.map +1 -1
  385. package/dist/domains/comet-native/native-verification-scope.js +106 -19
  386. package/dist/domains/comet-native/native-verification-scope.js.map +1 -1
  387. package/dist/domains/comet-native/native-verifier-protocol.d.ts +49 -0
  388. package/dist/domains/comet-native/native-verifier-protocol.d.ts.map +1 -0
  389. package/dist/domains/comet-native/native-verifier-protocol.js +157 -0
  390. package/dist/domains/comet-native/native-verifier-protocol.js.map +1 -0
  391. package/dist/domains/comet-native/native-workspace-finish.d.ts +61 -0
  392. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -0
  393. package/dist/domains/comet-native/native-workspace-finish.js +332 -0
  394. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -0
  395. package/dist/domains/comet-native/native-workspace-preparation.d.ts +32 -0
  396. package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -0
  397. package/dist/domains/comet-native/native-workspace-preparation.js +265 -0
  398. package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -0
  399. package/dist/domains/comet-native/native-workspace.d.ts +9 -1
  400. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  401. package/dist/domains/comet-native/native-workspace.js +109 -11
  402. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  403. package/dist/domains/dashboard/native-adapter.d.ts +136 -127
  404. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  405. package/dist/domains/dashboard/native-adapter.js +157 -271
  406. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  407. package/dist/domains/dashboard/native-collector.d.ts +4 -4
  408. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  409. package/dist/domains/dashboard/native-collector.js +230 -412
  410. package/dist/domains/dashboard/native-collector.js.map +1 -1
  411. package/dist/domains/dashboard/native-legacy-adapter.d.ts +30 -0
  412. package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -0
  413. package/dist/domains/dashboard/native-legacy-adapter.js +115 -0
  414. package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -0
  415. package/dist/domains/dashboard/web/assets/{arc-ClrSujVb.js → arc-CkuYweSh.js} +1 -1
  416. package/dist/domains/dashboard/web/assets/{architectureDiagram-3BPJPVTR-B4A_t84A.js → architectureDiagram-3BPJPVTR--tTGrKam.js} +1 -1
  417. package/dist/domains/dashboard/web/assets/{blockDiagram-GPEHLZMM-D72u2953.js → blockDiagram-GPEHLZMM-DLKYOixs.js} +1 -1
  418. package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-Ca5zba3N.js → c4Diagram-AAUBKEIU-BL17BIb8.js} +1 -1
  419. package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +1 -0
  420. package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-CCVPBm0J.js → chunk-2J33WTMH-B_DDS2IK.js} +1 -1
  421. package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-JYluRsP-.js → chunk-4BX2VUAB-vQyyh3eG.js} +1 -1
  422. package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-DfYm7pN7.js → chunk-55IACEB6-Cug8J1Qa.js} +1 -1
  423. package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-CwghIMO9.js → chunk-727SXJPM-pMreYMW7.js} +1 -1
  424. package/dist/domains/dashboard/web/assets/{chunk-AQP2D5EJ-BA_zgMXZ.js → chunk-AQP2D5EJ-BUkV_rb7.js} +1 -1
  425. package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-BAJLB5V6.js → chunk-FMBD7UC4-CQXqBSqQ.js} +1 -1
  426. package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-Bj6HWRwi.js → chunk-ND2GUHAM-XWLMOyd4.js} +1 -1
  427. package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-B1kXfg5N.js → chunk-QZHKN3VN-4drjXzHQ.js} +1 -1
  428. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +1 -0
  429. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +1 -0
  430. package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-BBrkuiAU.js → cose-bilkent-S5V4N54A-IQKP-hgj.js} +1 -1
  431. package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-DlFhgQHt.js → cynefin-VYW2F7L2-CvvRO4J2.js} +1 -1
  432. package/dist/domains/dashboard/web/assets/{dagre-BM42HDAG-B0Bk5oiP.js → dagre-BM42HDAG-DeOQo7bP.js} +1 -1
  433. package/dist/domains/dashboard/web/assets/demo-CeIDHUFJ.js +24 -0
  434. package/dist/domains/dashboard/web/assets/{diagram-2AECGRRQ-tvTUiBA2.js → diagram-2AECGRRQ-IQd_jQwB.js} +1 -1
  435. package/dist/domains/dashboard/web/assets/{diagram-5GNKFQAL-BZfcK29q.js → diagram-5GNKFQAL-Dllkdt0m.js} +1 -1
  436. package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-BQahyP-C.js → diagram-KO2AKTUF-CN_LYqvT.js} +1 -1
  437. package/dist/domains/dashboard/web/assets/{diagram-LMA3HP47-D5bJnW2C.js → diagram-LMA3HP47-DK36WkNN.js} +1 -1
  438. package/dist/domains/dashboard/web/assets/{diagram-OG6HWLK6-DTwWdzWJ.js → diagram-OG6HWLK6-iqUnMYEh.js} +1 -1
  439. package/dist/domains/dashboard/web/assets/{erDiagram-TEJ5UH35-BbvrdCp9.js → erDiagram-TEJ5UH35-Bc64lzy8.js} +1 -1
  440. package/dist/domains/dashboard/web/assets/{flowDiagram-I6XJVG4X-DgbR7Tcc.js → flowDiagram-I6XJVG4X-UfOqef9j.js} +1 -1
  441. package/dist/domains/dashboard/web/assets/{ganttDiagram-6RSMTGT7-wWMOA7F4.js → ganttDiagram-6RSMTGT7-D-u6Aauc.js} +1 -1
  442. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-DCxvMAUJ.js → gitGraphDiagram-PVQCEYII-CaWEk3PM.js} +1 -1
  443. package/dist/domains/dashboard/web/assets/index-BFwKBVTJ.css +1 -0
  444. package/dist/domains/dashboard/web/assets/{index-Blit0P5Z.js → index-BNyOfAhu.js} +1 -1
  445. package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +257 -0
  446. package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-9qXEkzDe.js → infoDiagram-5YYISTIA-BK07mNG0.js} +1 -1
  447. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-Dkf5othW.js → ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js} +1 -1
  448. package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-C2_IkO4s.js → journeyDiagram-JHISSGLW-BPy-P7xx.js} +1 -1
  449. package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-BxWgu4DL.js → kanban-definition-UN3LZRKU-3Jq9c_lo.js} +1 -1
  450. package/dist/domains/dashboard/web/assets/{linear-Dkr6p-Ro.js → linear-kQyEW-4G.js} +1 -1
  451. package/dist/domains/dashboard/web/assets/{mermaid.core-DZUcsoG4.js → mermaid.core-COBBjtVH.js} +4 -4
  452. package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-C9xyxGfa.js → mindmap-definition-RKZ34NQL-CyyurUpv.js} +1 -1
  453. package/dist/domains/dashboard/web/assets/{pieDiagram-4H26LBE5-Dn67tdOF.js → pieDiagram-4H26LBE5-CJro_XKk.js} +1 -1
  454. package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-Cy6iOcxc.js → quadrantDiagram-W4KKPZXB-CpayUMjH.js} +1 -1
  455. package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-B_gZONhx.js → requirementDiagram-4Y6WPE33-Bi8YpfnA.js} +1 -1
  456. package/dist/domains/dashboard/web/assets/{sankeyDiagram-5OEKKPKP-C3u-4dOk.js → sankeyDiagram-5OEKKPKP-Wx60WwHe.js} +1 -1
  457. package/dist/domains/dashboard/web/assets/{sequenceDiagram-3UESZ5HK-Xd3ByTVF.js → sequenceDiagram-3UESZ5HK-BiMsRFbc.js} +1 -1
  458. package/dist/domains/dashboard/web/assets/{stateDiagram-AJRCARHV-CJGHL7Up.js → stateDiagram-AJRCARHV-BrURMY0R.js} +1 -1
  459. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +1 -0
  460. package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-DvONX2YQ.js → timeline-definition-PNZ67QCA-aHrrtV-b.js} +1 -1
  461. package/dist/domains/dashboard/web/assets/{vennDiagram-CIIHVFJN-B-L4qWy4.js → vennDiagram-CIIHVFJN-DGB16bvR.js} +1 -1
  462. package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-cf39WX2o.js → wardleyDiagram-YWT4CUSO-RVQbcySh.js} +1 -1
  463. package/dist/domains/dashboard/web/assets/{xychartDiagram-2RQKCTM6-Dk1vcm3u.js → xychartDiagram-2RQKCTM6-DMzzwDVX.js} +1 -1
  464. package/dist/domains/dashboard/web/index.html +16 -16
  465. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  466. package/dist/domains/skill/platform-inspect.js +11 -3
  467. package/dist/domains/skill/platform-inspect.js.map +1 -1
  468. package/dist/domains/skill/platform-install.d.ts +7 -1
  469. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  470. package/dist/domains/skill/platform-install.js +114 -33
  471. package/dist/domains/skill/platform-install.js.map +1 -1
  472. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  473. package/dist/domains/skill/uninstall.js +69 -15
  474. package/dist/domains/skill/uninstall.js.map +1 -1
  475. package/dist/domains/workflow-contract/index.d.ts +1 -0
  476. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  477. package/dist/domains/workflow-contract/index.js +1 -0
  478. package/dist/domains/workflow-contract/index.js.map +1 -1
  479. package/dist/domains/workflow-contract/project-config.d.ts +2 -0
  480. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  481. package/dist/domains/workflow-contract/project-config.js +77 -17
  482. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  483. package/dist/domains/workflow-contract/project-gitignore.d.ts +9 -0
  484. package/dist/domains/workflow-contract/project-gitignore.d.ts.map +1 -0
  485. package/dist/domains/workflow-contract/project-gitignore.js +108 -0
  486. package/dist/domains/workflow-contract/project-gitignore.js.map +1 -0
  487. package/dist/platform/install/platforms.d.ts +3 -1
  488. package/dist/platform/install/platforms.d.ts.map +1 -1
  489. package/dist/platform/install/platforms.js +9 -0
  490. package/dist/platform/install/platforms.js.map +1 -1
  491. package/dist/platform/paths/git-worktree.d.ts +2 -1
  492. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  493. package/dist/platform/paths/git-worktree.js +14 -1
  494. package/dist/platform/paths/git-worktree.js.map +1 -1
  495. package/dist/platform/process/external-command.d.ts +13 -0
  496. package/dist/platform/process/external-command.d.ts.map +1 -0
  497. package/dist/platform/process/external-command.js +45 -0
  498. package/dist/platform/process/external-command.js.map +1 -0
  499. package/dist/platform/process/git.d.ts +12 -0
  500. package/dist/platform/process/git.d.ts.map +1 -0
  501. package/dist/platform/process/git.js +86 -0
  502. package/dist/platform/process/git.js.map +1 -0
  503. package/dist/platform/process/spawn-command.d.ts +8 -0
  504. package/dist/platform/process/spawn-command.d.ts.map +1 -0
  505. package/dist/platform/process/spawn-command.js +113 -0
  506. package/dist/platform/process/spawn-command.js.map +1 -0
  507. package/eval/local/tasks/comet-native-clarification/validation/test_native_clarification.py +9 -21
  508. package/eval/local/tasks/comet-native-clarification-depth/validation/test_native_clarification_depth.py +4 -7
  509. package/eval/local/tasks/comet-native-clarification-modes/validation/test_native_clarification_modes.py +4 -10
  510. package/eval/local/tasks/comet-native-interrupted-transition/instruction.md +1 -1
  511. package/eval/local/tasks/comet-native-interrupted-transition/validation/test_native_interrupted_transition.py +15 -16
  512. package/eval/local/tasks/comet-native-repository-fact/instruction.md +2 -2
  513. package/eval/local/tasks/comet-native-repository-fact/validation/test_native_repository_fact.py +8 -2
  514. package/eval/local/tasks/comet-native-wave-b-decision-resume/instruction.md +8 -4
  515. package/eval/local/tasks/comet-native-wave-b-decision-resume/task.toml +6 -6
  516. package/eval/local/tasks/comet-native-wave-b-decision-resume/validation/test_native_wave_b_decision_resume.py +126 -135
  517. package/eval/local/tasks/comet-native-wave-c-verification-integrity/instruction.md +6 -6
  518. package/eval/local/tasks/comet-native-wave-c-verification-integrity/task.toml +8 -8
  519. package/eval/local/tasks/comet-native-wave-c-verification-integrity/validation/test_native_wave_c_verification_integrity.py +97 -317
  520. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +7 -7
  521. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +4 -4
  522. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +130 -199
  523. package/eval/local/tasks/comet-native-wave-e-parallel-safety/instruction.md +5 -5
  524. package/eval/local/tasks/comet-native-wave-e-parallel-safety/task.toml +8 -8
  525. package/eval/local/tasks/comet-native-wave-e-parallel-safety/validation/test_native_wave_e_parallel_safety.py +135 -239
  526. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/instruction.md +3 -3
  527. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/task.toml +6 -6
  528. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/validation/test_native_wave_f_dashboard_readonly.py +81 -439
  529. package/eval/local/tasks/comet-native-workflow/instruction.md +5 -4
  530. package/eval/local/tasks/comet-native-workflow/validation/test_native_workflow.py +145 -502
  531. package/eval/local/tasks/index.yaml +5 -5
  532. package/eval/local/tests/scaffold/test_native_aligned_eval.py +146 -35
  533. package/eval/local/tests/scaffold/test_native_wave_evaluations.py +75 -2054
  534. package/eval/local/tests/scaffold/test_tasks.py +38 -52
  535. package/eval/local/tests/tasks/test_tasks.py +3 -3
  536. package/eval/local/treatments/comet/comet_native_phase1.yaml +7 -4
  537. package/eval/pyproject.toml +4 -4
  538. package/eval/scaffold/python/native_eval.py +10 -5
  539. package/eval/scaffold/python/validation/native_v4.py +249 -0
  540. package/eval/scaffold/python/validation/native_wave.py +4 -5
  541. package/eval/scaffold/python/validation/native_workflow.py +193 -97
  542. package/eval/scaffold/python/validation/rubric.py +114 -1
  543. package/package.json +2 -1
  544. package/assets/skills/comet-native/scripts/comet-native-check.mjs +0 -179
  545. package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +0 -179
  546. package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +0 -151
  547. package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +0 -187
  548. package/dist/domains/comet-native/native-check-entry.d.ts +0 -2
  549. package/dist/domains/comet-native/native-check-entry.d.ts.map +0 -1
  550. package/dist/domains/comet-native/native-check-entry.js +0 -4
  551. package/dist/domains/comet-native/native-check-entry.js.map +0 -1
  552. package/dist/domains/comet-native/native-checkpoint-entry.d.ts +0 -2
  553. package/dist/domains/comet-native/native-checkpoint-entry.d.ts.map +0 -1
  554. package/dist/domains/comet-native/native-checkpoint-entry.js +0 -4
  555. package/dist/domains/comet-native/native-checkpoint-entry.js.map +0 -1
  556. package/dist/domains/comet-native/native-evidence-entry.d.ts +0 -2
  557. package/dist/domains/comet-native/native-evidence-entry.d.ts.map +0 -1
  558. package/dist/domains/comet-native/native-evidence-entry.js +0 -4
  559. package/dist/domains/comet-native/native-evidence-entry.js.map +0 -1
  560. package/dist/domains/comet-native/native-receipt-entry.d.ts +0 -2
  561. package/dist/domains/comet-native/native-receipt-entry.d.ts.map +0 -1
  562. package/dist/domains/comet-native/native-receipt-entry.js +0 -4
  563. package/dist/domains/comet-native/native-receipt-entry.js.map +0 -1
  564. package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +0 -1
  565. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-BpA7BPgX.js +0 -1
  566. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-BpA7BPgX.js +0 -1
  567. package/dist/domains/dashboard/web/assets/demo-DZYPLZpF.js +0 -25
  568. package/dist/domains/dashboard/web/assets/index-Bk1o-4VO.css +0 -1
  569. package/dist/domains/dashboard/web/assets/index-g8vyW0R_.js +0 -257
  570. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +0 -1
  571. /package/assets/skills/{comet → comet-classic}/reference/classic-layout.md +0 -0
  572. /package/assets/skills-zh/{comet → comet-classic}/reference/classic-layout.md +0 -0
@@ -1,184 +1,216 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var aw=Object.create;var Uu=Object.defineProperty;var ow=Object.getOwnPropertyDescriptor;var sw=Object.getOwnPropertyNames;var cw=Object.getPrototypeOf,lw=Object.prototype.hasOwnProperty;var Jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var uw=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of sw(t))!lw.call(e,r)&&r!==i&&Uu(e,r,{get:()=>t[r],enumerable:!(n=ow(t,r))||n.enumerable});return e};var as=(e,t,i)=>(i=e!=null?aw(cw(e)):{},uw(t||!e||!e.__esModule?Uu(i,"default",{value:e,enumerable:!0}):i,e));var F=R(fe=>{"use strict";var cs=Symbol.for("yaml.alias"),ef=Symbol.for("yaml.document"),Gr=Symbol.for("yaml.map"),tf=Symbol.for("yaml.pair"),ls=Symbol.for("yaml.scalar"),Ur=Symbol.for("yaml.seq"),pt=Symbol.for("yaml.node.type"),pw=e=>!!e&&typeof e=="object"&&e[pt]===cs,mw=e=>!!e&&typeof e=="object"&&e[pt]===ef,vw=e=>!!e&&typeof e=="object"&&e[pt]===Gr,gw=e=>!!e&&typeof e=="object"&&e[pt]===tf,nf=e=>!!e&&typeof e=="object"&&e[pt]===ls,ww=e=>!!e&&typeof e=="object"&&e[pt]===Ur;function rf(e){if(e&&typeof e=="object")switch(e[pt]){case Gr:case Ur:return!0}return!1}function yw(e){if(e&&typeof e=="object")switch(e[pt]){case cs:case Gr:case ls:case Ur:return!0}return!1}var Nw=e=>(nf(e)||rf(e))&&!!e.anchor;fe.ALIAS=cs;fe.DOC=ef;fe.MAP=Gr;fe.NODE_TYPE=pt;fe.PAIR=tf;fe.SCALAR=ls;fe.SEQ=Ur;fe.hasAnchor=Nw;fe.isAlias=pw;fe.isCollection=rf;fe.isDocument=mw;fe.isMap=vw;fe.isNode=yw;fe.isPair=gw;fe.isScalar=nf;fe.isSeq=ww});var Nn=R(us=>{"use strict";var ce=F(),Ce=Symbol("break visit"),af=Symbol("skip children"),rt=Symbol("remove node");function Kr(e,t){let i=of(t);ce.isDocument(e)?Ii(null,e.contents,i,Object.freeze([e]))===rt&&(e.contents=null):Ii(null,e,i,Object.freeze([]))}Kr.BREAK=Ce;Kr.SKIP=af;Kr.REMOVE=rt;function Ii(e,t,i,n){let r=sf(e,t,i,n);if(ce.isNode(r)||ce.isPair(r))return cf(e,n,r),Ii(e,r,i,n);if(typeof r!="symbol"){if(ce.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=Ii(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===Ce)return Ce;o===rt&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){n=Object.freeze(n.concat(t));let a=Ii("key",t.key,i,n);if(a===Ce)return Ce;a===rt&&(t.key=null);let o=Ii("value",t.value,i,n);if(o===Ce)return Ce;o===rt&&(t.value=null)}}return r}async function Yr(e,t){let i=of(t);ce.isDocument(e)?await _i(null,e.contents,i,Object.freeze([e]))===rt&&(e.contents=null):await _i(null,e,i,Object.freeze([]))}Yr.BREAK=Ce;Yr.SKIP=af;Yr.REMOVE=rt;async function _i(e,t,i,n){let r=await sf(e,t,i,n);if(ce.isNode(r)||ce.isPair(r))return cf(e,n,r),_i(e,r,i,n);if(typeof r!="symbol"){if(ce.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await _i(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===Ce)return Ce;o===rt&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){n=Object.freeze(n.concat(t));let a=await _i("key",t.key,i,n);if(a===Ce)return Ce;a===rt&&(t.key=null);let o=await _i("value",t.value,i,n);if(o===Ce)return Ce;o===rt&&(t.value=null)}}return r}function of(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 sf(e,t,i,n){if(typeof i=="function")return i(e,t,n);if(ce.isMap(t))return i.Map?.(e,t,n);if(ce.isSeq(t))return i.Seq?.(e,t,n);if(ce.isPair(t))return i.Pair?.(e,t,n);if(ce.isScalar(t))return i.Scalar?.(e,t,n);if(ce.isAlias(t))return i.Alias?.(e,t,n)}function cf(e,t,i){let n=t[t.length-1];if(ce.isCollection(n))n.items[e]=i;else if(ce.isPair(n))e==="key"?n.key=i:n.value=i;else if(ce.isDocument(n))n.contents=i;else{let r=ce.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}us.visit=Kr;us.visitAsync=Yr});var fs=R(uf=>{"use strict";var lf=F(),bw=Nn(),kw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Sw=e=>e.replace(/[!,[\]{}]/g,t=>kw[t]),bn=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}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,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${r}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,n,r]=t.match(/^(.*!)([^!]*)$/s);r||i(`The ${t} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(r)}catch(o){return i(String(o)),null}return n==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,n]of Object.entries(this.tags))if(t.startsWith(n))return i+Sw(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),r;if(t&&n.length>0&&lf.isNode(t.contents)){let a={};bw.visit(t.contents,(o,s)=>{lf.isNode(s)&&s.tag&&(a[s.tag]=!0)}),r=Object.keys(a)}else r=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||r.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
- `)}};bn.defaultYaml={explicit:!1,version:"1.2"};bn.defaultTags={"!!":"tag:yaml.org,2002:"};uf.Directives=bn});var Xr=R(kn=>{"use strict";var ff=F(),Ew=Nn();function Cw(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function df(e){let t=new Set;return Ew.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function hf(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function Rw(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=df(e));let o=hf(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(ff.isScalar(o.node)||ff.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:n}}kn.anchorIsValid=Cw;kn.anchorNames=df;kn.createNodeAnchors=Rw;kn.findNewAnchor=hf});var ds=R(pf=>{"use strict";function Sn(e,t,i,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,a=n.length;r<a;++r){let o=n[r],s=Sn(e,n,String(r),o);s===void 0?delete n[r]:s!==o&&(n[r]=s)}else if(n instanceof Map)for(let r of Array.from(n.keys())){let a=n.get(r),o=Sn(e,n,r,a);o===void 0?n.delete(r):o!==a&&n.set(r,o)}else if(n instanceof Set)for(let r of Array.from(n)){let a=Sn(e,n,r,r);a===void 0?n.delete(r):a!==r&&(n.delete(r),n.add(a))}else for(let[r,a]of Object.entries(n)){let o=Sn(e,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return e.call(t,i,n)}pf.applyReviver=Sn});var _t=R(vf=>{"use strict";var Pw=F();function mf(e,t,i){if(Array.isArray(e))return e.map((n,r)=>mf(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!Pw.hasAnchor(e))return e.toJSON(t,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=e.toJSON(t,i);return i.onCreate&&i.onCreate(r),r}return typeof e=="bigint"&&!i?.keep?Number(e):e}vf.toJS=mf});var Qr=R(wf=>{"use strict";var Aw=ds(),gf=F(),xw=_t(),hs=class{constructor(t){Object.defineProperty(this,gf.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:i,maxAliasCount:n,onAnchor:r,reviver:a}={}){if(!gf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=xw.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?Aw.applyReviver(a,{"":s},"",s):s}};wf.NodeBase=hs});var En=R(yf=>{"use strict";var Tw=Xr(),Iw=Nn(),Oi=F(),_w=Qr(),Ow=_t(),ps=class extends _w.NodeBase{constructor(t){super(Oi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;i?.aliasResolveCache?n=i.aliasResolveCache:(n=[],Iw.visit(t,{Node:(a,o)=>{(Oi.isAlias(o)||Oi.hasAnchor(o))&&n.push(o)}}),i&&(i.aliasResolveCache=n));let r;for(let a of n){if(a===this)break;a.anchor===this.source&&(r=a)}return r}toJSON(t,i){if(!i)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:a}=i,o=this.resolve(r,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(Ow.toJS(o,null,i),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Zr(r,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,n){let r=`*${this.source}`;if(t){if(Tw.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`${r} `}return r}};function Zr(e,t,i){if(Oi.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(Oi.isCollection(t)){let n=0;for(let r of t.items){let a=Zr(e,r,i);a>n&&(n=a)}return n}else if(Oi.isPair(t)){let n=Zr(e,t.key,i),r=Zr(e,t.value,i);return Math.max(n,r)}return 1}yf.Alias=ps});var ne=R(ms=>{"use strict";var jw=F(),$w=Qr(),Hw=_t(),Fw=e=>!e||typeof e!="function"&&typeof e!="object",Ot=class extends $w.NodeBase{constructor(t){super(jw.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Hw.toJS(this.value,t,i)}toString(){return String(this.value)}};Ot.BLOCK_FOLDED="BLOCK_FOLDED";Ot.BLOCK_LITERAL="BLOCK_LITERAL";Ot.PLAIN="PLAIN";Ot.QUOTE_DOUBLE="QUOTE_DOUBLE";Ot.QUOTE_SINGLE="QUOTE_SINGLE";ms.Scalar=Ot;ms.isScalarValue=Fw});var Cn=R(bf=>{"use strict";var Lw=En(),oi=F(),Nf=ne(),Mw="tag:yaml.org,2002:";function Dw(e,t,i){if(t){let n=i.filter(a=>a.tag===t),r=n.find(a=>!a.format)??n[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return i.find(n=>n.identify?.(e)&&!n.format)}function Bw(e,t,i){if(oi.isDocument(e)&&(e=e.contents),oi.isNode(e))return e;if(oi.isPair(e)){let f=i.schema[oi.MAP].createNode?.(i.schema,null,i);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:r,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=r(e)),new Lw.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Mw+t.slice(2));let l=Dw(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new Nf.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?o[oi.MAP]:Symbol.iterator in Object(e)?o[oi.SEQ]:o[oi.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Nf.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}bf.createNode=Bw});var ta=R(ea=>{"use strict";var qw=Cn(),at=F(),Vw=Qr();function vs(e,t,i){let n=i;for(let r=t.length-1;r>=0;--r){let a=t[r];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return qw.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var kf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,gs=class extends Vw.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(n=>at.isNode(n)||at.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(kf(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(at.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,vs(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(t){let[i,...n]=t;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(at.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(t,i){let[n,...r]=t,a=this.get(n,!0);return r.length===0?!i&&at.isScalar(a)?a.value:a:at.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!at.isPair(i))return!1;let n=i.value;return n==null||t&&at.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[i,...n]=t;if(n.length===0)return this.has(i);let r=this.get(i,!0);return at.isCollection(r)?r.hasIn(n):!1}setIn(t,i){let[n,...r]=t;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(at.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,vs(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};ea.Collection=gs;ea.collectionFromPath=vs;ea.isEmptyPath=kf});var Rn=R(ia=>{"use strict";var Ww=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ws(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var zw=(e,t,i)=>e.endsWith(`
6
- `)?ws(i,t):i.includes(`
4
+ var Ff=Object.create;var nc=Object.defineProperty;var Mf=Object.getOwnPropertyDescriptor;var Vf=Object.getOwnPropertyNames;var qf=Object.getPrototypeOf,Wf=Object.prototype.hasOwnProperty;var dr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var zf=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vf(t))!Wf.call(e,n)&&n!==i&&nc(e,n,{get:()=>t[n],enumerable:!(r=Mf(t,n))||r.enumerable});return e};var fr=(e,t,i)=>(i=e!=null?Ff(qf(e)):{},zf(t||!e||!e.__esModule?nc(i,"default",{value:e,enumerable:!0}):i,e));var P=y(M=>{"use strict";var ua=Symbol.for("yaml.alias"),cc=Symbol.for("yaml.document"),mr=Symbol.for("yaml.map"),lc=Symbol.for("yaml.pair"),da=Symbol.for("yaml.scalar"),vr=Symbol.for("yaml.seq"),Ie=Symbol.for("yaml.node.type"),ch=e=>!!e&&typeof e=="object"&&e[Ie]===ua,lh=e=>!!e&&typeof e=="object"&&e[Ie]===cc,uh=e=>!!e&&typeof e=="object"&&e[Ie]===mr,dh=e=>!!e&&typeof e=="object"&&e[Ie]===lc,uc=e=>!!e&&typeof e=="object"&&e[Ie]===da,fh=e=>!!e&&typeof e=="object"&&e[Ie]===vr;function dc(e){if(e&&typeof e=="object")switch(e[Ie]){case mr:case vr:return!0}return!1}function hh(e){if(e&&typeof e=="object")switch(e[Ie]){case ua:case mr:case da:case vr:return!0}return!1}var ph=e=>(uc(e)||dc(e))&&!!e.anchor;M.ALIAS=ua;M.DOC=cc;M.MAP=mr;M.NODE_TYPE=Ie;M.PAIR=lc;M.SCALAR=da;M.SEQ=vr;M.hasAnchor=ph;M.isAlias=ch;M.isCollection=dc;M.isDocument=lh;M.isMap=uh;M.isNode=hh;M.isPair=dh;M.isScalar=uc;M.isSeq=fh});var ri=y(fa=>{"use strict";var H=P(),X=Symbol("break visit"),fc=Symbol("skip children"),ke=Symbol("remove node");function gr(e,t){let i=hc(t);H.isDocument(e)?Et(null,e.contents,i,Object.freeze([e]))===ke&&(e.contents=null):Et(null,e,i,Object.freeze([]))}gr.BREAK=X;gr.SKIP=fc;gr.REMOVE=ke;function Et(e,t,i,r){let n=pc(e,t,i,r);if(H.isNode(n)||H.isPair(n))return mc(e,r,n),Et(e,n,i,r);if(typeof n!="symbol"){if(H.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Et(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===ke&&(t.items.splice(a,1),a-=1)}}}else if(H.isPair(t)){r=Object.freeze(r.concat(t));let a=Et("key",t.key,i,r);if(a===X)return X;a===ke&&(t.key=null);let o=Et("value",t.value,i,r);if(o===X)return X;o===ke&&(t.value=null)}}return n}async function wr(e,t){let i=hc(t);H.isDocument(e)?await Pt(null,e.contents,i,Object.freeze([e]))===ke&&(e.contents=null):await Pt(null,e,i,Object.freeze([]))}wr.BREAK=X;wr.SKIP=fc;wr.REMOVE=ke;async function Pt(e,t,i,r){let n=await pc(e,t,i,r);if(H.isNode(n)||H.isPair(n))return mc(e,r,n),Pt(e,n,i,r);if(typeof n!="symbol"){if(H.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Pt(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===ke&&(t.items.splice(a,1),a-=1)}}}else if(H.isPair(t)){r=Object.freeze(r.concat(t));let a=await Pt("key",t.key,i,r);if(a===X)return X;a===ke&&(t.key=null);let o=await Pt("value",t.value,i,r);if(o===X)return X;o===ke&&(t.value=null)}}return n}function hc(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 pc(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(H.isMap(t))return i.Map?.(e,t,r);if(H.isSeq(t))return i.Seq?.(e,t,r);if(H.isPair(t))return i.Pair?.(e,t,r);if(H.isScalar(t))return i.Scalar?.(e,t,r);if(H.isAlias(t))return i.Alias?.(e,t,r)}function mc(e,t,i){let r=t[t.length-1];if(H.isCollection(r))r.items[e]=i;else if(H.isPair(r))e==="key"?r.key=i:r.value=i;else if(H.isDocument(r))r.contents=i;else{let n=H.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}fa.visit=gr;fa.visitAsync=wr});var ha=y(gc=>{"use strict";var vc=P(),mh=ri(),vh={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},gh=e=>e.replace(/[!,[\]{}]/g,t=>vh[t]),ni=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}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,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+gh(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&vc.isNode(t.contents)){let a={};mh.visit(t.contents,(o,s)=>{vc.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
+ `)}};ni.defaultYaml={explicit:!1,version:"1.2"};ni.defaultTags={"!!":"tag:yaml.org,2002:"};gc.Directives=ni});var yr=y(ai=>{"use strict";var wc=P(),wh=ri();function yh(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function yc(e){let t=new Set;return wh.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Nc(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function Nh(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=yc(e));let o=Nc(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(wc.isScalar(o.node)||wc.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:r}}ai.anchorIsValid=yh;ai.anchorNames=yc;ai.createNodeAnchors=Nh;ai.findNewAnchor=Nc});var pa=y(bc=>{"use strict";function oi(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=oi(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=oi(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=oi(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=oi(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}bc.applyReviver=oi});var Ve=y(Sc=>{"use strict";var bh=P();function kc(e,t,i){if(Array.isArray(e))return e.map((r,n)=>kc(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!bh.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Sc.toJS=kc});var Nr=y(Pc=>{"use strict";var kh=pa(),Ec=P(),Sh=Ve(),ma=class{constructor(t){Object.defineProperty(this,Ec.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:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Ec.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=Sh.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?kh.applyReviver(a,{"":s},"",s):s}};Pc.NodeBase=ma});var si=y(xc=>{"use strict";var Eh=yr(),Ph=ri(),xt=P(),xh=Nr(),Rh=Ve(),va=class extends xh.NodeBase{constructor(t){super(xt.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],Ph.visit(t,{Node:(a,o)=>{(xt.isAlias(o)||xt.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(Rh.toJS(o,null,i),s=r.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=br(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(Eh.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 br(e,t,i){if(xt.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(xt.isCollection(t)){let r=0;for(let n of t.items){let a=br(e,n,i);a>r&&(r=a)}return r}else if(xt.isPair(t)){let r=br(e,t.key,i),n=br(e,t.value,i);return Math.max(r,n)}return 1}xc.Alias=va});var I=y(ga=>{"use strict";var Ch=P(),Ah=Nr(),_h=Ve(),Th=e=>!e||typeof e!="function"&&typeof e!="object",qe=class extends Ah.NodeBase{constructor(t){super(Ch.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:_h.toJS(this.value,t,i)}toString(){return String(this.value)}};qe.BLOCK_FOLDED="BLOCK_FOLDED";qe.BLOCK_LITERAL="BLOCK_LITERAL";qe.PLAIN="PLAIN";qe.QUOTE_DOUBLE="QUOTE_DOUBLE";qe.QUOTE_SINGLE="QUOTE_SINGLE";ga.Scalar=qe;ga.isScalarValue=Th});var ci=y(Cc=>{"use strict";var Ih=si(),nt=P(),Rc=I(),jh="tag:yaml.org,2002:";function $h(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function Oh(e,t,i){if(nt.isDocument(e)&&(e=e.contents),nt.isNode(e))return e;if(nt.isPair(e)){let f=i.schema[nt.MAP].createNode?.(i.schema,null,i);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Ih.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=jh+t.slice(2));let l=$h(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new Rc.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?o[nt.MAP]:Symbol.iterator in Object(e)?o[nt.SEQ]:o[nt.MAP]}a&&(a(l),delete i.onTagObj);let d=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new Rc.Scalar(e);return t?d.tag=t:l.default||(d.tag=l.tag),c&&(c.node=d),d}Cc.createNode=Oh});var Sr=y(kr=>{"use strict";var Hh=ci(),Se=P(),Dh=Nr();function wa(e,t,i){let r=i;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]=r,r=o}else r=new Map([[a,r]])}return Hh.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Ac=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ya=class extends Dh.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>Se.isNode(r)||Se.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Ac(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(Se.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,wa(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(Se.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&Se.isScalar(a)?a.value:a:Se.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Se.isPair(i))return!1;let r=i.value;return r==null||t&&Se.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return Se.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(Se.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,wa(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};kr.Collection=ya;kr.collectionFromPath=wa;kr.isEmptyPath=Ac});var li=y(Er=>{"use strict";var Bh=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Na(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Lh=(e,t,i)=>e.endsWith(`
6
+ `)?Na(i,t):i.includes(`
7
7
  `)?`
8
- `+ws(i,t):(e.endsWith(" ")?"":" ")+i;ia.indentComment=ws;ia.lineComment=zw;ia.stringifyComment=Ww});var Ef=R(Pn=>{"use strict";var Jw="flow",ys="block",na="quoted";function Gw(e,t,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return e;r<a&&(a=0);let c=Math.max(1+a,1+r-t.length);if(e.length<=c)return e;let l=[],u={},f=r-t.length;typeof n=="number"&&(n>r-Math.max(2,a)?l.push(0):f=r-n);let d,p,m=!1,h=-1,v=-1,w=-1;i===ys&&(h=Sf(e,h,t.length),h!==-1&&(f=h+c));for(let b;b=e[h+=1];){if(i===na&&b==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===`
9
- `)i===ys&&(h=Sf(e,h,t.length)),f=h+t.length+c,d=void 0;else{if(b===" "&&p&&p!==" "&&p!==`
10
- `&&p!==" "){let N=e[h+1];N&&N!==" "&&N!==`
11
- `&&N!==" "&&(d=h)}if(h>=f)if(d)l.push(d),f=d+c,d=void 0;else if(i===na){for(;p===" "||p===" ";)p=b,b=e[h+=1],m=!0;let N=h>w+1?h-2:v-1;if(u[N])return e;l.push(N),u[N]=!0,f=N+c,d=void 0}else m=!0}p=b}if(m&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let b=0;b<l.length;++b){let N=l[b],E=l[b+1]||e.length;N===0?y=`
12
- ${t}${e.slice(0,E)}`:(i===na&&u[N]&&(y+=`${e[N]}\\`),y+=`
13
- ${t}${e.slice(N+1,E)}`)}return y}function Sf(e,t,i){let n=t,r=t+1,a=e[r];for(;a===" "||a===" ";)if(t<r+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);n=t,r=t+1,a=e[r]}return n}Pn.FOLD_BLOCK=ys;Pn.FOLD_FLOW=Jw;Pn.FOLD_QUOTED=na;Pn.foldFlowLines=Gw});var xn=R(Cf=>{"use strict";var ze=ne(),jt=Ef(),aa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),oa=e=>/^(%|---|\.\.\.)/m.test(e);function Uw(e,t,i){if(!t||t<0)return!1;let n=t-i,r=e.length;if(r<=n)return!1;for(let a=0,o=0;a<r;++a)if(e[a]===`
15
- `){if(a-o>n)return!0;if(o=a+1,r-o<=n)return!1}return!0}function An(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(oa(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.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+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||i[c+2]==='"'||i.length<r)c+=1;else{for(o+=i.slice(s,c)+`
8
+ `+Na(i,t):(e.endsWith(" ")?"":" ")+i;Er.indentComment=Na;Er.lineComment=Lh;Er.stringifyComment=Bh});var Tc=y(ui=>{"use strict";var Fh="flow",ba="block",Pr="quoted";function Mh(e,t,i="flow",{indentAtStart:r,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=[],d={},f=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):f=n-r);let u,p,v=!1,h=-1,m=-1,g=-1;i===ba&&(h=_c(e,h,t.length),h!==-1&&(f=h+c));for(let w;w=e[h+=1];){if(i===Pr&&w==="\\"){switch(m=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(w===`
9
+ `)i===ba&&(h=_c(e,h,t.length)),f=h+t.length+c,u=void 0;else{if(w===" "&&p&&p!==" "&&p!==`
10
+ `&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==`
11
+ `&&k!==" "&&(u=h)}if(h>=f)if(u)l.push(u),f=u+c,u=void 0;else if(i===Pr){for(;p===" "||p===" ";)p=w,w=e[h+=1],v=!0;let k=h>g+1?h-2:m-1;if(d[k])return e;l.push(k),d[k]=!0,f=k+c,u=void 0}else v=!0}p=w}if(v&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let w=0;w<l.length;++w){let k=l[w],S=l[w+1]||e.length;k===0?N=`
12
+ ${t}${e.slice(0,S)}`:(i===Pr&&d[k]&&(N+=`${e[k]}\\`),N+=`
13
+ ${t}${e.slice(k+1,S)}`)}return N}function _c(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);r=t,n=t+1,a=e[n]}return r}ui.FOLD_BLOCK=ba;ui.FOLD_FLOW=Fh;ui.FOLD_QUOTED=Pr;ui.foldFlowLines=Mh});var fi=y(Ic=>{"use strict";var pe=I(),We=Tc(),Rr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Cr=e=>/^(%|---|\.\.\.)/m.test(e);function Vh(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function di(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Cr(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let d=i.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
16
16
 
17
17
  `;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,n?o:jt.foldFlowLines(o,a,jt.FOLD_QUOTED,aa(t,!1))}function Ns(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return An(e,t);let i=t.indent||(oa(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?n:jt.foldFlowLines(n,i,jt.FOLD_FLOW,aa(t,!1))}function ji(e,t){let{singleQuote:i}=t.options,n;if(i===!1)n=An;else{let r=e.includes('"'),a=e.includes("'");r&&!a?n=Ns:a&&!r?n=An:n=i?Ns:An}return n(e,t)}var bs;try{bs=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:We.foldFlowLines(o,a,We.FOLD_QUOTED,Rr(t,!1))}function ka(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return di(e,t);let i=t.indent||(Cr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?r:We.foldFlowLines(r,i,We.FOLD_FLOW,Rr(t,!1))}function Rt(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=di;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=ka:a&&!n?r=di:r=i?ka:di}return r(e,t)}var Sa;try{Sa=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{bs=/\n+(?!\n|$)/g}function ra({comment:e,type:t,value:i},n,r,a){let{blockQuote:o,commentString:s,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(i))return ji(i,n);let l=n.indent||(n.forceBlockIndent||oa(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===ze.Scalar.BLOCK_FOLDED?!1:t===ze.Scalar.BLOCK_LITERAL?!0:!Uw(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{Sa=/\n+(?!\n|$)/g}function xr({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Rt(i,r);let l=r.indent||(r.forceBlockIndent||Cr(i)?" ":""),d=o==="literal"?!0:o==="folded"||t===pe.Scalar.BLOCK_FOLDED?!1:t===pe.Scalar.BLOCK_LITERAL?!0:!Vh(i,c,l.length);if(!i)return d?`|
24
24
  `:`>
25
- `;let f,d;for(d=i.length;d>0;--d){let E=i[d-1];if(E!==`
26
- `&&E!==" "&&E!==" ")break}let p=i.substring(d),m=p.indexOf(`
27
- `);m===-1?f="-":i===p||m!==p.length-1?(f="+",a&&a()):f="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
28
- `&&(p=p.slice(0,-1)),p=p.replace(bs,`$&${l}`));let h=!1,v,w=-1;for(v=0;v<i.length;++v){let E=i[v];if(E===" ")h=!0;else if(E===`
29
- `)w=v;else break}let y=i.substring(0,w<v?w+1:v);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+f;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let E=i.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,S=aa(n,!0);o!=="folded"&&t!==ze.Scalar.BLOCK_FOLDED&&(S.onOverflow=()=>{g=!0});let k=jt.foldFlowLines(`${y}${E}${p}`,l,jt.FOLD_BLOCK,S);if(!g)return`>${N}
31
- ${l}${k}`}return i=i.replace(/\n+/g,`$&${l}`),`|${N}
32
- ${l}${y}${i}${p}`}function Kw(e,t,i,n){let{type:r,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
- `)||u&&/[[\]{},]/.test(a))return ji(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?ji(a,t):ra(e,t,i,n);if(!s&&!u&&r!==ze.Scalar.PLAIN&&a.includes(`
35
- `))return ra(e,t,i,n);if(oa(a)){if(c==="")return t.forceBlockIndent=!0,ra(e,t,i,n);if(s&&c===l)return ji(a,t)}let f=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:m}=t.doc.schema;if(m.some(d)||p?.some(d))return ji(a,t)}return s?f:jt.foldFlowLines(f,c,jt.FOLD_FLOW,aa(t,!1))}function Yw(e,t,i,n){let{implicitKey:r,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==ze.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ze.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case ze.Scalar.BLOCK_FOLDED:case ze.Scalar.BLOCK_LITERAL:return r||a?ji(o.value,t):ra(o,t,i,n);case ze.Scalar.QUOTE_DOUBLE:return An(o.value,t);case ze.Scalar.QUOTE_SINGLE:return Ns(o.value,t);case ze.Scalar.PLAIN:return Kw(o,t,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=t.options,d=r&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Cf.stringifyString=Yw});var Tn=R(ks=>{"use strict";var Xw=Xr(),$t=F(),Qw=Rn(),Zw=xn();function ey(e,t){let i=Object.assign({blockQuote:!0,commentString:Qw.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(i.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:n,options:i}}function ty(e,t){if(t.tag){let r=e.filter(a=>a.tag===t.tag);if(r.length>0)return r.find(a=>a.format===t.format)??r[0]}let i,n;if($t.isScalar(t)){n=t.value;let r=e.filter(a=>a.identify?.(n));if(r.length>1){let a=r.filter(o=>o.test);a.length>0&&(r=a)}i=r.find(a=>a.format===t.format)??r.find(a=>!a.format)}else n=t,i=e.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!i){let r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return i}function iy(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=($t.isScalar(e)||$t.isCollection(e))&&e.anchor;a&&Xw.anchorIsValid(a)&&(i.add(a),r.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}function ny(e,t,i,n){if($t.isPair(e))return e.toString(t,i,n);if($t.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,a=$t.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=ty(t.doc.schema.tags,a));let o=iy(a,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof r.stringify=="function"?r.stringify(a,t,i,n):$t.isScalar(a)?Zw.stringifyString(a,t,i,n):a.toString(t,i,n);return o?$t.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}ks.createStringifyContext=ey;ks.stringify=ny});var xf=R(Af=>{"use strict";var mt=F(),Rf=ne(),Pf=Tn(),In=Rn();function ry({key:e,value:t},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=i,d=mt.isNode(e)&&e.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(mt.isCollection(e)||!mt.isNode(e)&&typeof e=="object"){let S="With simple keys, collection cannot be used as a key value";throw new Error(S)}}let p=!f&&(!e||d&&t==null&&!i.inFlow||mt.isCollection(e)||(mt.isScalar(e)?e.type===Rf.Scalar.BLOCK_FOLDED||e.type===Rf.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(f||!a),indent:s+c});let m=!1,h=!1,v=Pf.stringify(e,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&v.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return m&&n&&n(),v===""?"?":p?`? ${v}`:v}else if(a&&!f||t==null&&p)return v=`? ${v}`,d&&!m?v+=In.lineComment(v,i.indent,l(d)):h&&r&&r(),v;m&&(d=null),p?(d&&(v+=In.lineComment(v,i.indent,l(d))),v=`? ${v}
38
- ${s}:`):(v=`${v}:`,d&&(v+=In.lineComment(v,i.indent,l(d))));let w,y,b;mt.isNode(t)?(w=!!t.spaceBefore,y=t.commentBefore,b=t.comment):(w=!1,y=null,b=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!d&&mt.isScalar(t)&&(i.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&mt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let N=!1,E=Pf.stringify(t,i,()=>N=!0,()=>h=!0),g=" ";if(d||w||y){if(g=w?`
39
- `:"",y){let S=l(y);g+=`
40
- ${In.indentComment(S,i.indent)}`}E===""&&!i.inFlow?g===`
41
- `&&b&&(g=`
42
-
43
- `):g+=`
44
- ${i.indent}`}else if(!p&&mt.isCollection(t)){let S=E[0],k=E.indexOf(`
45
- `),C=k!==-1,B=i.inFlow??t.flow??t.items.length===0;if(C||!B){let K=!1;if(C&&(S==="&"||S==="!")){let D=E.indexOf(" ");S==="&"&&D!==-1&&D<k&&E[D+1]==="!"&&(D=E.indexOf(" ",D+1)),(D===-1||k<D)&&(K=!0)}K||(g=`
46
- ${i.indent}`)}}else(E===""||E[0]===`
47
- `)&&(g="");return v+=g+E,i.inFlow?N&&n&&n():b&&!N?v+=In.lineComment(v,i.indent,l(b)):h&&r&&r(),v}Af.stringifyPair=ry});var Es=R(Ss=>{"use strict";var Tf=Jr("process");function ay(e,...t){e==="debug"&&console.log(...t)}function oy(e,t){(e==="debug"||e==="warn")&&(typeof Tf.emitWarning=="function"?Tf.emitWarning(t):console.warn(t))}Ss.debug=ay;Ss.warn=oy});var fa=R(ua=>{"use strict";var la=F(),If=ne(),sa="<<",ca={identify:e=>e===sa||typeof e=="symbol"&&e.description===sa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new If.Scalar(Symbol(sa)),{addToJSMap:_f}),stringify:()=>sa},sy=(e,t)=>(ca.identify(t)||la.isScalar(t)&&(!t.type||t.type===If.Scalar.PLAIN)&&ca.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===ca.tag&&i.default);function _f(e,t,i){let n=Of(e,i);if(la.isSeq(n))for(let r of n.items)Cs(e,t,r);else if(Array.isArray(n))for(let r of n)Cs(e,t,r);else Cs(e,t,n)}function Cs(e,t,i){let n=Of(e,i);if(!la.isMap(n))throw new Error("Merge sources must be maps or map aliases");let r=n.toJSON(null,e,Map);for(let[a,o]of r)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 Of(e,t){return e&&la.isAlias(t)?t.resolve(e.doc,e):t}ua.addMergeToJSMap=_f;ua.isMergeKey=sy;ua.merge=ca});var Ps=R(Hf=>{"use strict";var cy=Es(),jf=fa(),ly=Tn(),$f=F(),Rs=_t();function uy(e,t,{key:i,value:n}){if($f.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(jf.isMergeKey(e,i))jf.addMergeToJSMap(e,t,n);else{let r=Rs.toJS(i,"",e);if(t instanceof Map)t.set(r,Rs.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=fy(i,r,e),o=Rs.toJS(n,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function fy(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if($f.isNode(e)&&i?.doc){let n=ly.createStringifyContext(i.doc,{});n.anchors=new Set;for(let a of i.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let r=e.toString(n);if(!i.mapKeyWarned){let a=JSON.stringify(r);a.length>40&&(a=a.substring(0,36)+'..."'),cy.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return r}return JSON.stringify(t)}Hf.addPairToJSMap=uy});var Ht=R(As=>{"use strict";var Ff=Cn(),dy=xf(),hy=Ps(),da=F();function py(e,t,i){let n=Ff.createNode(e,void 0,i),r=Ff.createNode(t,void 0,i);return new ha(n,r)}var ha=class e{constructor(t,i=null){Object.defineProperty(this,da.NODE_TYPE,{value:da.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return da.isNode(i)&&(i=i.clone(t)),da.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return hy.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?dy.stringifyPair(this,t,i,n):JSON.stringify(this)}};As.Pair=ha;As.createPair=py});var xs=R(Mf=>{"use strict";var si=F(),Lf=Tn(),pa=Rn();function my(e,t,i){return(t.inFlow??e.flow?gy:vy)(e,t,i)}function vy({comment:e,items:t},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),f=!1,d=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(si.isNode(h))!f&&h.spaceBefore&&d.push(""),ma(i,d,h.commentBefore,f),h.comment&&(v=h.comment);else if(si.isPair(h)){let y=si.isNode(h.key)?h.key:null;y&&(!f&&y.spaceBefore&&d.push(""),ma(i,d,y.commentBefore,f))}f=!1;let w=Lf.stringify(h,u,()=>v=null,()=>f=!0);v&&(w+=pa.lineComment(w,a,l(v))),f&&v&&(f=!1),d.push(n+w)}let p;if(d.length===0)p=r.start+r.end;else{p=d[0];for(let m=1;m<d.length;++m){let h=d[m];p+=h?`
25
+ `;let f,u;for(u=i.length;u>0;--u){let S=i[u-1];if(S!==`
26
+ `&&S!==" "&&S!==" ")break}let p=i.substring(u),v=p.indexOf(`
27
+ `);v===-1?f="-":i===p||v!==p.length-1?(f="+",a&&a()):f="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
28
+ `&&(p=p.slice(0,-1)),p=p.replace(Sa,`$&${l}`));let h=!1,m,g=-1;for(m=0;m<i.length;++m){let S=i[m];if(S===" ")h=!0;else if(S===`
29
+ `)g=m;else break}let N=i.substring(0,g<m?g+1:m);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let k=(h?l?"2":"1":"")+f;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!d){let S=i.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C=Rr(r,!0);o!=="folded"&&t!==pe.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{E=!0});let b=We.foldFlowLines(`${N}${S}${p}`,l,We.FOLD_BLOCK,C);if(!E)return`>${k}
31
+ ${l}${b}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
32
+ ${l}${N}${i}${p}`}function qh(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:d}=t;if(s&&a.includes(`
33
+ `)||d&&/[[\]{},]/.test(a))return Rt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||d||!a.includes(`
34
+ `)?Rt(a,t):xr(e,t,i,r);if(!s&&!d&&n!==pe.Scalar.PLAIN&&a.includes(`
35
+ `))return xr(e,t,i,r);if(Cr(a)){if(c==="")return t.forceBlockIndent=!0,xr(e,t,i,r);if(s&&c===l)return Rt(a,t)}let f=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:v}=t.doc.schema;if(v.some(u)||p?.some(u))return Rt(a,t)}return s?f:We.foldFlowLines(f,c,We.FOLD_FLOW,Rr(t,!1))}function Wh(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==pe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=pe.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case pe.Scalar.BLOCK_FOLDED:case pe.Scalar.BLOCK_LITERAL:return n||a?Rt(o.value,t):xr(o,t,i,r);case pe.Scalar.QUOTE_DOUBLE:return di(o.value,t);case pe.Scalar.QUOTE_SINGLE:return ka(o.value,t);case pe.Scalar.PLAIN:return qh(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:d,defaultStringType:f}=t.options,u=n&&d||f;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}Ic.stringifyString=Wh});var hi=y(Ea=>{"use strict";var zh=yr(),ze=P(),Jh=li(),Gh=fi();function Uh(e,t){let i=Object.assign({blockQuote:!0,commentString:Jh.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),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function Kh(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 i,r;if(ze.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function Yh(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(ze.isScalar(e)||ze.isCollection(e))&&e.anchor;a&&zh.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function Xh(e,t,i,r){if(ze.isPair(e))return e.toString(t,i,r);if(ze.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=ze.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Kh(t.doc.schema.tags,a));let o=Yh(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):ze.isScalar(a)?Gh.stringifyString(a,t,i,r):a.toString(t,i,r);return o?ze.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Ea.createStringifyContext=Uh;Ea.stringify=Xh});var Hc=y(Oc=>{"use strict";var je=P(),jc=I(),$c=hi(),pi=li();function Qh({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:f}}=i,u=je.isNode(e)&&e.comment||null;if(f){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(je.isCollection(e)||!je.isNode(e)&&typeof e=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!f&&(!e||u&&t==null&&!i.inFlow||je.isCollection(e)||(je.isScalar(e)?e.type===jc.Scalar.BLOCK_FOLDED||e.type===jc.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(f||!a),indent:s+c});let v=!1,h=!1,m=$c.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!f||t==null&&p)return m=`? ${m}`,u&&!v?m+=pi.lineComment(m,i.indent,l(u)):h&&n&&n(),m;v&&(u=null),p?(u&&(m+=pi.lineComment(m,i.indent,l(u))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,u&&(m+=pi.lineComment(m,i.indent,l(u))));let g,N,w;je.isNode(t)?(g=!!t.spaceBefore,N=t.commentBefore,w=t.comment):(g=!1,N=null,w=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!u&&je.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!d&&c.length>=2&&!i.inFlow&&!p&&je.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,S=$c.stringify(t,i,()=>k=!0,()=>h=!0),E=" ";if(u||g||N){if(E=g?`
39
+ `:"",N){let C=l(N);E+=`
40
+ ${pi.indentComment(C,i.indent)}`}S===""&&!i.inFlow?E===`
41
+ `&&w&&(E=`
42
+
43
+ `):E+=`
44
+ ${i.indent}`}else if(!p&&je.isCollection(t)){let C=S[0],b=S.indexOf(`
45
+ `),$=b!==-1,Fe=i.inFlow??t.flow??t.items.length===0;if($||!Fe){let kt=!1;if($&&(C==="&"||C==="!")){let O=S.indexOf(" ");C==="&"&&O!==-1&&O<b&&S[O+1]==="!"&&(O=S.indexOf(" ",O+1)),(O===-1||b<O)&&(kt=!0)}kt||(E=`
46
+ ${i.indent}`)}}else(S===""||S[0]===`
47
+ `)&&(E="");return m+=E+S,i.inFlow?k&&r&&r():w&&!k?m+=pi.lineComment(m,i.indent,l(w)):h&&n&&n(),m}Oc.stringifyPair=Qh});var xa=y(Pa=>{"use strict";var Dc=dr("process");function Zh(e,...t){e==="debug"&&console.log(...t)}function ep(e,t){(e==="debug"||e==="warn")&&(typeof Dc.emitWarning=="function"?Dc.emitWarning(t):console.warn(t))}Pa.debug=Zh;Pa.warn=ep});var jr=y(Ir=>{"use strict";var Tr=P(),Bc=I(),Ar="<<",_r={identify:e=>e===Ar||typeof e=="symbol"&&e.description===Ar,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Bc.Scalar(Symbol(Ar)),{addToJSMap:Lc}),stringify:()=>Ar},tp=(e,t)=>(_r.identify(t)||Tr.isScalar(t)&&(!t.type||t.type===Bc.Scalar.PLAIN)&&_r.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===_r.tag&&i.default);function Lc(e,t,i){let r=Fc(e,i);if(Tr.isSeq(r))for(let n of r.items)Ra(e,t,n);else if(Array.isArray(r))for(let n of r)Ra(e,t,n);else Ra(e,t,r)}function Ra(e,t,i){let r=Fc(e,i);if(!Tr.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.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 Fc(e,t){return e&&Tr.isAlias(t)?t.resolve(e.doc,e):t}Ir.addMergeToJSMap=Lc;Ir.isMergeKey=tp;Ir.merge=_r});var Aa=y(qc=>{"use strict";var ip=xa(),Mc=jr(),rp=hi(),Vc=P(),Ca=Ve();function np(e,t,{key:i,value:r}){if(Vc.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Mc.isMergeKey(e,i))Mc.addMergeToJSMap(e,t,r);else{let n=Ca.toJS(i,"",e);if(t instanceof Map)t.set(n,Ca.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=ap(i,n,e),o=Ca.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function ap(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Vc.isNode(e)&&i?.doc){let r=rp.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),ip.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}qc.addPairToJSMap=np});var Je=y(_a=>{"use strict";var Wc=ci(),op=Hc(),sp=Aa(),$r=P();function cp(e,t,i){let r=Wc.createNode(e,void 0,i),n=Wc.createNode(t,void 0,i);return new Or(r,n)}var Or=class e{constructor(t,i=null){Object.defineProperty(this,$r.NODE_TYPE,{value:$r.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return $r.isNode(i)&&(i=i.clone(t)),$r.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return sp.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?op.stringifyPair(this,t,i,r):JSON.stringify(this)}};_a.Pair=Or;_a.createPair=cp});var Ta=y(Jc=>{"use strict";var at=P(),zc=hi(),Hr=li();function lp(e,t,i){return(t.inFlow??e.flow?dp:up)(e,t,i)}function up({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,d=Object.assign({},i,{indent:a,type:null}),f=!1,u=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(at.isNode(h))!f&&h.spaceBefore&&u.push(""),Dr(i,u,h.commentBefore,f),h.comment&&(m=h.comment);else if(at.isPair(h)){let N=at.isNode(h.key)?h.key:null;N&&(!f&&N.spaceBefore&&u.push(""),Dr(i,u,N.commentBefore,f))}f=!1;let g=zc.stringify(h,d,()=>m=null,()=>f=!0);m&&(g+=Hr.lineComment(g,a,l(m))),f&&m&&(f=!1),u.push(r+g)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v<u.length;++v){let h=u[v];p+=h?`
48
48
  ${c}${h}`:`
49
49
  `}}return e?(p+=`
50
- `+pa.indentComment(l(e),c),s&&s()):f&&o&&o(),p}function gy({items:e},t,{flowChars:i,itemIndent:n}){let{indent:r,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;n+=a;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(si.isNode(h))h.spaceBefore&&f.push(""),ma(t,f,h.commentBefore,!1),h.comment&&(v=h.comment);else if(si.isPair(h)){let y=si.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&f.push(""),ma(t,f,y.commentBefore,!1),y.comment&&(l=!0));let b=si.isNode(h.value)?h.value:null;b?(b.comment&&(v=b.comment),b.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(v=y.comment)}v&&(l=!0);let w=Lf.stringify(h,c,()=>v=null);l||(l=f.length>u||w.includes(`
51
- `)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((y,b)=>y+b.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),v&&(w+=pa.lineComment(w,n,s(v))),f.push(w),u=f.length}let{start:d,end:p}=i;if(f.length===0)return d+p;if(!l){let m=f.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=d;for(let h of f)m+=h?`
52
- ${a}${r}${h}`:`
53
- `;return`${m}
54
- ${r}${p}`}else return`${d}${o}${f.join(" ")}${o}${p}`}function ma({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=pa.indentComment(t(n),e);i.push(a.trimStart())}}Mf.stringifyCollection=my});var Lt=R(Is=>{"use strict";var wy=xs(),yy=Ps(),Ny=ta(),Ft=F(),va=Ht(),by=ne();function _n(e,t){let i=Ft.isScalar(t)?t.value:t;for(let n of e)if(Ft.isPair(n)&&(n.key===t||n.key===i||Ft.isScalar(n.key)&&n.key.value===i))return n}var Ts=class extends Ny.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ft.MAP,t),this.items=[]}static from(t,i,n){let{keepUndefined:r,replacer:a}=n,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||r)&&o.items.push(va.createPair(c,l,n))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let n;Ft.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new va.Pair(t,t?.value):n=new va.Pair(t.key,t.value);let r=_n(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);Ft.isScalar(r.value)&&by.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let i=_n(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=_n(this.items,t)?.value;return(!i&&Ft.isScalar(r)?r.value:r)??void 0}has(t){return!!_n(this.items,t)}set(t,i){this.add(new va.Pair(t,i),!0)}toJSON(t,i,n){let r=n?new n:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(r);for(let a of this.items)yy.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!Ft.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),wy.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};Is.YAMLMap=Ts;Is.findPair=_n});var $i=R(Bf=>{"use strict";var ky=F(),Df=Lt(),Sy={collection:"map",default:!0,nodeClass:Df.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ky.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Df.YAMLMap.from(e,t,i)};Bf.map=Sy});var Mt=R(qf=>{"use strict";var Ey=Cn(),Cy=xs(),Ry=ta(),wa=F(),Py=ne(),Ay=_t(),_s=class extends Ry.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(wa.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=ga(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=ga(t);if(typeof n!="number")return;let r=this.items[n];return!i&&wa.isScalar(r)?r.value:r}has(t){let i=ga(t);return typeof i=="number"&&i<this.items.length}set(t,i){let n=ga(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[n];wa.isScalar(r)&&Py.isScalarValue(i)?r.value=i:this.items[n]=i}toJSON(t,i){let n=[];i?.onCreate&&i.onCreate(n);let r=0;for(let a of this.items)n.push(Ay.toJS(a,String(r++),i));return n}toString(t,i,n){return t?Cy.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:i}):JSON.stringify(this)}static from(t,i,n){let{replacer:r}=n,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof r=="function"){let c=i instanceof Set?s:String(o++);s=r.call(i,c,s)}a.items.push(Ey.createNode(s,void 0,n))}}return a}};function ga(e){let t=wa.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}qf.YAMLSeq=_s});var Hi=R(Wf=>{"use strict";var xy=F(),Vf=Mt(),Ty={collection:"seq",default:!0,nodeClass:Vf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return xy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Vf.YAMLSeq.from(e,t,i)};Wf.seq=Ty});var On=R(zf=>{"use strict";var Iy=xn(),_y={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,n){return t=Object.assign({actualString:!0},t),Iy.stringifyString(e,t,i,n)}};zf.string=_y});var ya=R(Uf=>{"use strict";var Jf=ne(),Gf={identify:e=>e==null,createNode:()=>new Jf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Jf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Gf.test.test(e)?e:t.options.nullStr};Uf.nullTag=Gf});var Os=R(Yf=>{"use strict";var Oy=ne(),Kf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Oy.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Kf.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};Yf.boolTag=Kf});var Fi=R(Xf=>{"use strict";function jy({format:e,minFractionDigits:t,tag:i,value:n}){if(typeof n=="bigint")return String(n);let r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!i||i==="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}Xf.stringifyNumber=jy});var $s=R(Na=>{"use strict";var $y=ne(),js=Fi(),Hy={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:js.stringifyNumber},Fy={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():js.stringifyNumber(e)}},Ly={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 $y.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:js.stringifyNumber};Na.float=Ly;Na.floatExp=Fy;Na.floatNaN=Hy});var Fs=R(ka=>{"use strict";var Qf=Fi(),ba=e=>typeof e=="bigint"||Number.isInteger(e),Hs=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function Zf(e,t,i){let{value:n}=e;return ba(n)&&n>=0?i+n.toString(t):Qf.stringifyNumber(e)}var My={identify:e=>ba(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Hs(e,2,8,i),stringify:e=>Zf(e,8,"0o")},Dy={identify:ba,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Hs(e,0,10,i),stringify:Qf.stringifyNumber},By={identify:e=>ba(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Hs(e,2,16,i),stringify:e=>Zf(e,16,"0x")};ka.int=Dy;ka.intHex=By;ka.intOct=My});var td=R(ed=>{"use strict";var qy=$i(),Vy=ya(),Wy=Hi(),zy=On(),Jy=Os(),Ls=$s(),Ms=Fs(),Gy=[qy.map,Wy.seq,zy.string,Vy.nullTag,Jy.boolTag,Ms.intOct,Ms.int,Ms.intHex,Ls.floatNaN,Ls.floatExp,Ls.float];ed.schema=Gy});var rd=R(nd=>{"use strict";var Uy=ne(),Ky=$i(),Yy=Hi();function id(e){return typeof e=="bigint"||Number.isInteger(e)}var Sa=({value:e})=>JSON.stringify(e),Xy=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Sa},{identify:e=>e==null,createNode:()=>new Uy.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Sa},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Sa},{identify:id,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>id(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:Sa}],Qy={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Zy=[Ky.map,Yy.seq].concat(Xy,Qy);nd.schema=Zy});var Bs=R(ad=>{"use strict";var jn=Jr("buffer"),Ds=ne(),eN=xn(),tN={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof jn.Buffer=="function")return jn.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(i.length);for(let r=0;r<i.length;++r)n[r]=i.charCodeAt(r);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},n,r,a){if(!i)return"";let o=i,s;if(typeof jn.Buffer=="function")s=o instanceof jn.Buffer?o.toString("base64"):jn.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=Ds.Scalar.BLOCK_LITERAL),t!==Ds.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(t===Ds.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return eN.stringifyString({comment:e,type:t,value:s},n,r,a)}};ad.binary=tN});var Ra=R(Ca=>{"use strict";var Ea=F(),qs=Ht(),iN=ne(),nN=Mt();function od(e,t){if(Ea.isSeq(e))for(let i=0;i<e.items.length;++i){let n=e.items[i];if(!Ea.isPair(n)){if(Ea.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new qs.Pair(new iN.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
56
- ${r.key.commentBefore}`:n.commentBefore),n.comment){let a=r.value??r.key;a.comment=a.comment?`${n.comment}
57
- ${a.comment}`:n.comment}n=r}e.items[i]=Ea.isPair(n)?n:new qs.Pair(n)}}else t("Expected a sequence for this tag");return e}function sd(e,t,i){let{replacer:n}=i,r=new nN.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;r.items.push(qs.createPair(s,c,i))}return r}var rN={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:od,createNode:sd};Ca.createPairs=sd;Ca.pairs=rN;Ca.resolvePairs=od});var zs=R(Ws=>{"use strict";var cd=F(),Vs=_t(),$n=Lt(),aN=Mt(),ld=Ra(),ci=class e extends aN.YAMLSeq{constructor(){super(),this.add=$n.YAMLMap.prototype.add.bind(this),this.delete=$n.YAMLMap.prototype.delete.bind(this),this.get=$n.YAMLMap.prototype.get.bind(this),this.has=$n.YAMLMap.prototype.has.bind(this),this.set=$n.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(cd.isPair(r)?(a=Vs.toJS(r.key,"",i),o=Vs.toJS(r.value,a,i)):a=Vs.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,i,n){let r=ld.createPairs(t,i,n),a=new this;return a.items=r.items,a}};ci.tag="tag:yaml.org,2002:omap";var oN={collection:"seq",identify:e=>e instanceof Map,nodeClass:ci,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=ld.resolvePairs(e,t),n=[];for(let{key:r}of i.items)cd.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new ci,i)},createNode:(e,t,i)=>ci.from(e,t,i)};Ws.YAMLOMap=ci;Ws.omap=oN});var pd=R(Js=>{"use strict";var ud=ne();function fd({value:e,source:t},i){return t&&(e?dd:hd).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var dd={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 ud.Scalar(!0),stringify:fd},hd={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 ud.Scalar(!1),stringify:fd};Js.falseTag=hd;Js.trueTag=dd});var md=R(Pa=>{"use strict";var sN=ne(),Gs=Fi(),cN={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:Gs.stringifyNumber},lN={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():Gs.stringifyNumber(e)}},uN={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 sN.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let n=e.substring(i+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:Gs.stringifyNumber};Pa.float=uN;Pa.floatExp=lN;Pa.floatNaN=cN});var gd=R(Fn=>{"use strict";var vd=Fi(),Hn=e=>typeof e=="bigint"||Number.isInteger(e);function Aa(e,t,i,{intAsBigInt:n}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return r==="-"?-1*a:a}function Us(e,t,i){let{value:n}=e;if(Hn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return vd.stringifyNumber(e)}var fN={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Aa(e,2,2,i),stringify:e=>Us(e,2,"0b")},dN={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Aa(e,1,8,i),stringify:e=>Us(e,8,"0")},hN={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Aa(e,0,10,i),stringify:vd.stringifyNumber},pN={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Aa(e,2,16,i),stringify:e=>Us(e,16,"0x")};Fn.int=hN;Fn.intBin=fN;Fn.intHex=pN;Fn.intOct=dN});var Ys=R(Ks=>{"use strict";var Ia=F(),xa=Ht(),Ta=Lt(),li=class e extends Ta.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Ia.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new xa.Pair(t.key,null):i=new xa.Pair(t,null),Ta.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=Ta.findPair(this.items,t);return!i&&Ia.isPair(n)?Ia.isScalar(n.key)?n.key.value:n.key:n}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let n=Ta.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new xa.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,n);throw new Error("Set items must all have null values")}static from(t,i,n){let{replacer:r}=n,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof r=="function"&&(o=r.call(i,o,o)),a.items.push(xa.createPair(o,null,n));return a}};li.tag="tag:yaml.org,2002:set";var mN={collection:"map",identify:e=>e instanceof Set,nodeClass:li,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>li.from(e,t,i),resolve(e,t){if(Ia.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new li,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ks.YAMLSet=li;Ks.set=mN});var Qs=R(_a=>{"use strict";var vN=Fi();function Xs(e,t){let i=e[0],n=i==="-"||i==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function wd(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return vN.stringifyNumber(e);let n="";t<0&&(n="-",t*=i(-1));let r=i(60),a=[t%r];return t<60?a.unshift(0):(t=(t-a[0])/r,a.unshift(t%r),t>=60&&(t=(t-a[0])/r,a.unshift(t))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var gN={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:i})=>Xs(e,i),stringify:wd},wN={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=>Xs(e,!1),stringify:wd},yd={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(yd.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let f=Xs(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};_a.floatTime=wN;_a.intTime=gN;_a.timestamp=yd});var kd=R(bd=>{"use strict";var yN=$i(),NN=ya(),bN=Hi(),kN=On(),SN=Bs(),Nd=pd(),Zs=md(),Oa=gd(),EN=fa(),CN=zs(),RN=Ra(),PN=Ys(),ec=Qs(),AN=[yN.map,bN.seq,kN.string,NN.nullTag,Nd.trueTag,Nd.falseTag,Oa.intBin,Oa.intOct,Oa.int,Oa.intHex,Zs.floatNaN,Zs.floatExp,Zs.float,SN.binary,EN.merge,CN.omap,RN.pairs,PN.set,ec.intTime,ec.floatTime,ec.timestamp];bd.schema=AN});var _d=R(nc=>{"use strict";var Rd=$i(),xN=ya(),Pd=Hi(),TN=On(),IN=Os(),tc=$s(),ic=Fs(),_N=td(),ON=rd(),Ad=Bs(),Ln=fa(),xd=zs(),Td=Ra(),Sd=kd(),Id=Ys(),ja=Qs(),Ed=new Map([["core",_N.schema],["failsafe",[Rd.map,Pd.seq,TN.string]],["json",ON.schema],["yaml11",Sd.schema],["yaml-1.1",Sd.schema]]),Cd={binary:Ad.binary,bool:IN.boolTag,float:tc.float,floatExp:tc.floatExp,floatNaN:tc.floatNaN,floatTime:ja.floatTime,int:ic.int,intHex:ic.intHex,intOct:ic.intOct,intTime:ja.intTime,map:Rd.map,merge:Ln.merge,null:xN.nullTag,omap:xd.omap,pairs:Td.pairs,seq:Pd.seq,set:Id.set,timestamp:ja.timestamp},jN={"tag:yaml.org,2002:binary":Ad.binary,"tag:yaml.org,2002:merge":Ln.merge,"tag:yaml.org,2002:omap":xd.omap,"tag:yaml.org,2002:pairs":Td.pairs,"tag:yaml.org,2002:set":Id.set,"tag:yaml.org,2002:timestamp":ja.timestamp};function $N(e,t,i){let n=Ed.get(t);if(n&&!e)return i&&!n.includes(Ln.merge)?n.concat(Ln.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(Ed.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)r=r.concat(a);else typeof e=="function"&&(r=e(r.slice()));return i&&(r=r.concat(Ln.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Cd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Cd).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},[])}nc.coreKnownTags=jN;nc.getTags=$N});var oc=R(Od=>{"use strict";var rc=F(),HN=$i(),FN=Hi(),LN=On(),$a=_d(),MN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ac=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?$a.getTags(t,"compat"):t?$a.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?$a.coreKnownTags:{},this.tags=$a.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,rc.MAP,{value:HN.map}),Object.defineProperty(this,rc.SCALAR,{value:LN.string}),Object.defineProperty(this,rc.SEQ,{value:FN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?MN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Od.Schema=ac});var $d=R(jd=>{"use strict";var DN=F(),sc=Tn(),Mn=Rn();function BN(e,t){let i=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&i.push("---");let r=sc.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Mn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(DN.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Mn.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=sc.stringify(e.contents,r,()=>s=null,c);s&&(l+=Mn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(sc.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(Mn.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(Mn.indentComment(a(c),"")))}return i.join(`
50
+ `+Hr.indentComment(l(e),c),s&&s()):f&&o&&o(),p}function dp({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,d=0,f=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(at.isNode(h))h.spaceBefore&&f.push(""),Dr(t,f,h.commentBefore,!1),h.comment&&(m=h.comment);else if(at.isPair(h)){let N=at.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&f.push(""),Dr(t,f,N.commentBefore,!1),N.comment&&(l=!0));let w=at.isNode(h.value)?h.value:null;w?(w.comment&&(m=w.comment),w.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(m=N.comment)}m&&(l=!0);let g=zc.stringify(h,c,()=>m=null);l||(l=f.length>d||g.includes(`
51
+ `)),v<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((N,w)=>N+w.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),m&&(g+=Hr.lineComment(g,r,s(m))),f.push(g),d=f.length}let{start:u,end:p}=i;if(f.length===0)return u+p;if(!l){let v=f.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=u;for(let h of f)v+=h?`
52
+ ${a}${n}${h}`:`
53
+ `;return`${v}
54
+ ${n}${p}`}else return`${u}${o}${f.join(" ")}${o}${p}`}function Dr({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Hr.indentComment(t(r),e);i.push(a.trimStart())}}Jc.stringifyCollection=lp});var Ue=y(ja=>{"use strict";var fp=Ta(),hp=Aa(),pp=Sr(),Ge=P(),Br=Je(),mp=I();function mi(e,t){let i=Ge.isScalar(t)?t.value:t;for(let r of e)if(Ge.isPair(r)&&(r.key===t||r.key===i||Ge.isScalar(r.key)&&r.key.value===i))return r}var Ia=class extends pp.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ge.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Br.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Ge.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Br.Pair(t,t?.value):r=new Br.Pair(t.key,t.value);let n=mi(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Ge.isScalar(n.value)&&mp.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=mi(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=mi(this.items,t)?.value;return(!i&&Ge.isScalar(n)?n.value:n)??void 0}has(t){return!!mi(this.items,t)}set(t,i){this.add(new Br.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)hp.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Ge.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})),fp.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};ja.YAMLMap=Ia;ja.findPair=mi});var Ct=y(Uc=>{"use strict";var vp=P(),Gc=Ue(),gp={collection:"map",default:!0,nodeClass:Gc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return vp.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Gc.YAMLMap.from(e,t,i)};Uc.map=gp});var Ke=y(Kc=>{"use strict";var wp=ci(),yp=Ta(),Np=Sr(),Fr=P(),bp=I(),kp=Ve(),$a=class extends Np.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Fr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Lr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Lr(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Fr.isScalar(n)?n.value:n}has(t){let i=Lr(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Lr(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Fr.isScalar(n)&&bp.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(kp.toJS(a,String(n++),i));return r}toString(t,i,r){return t?yp.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(wp.createNode(s,void 0,r))}}return a}};function Lr(e){let t=Fr.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Kc.YAMLSeq=$a});var At=y(Xc=>{"use strict";var Sp=P(),Yc=Ke(),Ep={collection:"seq",default:!0,nodeClass:Yc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Sp.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Yc.YAMLSeq.from(e,t,i)};Xc.seq=Ep});var vi=y(Qc=>{"use strict";var Pp=fi(),xp={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),Pp.stringifyString(e,t,i,r)}};Qc.string=xp});var Mr=y(tl=>{"use strict";var Zc=I(),el={identify:e=>e==null,createNode:()=>new Zc.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Zc.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&el.test.test(e)?e:t.options.nullStr};tl.nullTag=el});var Oa=y(rl=>{"use strict";var Rp=I(),il={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Rp.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&il.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};rl.boolTag=il});var _t=y(nl=>{"use strict";function Cp({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="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}nl.stringifyNumber=Cp});var Da=y(Vr=>{"use strict";var Ap=I(),Ha=_t(),_p={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:Ha.stringifyNumber},Tp={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():Ha.stringifyNumber(e)}},Ip={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 Ap.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ha.stringifyNumber};Vr.float=Ip;Vr.floatExp=Tp;Vr.floatNaN=_p});var La=y(Wr=>{"use strict";var al=_t(),qr=e=>typeof e=="bigint"||Number.isInteger(e),Ba=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function ol(e,t,i){let{value:r}=e;return qr(r)&&r>=0?i+r.toString(t):al.stringifyNumber(e)}var jp={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Ba(e,2,8,i),stringify:e=>ol(e,8,"0o")},$p={identify:qr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Ba(e,0,10,i),stringify:al.stringifyNumber},Op={identify:e=>qr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Ba(e,2,16,i),stringify:e=>ol(e,16,"0x")};Wr.int=$p;Wr.intHex=Op;Wr.intOct=jp});var cl=y(sl=>{"use strict";var Hp=Ct(),Dp=Mr(),Bp=At(),Lp=vi(),Fp=Oa(),Fa=Da(),Ma=La(),Mp=[Hp.map,Bp.seq,Lp.string,Dp.nullTag,Fp.boolTag,Ma.intOct,Ma.int,Ma.intHex,Fa.floatNaN,Fa.floatExp,Fa.float];sl.schema=Mp});var dl=y(ul=>{"use strict";var Vp=I(),qp=Ct(),Wp=At();function ll(e){return typeof e=="bigint"||Number.isInteger(e)}var zr=({value:e})=>JSON.stringify(e),zp=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:zr},{identify:e=>e==null,createNode:()=>new Vp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:zr},{identify:ll,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>ll(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:zr}],Jp={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Gp=[qp.map,Wp.seq].concat(zp,Jp);ul.schema=Gp});var qa=y(fl=>{"use strict";var gi=dr("buffer"),Va=I(),Up=fi(),Kp={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof gi.Buffer=="function")return gi.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof gi.Buffer=="function")s=o instanceof gi.Buffer?o.toString("base64"):gi.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let 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=Va.Scalar.BLOCK_LITERAL),t!==Va.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),d=new Array(l);for(let f=0,u=0;f<l;++f,u+=c)d[f]=s.substr(u,c);s=d.join(t===Va.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return Up.stringifyString({comment:e,type:t,value:s},r,n,a)}};fl.binary=Kp});var Ur=y(Gr=>{"use strict";var Jr=P(),Wa=Je(),Yp=I(),Xp=Ke();function hl(e,t){if(Jr.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Jr.isPair(r)){if(Jr.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Wa.Pair(new Yp.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
56
+ ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
57
+ ${a.comment}`:r.comment}r=n}e.items[i]=Jr.isPair(r)?r:new Wa.Pair(r)}}else t("Expected a sequence for this tag");return e}function pl(e,t,i){let{replacer:r}=i,n=new Xp.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 r=="function"&&(o=r.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(Wa.createPair(s,c,i))}return n}var Qp={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hl,createNode:pl};Gr.createPairs=pl;Gr.pairs=Qp;Gr.resolvePairs=hl});var Ga=y(Ja=>{"use strict";var ml=P(),za=Ve(),wi=Ue(),Zp=Ke(),vl=Ur(),ot=class e extends Zp.YAMLSeq{constructor(){super(),this.add=wi.YAMLMap.prototype.add.bind(this),this.delete=wi.YAMLMap.prototype.delete.bind(this),this.get=wi.YAMLMap.prototype.get.bind(this),this.has=wi.YAMLMap.prototype.has.bind(this),this.set=wi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(ml.isPair(n)?(a=za.toJS(n.key,"",i),o=za.toJS(n.value,a,i)):a=za.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=vl.createPairs(t,i,r),a=new this;return a.items=n.items,a}};ot.tag="tag:yaml.org,2002:omap";var em={collection:"seq",identify:e=>e instanceof Map,nodeClass:ot,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=vl.resolvePairs(e,t),r=[];for(let{key:n}of i.items)ml.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new ot,i)},createNode:(e,t,i)=>ot.from(e,t,i)};Ja.YAMLOMap=ot;Ja.omap=em});var bl=y(Ua=>{"use strict";var gl=I();function wl({value:e,source:t},i){return t&&(e?yl:Nl).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var yl={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 gl.Scalar(!0),stringify:wl},Nl={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 gl.Scalar(!1),stringify:wl};Ua.falseTag=Nl;Ua.trueTag=yl});var kl=y(Kr=>{"use strict";var tm=I(),Ka=_t(),im={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:Ka.stringifyNumber},rm={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():Ka.stringifyNumber(e)}},nm={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 tm.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Ka.stringifyNumber};Kr.float=nm;Kr.floatExp=rm;Kr.floatNaN=im});var El=y(Ni=>{"use strict";var Sl=_t(),yi=e=>typeof e=="bigint"||Number.isInteger(e);function Yr(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){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,i);return n==="-"?-1*a:a}function Ya(e,t,i){let{value:r}=e;if(yi(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Sl.stringifyNumber(e)}var am={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Yr(e,2,2,i),stringify:e=>Ya(e,2,"0b")},om={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Yr(e,1,8,i),stringify:e=>Ya(e,8,"0")},sm={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Yr(e,0,10,i),stringify:Sl.stringifyNumber},cm={identify:yi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Yr(e,2,16,i),stringify:e=>Ya(e,16,"0x")};Ni.int=sm;Ni.intBin=am;Ni.intHex=cm;Ni.intOct=om});var Qa=y(Xa=>{"use strict";var Zr=P(),Xr=Je(),Qr=Ue(),st=class e extends Qr.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Zr.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Xr.Pair(t.key,null):i=new Xr.Pair(t,null),Qr.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Qr.findPair(this.items,t);return!i&&Zr.isPair(r)?Zr.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Qr.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Xr.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Xr.createPair(o,null,r));return a}};st.tag="tag:yaml.org,2002:set";var lm={collection:"map",identify:e=>e instanceof Set,nodeClass:st,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>st.from(e,t,i),resolve(e,t){if(Zr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new st,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Xa.YAMLSet=st;Xa.set=lm});var eo=y(en=>{"use strict";var um=_t();function Za(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Pl(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return um.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(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))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var dm={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:i})=>Za(e,i),stringify:Pl},fm={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=>Za(e,!1),stringify:Pl},xl={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(xl.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),d=t[8];if(d&&d!=="Z"){let f=Za(d,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};en.floatTime=fm;en.intTime=dm;en.timestamp=xl});var Al=y(Cl=>{"use strict";var hm=Ct(),pm=Mr(),mm=At(),vm=vi(),gm=qa(),Rl=bl(),to=kl(),tn=El(),wm=jr(),ym=Ga(),Nm=Ur(),bm=Qa(),io=eo(),km=[hm.map,mm.seq,vm.string,pm.nullTag,Rl.trueTag,Rl.falseTag,tn.intBin,tn.intOct,tn.int,tn.intHex,to.floatNaN,to.floatExp,to.float,gm.binary,wm.merge,ym.omap,Nm.pairs,bm.set,io.intTime,io.floatTime,io.timestamp];Cl.schema=km});var Ll=y(ao=>{"use strict";var jl=Ct(),Sm=Mr(),$l=At(),Em=vi(),Pm=Oa(),ro=Da(),no=La(),xm=cl(),Rm=dl(),Ol=qa(),bi=jr(),Hl=Ga(),Dl=Ur(),_l=Al(),Bl=Qa(),rn=eo(),Tl=new Map([["core",xm.schema],["failsafe",[jl.map,$l.seq,Em.string]],["json",Rm.schema],["yaml11",_l.schema],["yaml-1.1",_l.schema]]),Il={binary:Ol.binary,bool:Pm.boolTag,float:ro.float,floatExp:ro.floatExp,floatNaN:ro.floatNaN,floatTime:rn.floatTime,int:no.int,intHex:no.intHex,intOct:no.intOct,intTime:rn.intTime,map:jl.map,merge:bi.merge,null:Sm.nullTag,omap:Hl.omap,pairs:Dl.pairs,seq:$l.seq,set:Bl.set,timestamp:rn.timestamp},Cm={"tag:yaml.org,2002:binary":Ol.binary,"tag:yaml.org,2002:merge":bi.merge,"tag:yaml.org,2002:omap":Hl.omap,"tag:yaml.org,2002:pairs":Dl.pairs,"tag:yaml.org,2002:set":Bl.set,"tag:yaml.org,2002:timestamp":rn.timestamp};function Am(e,t,i){let r=Tl.get(t);if(r&&!e)return i&&!r.includes(bi.merge)?r.concat(bi.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Tl.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 i&&(n=n.concat(bi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Il[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Il).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}ao.coreKnownTags=Cm;ao.getTags=Am});var co=y(Fl=>{"use strict";var oo=P(),_m=Ct(),Tm=At(),Im=vi(),nn=Ll(),jm=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,so=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?nn.getTags(t,"compat"):t?nn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?nn.coreKnownTags:{},this.tags=nn.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,oo.MAP,{value:_m.map}),Object.defineProperty(this,oo.SCALAR,{value:Im.string}),Object.defineProperty(this,oo.SEQ,{value:Tm.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?jm:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Fl.Schema=so});var Vl=y(Ml=>{"use strict";var $m=P(),lo=hi(),ki=li();function Om(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=lo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(ki.indentComment(c,""))}let o=!1,s=null;if(e.contents){if($m.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let d=a(e.contents.commentBefore);i.push(ki.indentComment(d,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=lo.stringify(e.contents,n,()=>s=null,c);s&&(l+=ki.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(lo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(ki.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(ki.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}jd.stringifyDocument=BN});var Dn=R(Hd=>{"use strict";var qN=En(),Li=ta(),Le=F(),VN=Ht(),WN=_t(),zN=oc(),JN=$d(),cc=Xr(),GN=ds(),UN=Cn(),lc=fs(),uc=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Le.NODE_TYPE,{value:Le.DOC});let r=null;typeof i=="function"||Array.isArray(i)?r=i:n===void 0&&i&&(n=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new lc.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,r,n)}clone(){let t=Object.create(e.prototype,{[Le.NODE_TYPE]:{value:Le.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=Le.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Mi(this.contents)&&this.contents.add(t)}addIn(t,i){Mi(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=cc.anchorNames(this);t.anchor=!i||n.has(i)?cc.findNewAnchor(i||"a",n):i}return new qN.Alias(t.anchor)}createNode(t,i,n){let r;if(typeof i=="function")t=i.call({"":t},"",t),r=i;else if(Array.isArray(i)){let v=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=i.filter(v).map(String);w.length>0&&(i=i.concat(w)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:f,setAnchors:d,sourceObjects:p}=cc.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=UN.createNode(t,u,m);return s&&Le.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,i,n={}){let r=this.createNode(t,null,n),a=this.createNode(i,null,n);return new VN.Pair(r,a)}delete(t){return Mi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Li.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Mi(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Le.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Li.isEmptyPath(t)?!i&&Le.isScalar(this.contents)?this.contents.value:this.contents:Le.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Le.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Li.isEmptyPath(t)?this.contents!==void 0:Le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Li.collectionFromPath(this.schema,[t],i):Mi(this.contents)&&this.contents.set(t,i)}setIn(t,i){Li.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Li.collectionFromPath(this.schema,Array.from(t),i):Mi(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new lc.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new lc.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let r=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(n)this.schema=new zN.Schema(Object.assign(n,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:n,maxAliasCount:r,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=WN.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?GN.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}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 i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return JN.stringifyDocument(this,t)}};function Mi(e){if(Le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Hd.Document=uc});var Vn=R(qn=>{"use strict";var Bn=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},fc=class extends Bn{constructor(t,i,n){super("YAMLParseError",t,i,n)}},dc=class extends Bn{constructor(t,i,n){super("YAMLWarning",t,i,n)}},KN=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:n,col:r}=i.linePos[0];i.message+=` at line ${n}, column ${r}`;let a=r-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
61
- `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===n&&c.col>r&&(s=Math.max(1,Math.min(c.col-r,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
60
+ `}Ml.stringifyDocument=Om});var Si=y(ql=>{"use strict";var Hm=si(),Tt=Sr(),oe=P(),Dm=Je(),Bm=Ve(),Lm=co(),Fm=Vl(),uo=yr(),Mm=pa(),Vm=ci(),fo=ha(),ho=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe.NODE_TYPE,{value:oe.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new fo.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[oe.NODE_TYPE]:{value:oe.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=oe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){It(this.contents)&&this.contents.add(t)}addIn(t,i){It(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=uo.anchorNames(this);t.anchor=!i||r.has(i)?uo.findNewAnchor(i||"a",r):i}return new Hm.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=N=>typeof N=="number"||N instanceof String||N instanceof Number,g=i.filter(m).map(String);g.length>0&&(i=i.concat(g)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:d}=r??{},{onAnchor:f,setAnchors:u,sourceObjects:p}=uo.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Vm.createNode(t,d,v);return s&&oe.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new Dm.Pair(n,a)}delete(t){return It(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Tt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):It(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return oe.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Tt.isEmptyPath(t)?!i&&oe.isScalar(this.contents)?this.contents.value:this.contents:oe.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return oe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Tt.isEmptyPath(t)?this.contents!==void 0:oe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Tt.collectionFromPath(this.schema,[t],i):It(this.contents)&&this.contents.set(t,i)}setIn(t,i){Tt.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Tt.collectionFromPath(this.schema,Array.from(t),i):It(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new fo.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new fo.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=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(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new Lm.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Bm.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:d}of s.anchors.values())a(d,l);return typeof o=="function"?Mm.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}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 i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return Fm.stringifyDocument(this,t)}};function It(e){if(oe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ql.Document=ho});var xi=y(Pi=>{"use strict";var Ei=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},po=class extends Ei{constructor(t,i,r){super("YAMLParseError",t,i,r)}},mo=class extends Ei{constructor(t,i,r){super("YAMLWarning",t,i,r)}},qm=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).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)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
61
+ `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};qn.YAMLError=Bn;qn.YAMLParseError=fc;qn.YAMLWarning=dc;qn.prettifyError=KN});var Wn=R(Fd=>{"use strict";function YN(e,{flow:t,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",p=!1,m=!1,h=null,v=null,w=null,y=null,b=null,N=null,E=null;for(let k of e)switch(m&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!t&&(i!=="doc-start"||n?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),u=!0;break;case"comment":{u||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=k.source.substring(1)||" ";f?f+=d+C:f=C,d="",l=!1;break}case"newline":l?f?f+=k.source:(!N||i!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,p=!0,(v||w)&&(y=k),u=!0;break;case"anchor":v&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=k,E??(E=k.offset),l=!1,u=!1,m=!0;break;case"tag":{w&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),w=k,E??(E=k.offset),l=!1,u=!1,m=!0;break}case i:(v||w)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),N&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),N=k,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){b&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=k,l=!1,u=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let g=e[e.length-1],S=g?g.offset+g.source.length:r;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:N,spaceBefore:c,comment:f,hasNewline:p,anchor:v,tag:w,newlineAfterProp:y,end:S,start:E??S}}Fd.resolveProps=YN});var Ha=R(Ld=>{"use strict";function hc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(hc(t.key)||hc(t.value))return!0}return!1;default:return!0}}Ld.containsNewline=hc});var pc=R(Md=>{"use strict";var XN=Ha();function QN(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&XN.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Md.flowIndentCheck=QN});var mc=R(Bd=>{"use strict";var Dd=F();function ZN(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||Dd.isScalar(a)&&Dd.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Bd.mapIncludes=ZN});var Gd=R(Jd=>{"use strict";var qd=Ht(),eb=Lt(),Vd=Wn(),tb=Ha(),Wd=pc(),ib=mc(),zd="All mapping items must start at the same column";function nb({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??eb.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:f,key:d,sep:p,value:m}=u,h=Vd.resolveProps(f,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),v=!h.found;if(v){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&r(c,"BAD_INDENT",zd)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||tb.containsNewline(d))&&r(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&r(c,"BAD_INDENT",zd);i.atKey=!0;let w=h.end,y=d?e(i,d,h,r):t(i,w,f,null,h,r);i.schema.compat&&Wd.flowIndentCheck(n.indent,d,r),i.atKey=!1,ib.mapIncludes(i,s.items,y)&&r(w,"DUPLICATE_KEY","Map keys must be unique");let b=Vd.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:r,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=b.end,b.found){v&&(m?.type==="block-map"&&!b.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<b.found.offset-1024&&r(y.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(i,m,b,r):t(i,c,p,null,b,r);i.schema.compat&&Wd.flowIndentCheck(n.indent,m,r),c=N.range[2];let E=new qd.Pair(y,N);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{v&&r(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(y.comment?y.comment+=`
68
- `+b.comment:y.comment=b.comment);let N=new qd.Pair(y);i.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}Jd.resolveBlockMap=nb});var Kd=R(Ud=>{"use strict";var rb=Mt(),ab=Wn(),ob=pc();function sb({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??rb.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:f}of n.items){let d=ab.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=f?e(i,f,d,r):t(i,d.end,u,null,d,r);i.schema.compat&&ob.flowIndentCheck(n.indent,f,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}Ud.resolveBlockSeq=sb});var Di=R(Yd=>{"use strict";function cb(e,t,i,n){let r="";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":{i&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";r?r+=o+u:r=u,o="";break}case"newline":r&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:r,offset:t}}Yd.resolveEnd=cb});var eh=R(Zd=>{"use strict";var lb=F(),ub=Ht(),Xd=Lt(),fb=Mt(),db=Di(),Qd=Wn(),hb=Ha(),pb=mc(),vc="Block collections are not allowed within flow collections",gc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function mb({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Xd.YAMLMap:fb.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let f=n.offset+n.start.source.length;for(let v=0;v<n.items.length;++v){let w=n.items[v],{start:y,key:b,sep:N,value:E}=w,g=Qd.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:b??N?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!N&&!E){v===0&&g.comma?r(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<n.items.length-1&&r(g.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),g.comment&&(l.comment?l.comment+=`
69
- `+g.comment:l.comment=g.comment),f=g.end;continue}!o&&i.options.strict&&hb.containsNewline(b)&&r(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)g.comma&&r(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||r(g.start,"MISSING_CHAR",`Missing , between ${s} items`),g.comment){let S="";e:for(let k of y)switch(k.type){case"comma":case"space":break;case"comment":S=k.source.substring(1);break e;default:break e}if(S){let k=l.items[l.items.length-1];lb.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
70
- `+S:k.comment=S,g.comment=g.comment.substring(S.length+1)}}if(!o&&!N&&!g.found){let S=E?e(i,E,g,r):t(i,g.end,N,null,g,r);l.items.push(S),f=S.range[2],gc(E)&&r(S.range,"BLOCK_IN_FLOW",vc)}else{i.atKey=!0;let S=g.end,k=b?e(i,b,g,r):t(i,S,y,null,g,r);gc(b)&&r(k.range,"BLOCK_IN_FLOW",vc),i.atKey=!1;let C=Qd.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:E,offset:k.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(C.found){if(!o&&!g.found&&i.options.strict){if(N)for(let D of N){if(D===C.found)break;if(D.type==="newline"){r(D,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<C.found.offset-1024&&r(C.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?r(E,"MISSING_CHAR",`Missing space after : in ${s}`):r(C.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let B=E?e(i,E,C,r):C.found?t(i,C.end,N,null,C,r):null;B?gc(E)&&r(B.range,"BLOCK_IN_FLOW",vc):C.comment&&(k.comment?k.comment+=`
71
- `+C.comment:k.comment=C.comment);let K=new ub.Pair(k,B);if(i.options.keepSourceTokens&&(K.srcToken=w),o){let D=l;pb.mapIncludes(i,D.items,k)&&r(S,"DUPLICATE_KEY","Map keys must be unique"),D.items.push(K)}else{let D=new Xd.YAMLMap(i.schema);D.flow=!0,D.items.push(K);let J=(B??k).range;D.range=[k.range[0],J[1],J[2]],l.items.push(D)}f=B?B.range[2]:C.end}}let d=o?"}":"]",[p,...m]=n.end,h=f;if(p?.source===d)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),w=u?`${v} must end with a ${d}`:`${v} in block collection must be sufficiently indented and end with a ${d}`;r(f,u?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=db.resolveEnd(m,h,i.options.strict,r);v.comment&&(l.comment?l.comment+=`
72
- `+v.comment:l.comment=v.comment),l.range=[n.offset,h,v.offset]}else l.range=[n.offset,h,h];return l}Zd.resolveFlowCollection=mb});var ih=R(th=>{"use strict";var vb=F(),gb=ne(),wb=Lt(),yb=Mt(),Nb=Gd(),bb=Kd(),kb=eh();function wc(e,t,i,n,r,a){let o=i.type==="block-map"?Nb.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?bb.resolveBlockSeq(e,t,i,n,a):kb.resolveFlowCollection(e,t,i,n,a),s=o.constructor;return r==="!"||r===s.tagName?(o.tag=s.tagName,o):(r&&(o.tag=r),o)}function Sb(e,t,i,n,r){let a=n.tag,o=a?t.directives.tagName(a.source,d=>r(a,"TAG_RESOLVE_FAILED",d)):null;if(i.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,m=d&&a?d.offset>a.offset?d:a:d??a;m&&(!p||p.offset<m.offset)&&r(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===wb.YAMLMap.tagName&&s==="map"||o===yb.YAMLSeq.tagName&&s==="seq")return wc(e,t,i,r,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):r(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),wc(e,t,i,r,o)}let l=wc(e,t,i,r,o,c),u=c.resolve?.(l,d=>r(a,"TAG_RESOLVE_FAILED",d),t.options)??l,f=vb.isNode(u)?u:new gb.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}th.composeCollection=Sb});var Nc=R(nh=>{"use strict";var yc=ne();function Eb(e,t,i){let n=t.offset,r=Cb(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?yc.Scalar.BLOCK_FOLDED:yc.Scalar.BLOCK_LITERAL,o=t.source?Rb(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=r.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",v=n+r.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:r.comment,range:[n,v,v]}}let c=t.indent+r.indent,l=t.offset+r.length,u=0;for(let h=0;h<s;++h){let[v,w]=o[h];if(w===""||w==="\r")r.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&i(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let f="",d="",p=!1;for(let h=0;h<u;++h)f+=o[h][0].slice(c)+`
74
- `;for(let h=u;h<s;++h){let[v,w]=o[h];l+=v.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&v.length<c){let N=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-w.length-(y?2:1),"BAD_INDENT",N),v=""}a===yc.Scalar.BLOCK_LITERAL?(f+=d+v.slice(c)+w,d=`
75
- `):v.length>c||w[0]===" "?(d===" "?d=`
76
- `:!p&&d===`
77
- `&&(d=`
78
-
79
- `),f+=d+v.slice(c)+w,d=`
80
- `,p=!0):w===""?d===`
65
+ `}};Pi.YAMLError=Ei;Pi.YAMLParseError=po;Pi.YAMLWarning=mo;Pi.prettifyError=qm});var Ri=y(Wl=>{"use strict";function Wm(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,d=s,f="",u="",p=!1,v=!1,h=null,m=null,g=null,N=null,w=null,k=null,S=null;for(let b of e)switch(v&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),d=!0;break;case"comment":{d||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let $=b.source.substring(1)||" ";f?f+=u+$:f=$,u="",l=!1;break}case"newline":l?f?f+=b.source:(!k||i!=="seq-item-ind")&&(c=!0):u+=b.source,l=!0,p=!0,(m||g)&&(N=b),d=!0;break;case"anchor":m&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,S??(S=b.offset),l=!1,d=!1,v=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,S??(S=b.offset),l=!1,d=!1,v=!0;break}case i:(m||g)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=i==="seq-item-ind"||i==="explicit-key-ind",d=!1;break;case"comma":if(t){w&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=b,l=!1,d=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,d=!1}let E=e[e.length-1],C=E?E.offset+E.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:k,spaceBefore:c,comment:f,hasNewline:p,anchor:m,tag:g,newlineAfterProp:N,end:C,start:S??C}}Wl.resolveProps=Wm});var an=y(zl=>{"use strict";function vo(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(vo(t.key)||vo(t.value))return!0}return!1;default:return!0}}zl.containsNewline=vo});var go=y(Jl=>{"use strict";var zm=an();function Jm(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&zm.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Jl.flowIndentCheck=Jm});var wo=y(Ul=>{"use strict";var Gl=P();function Gm(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Gl.isScalar(a)&&Gl.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Ul.mapIncludes=Gm});var eu=y(Zl=>{"use strict";var Kl=Je(),Um=Ue(),Yl=Ri(),Km=an(),Xl=go(),Ym=wo(),Ql="All mapping items must start at the same column";function Xm({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Um.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let d of r.items){let{start:f,key:u,sep:p,value:v}=d,h=Yl.resolveProps(f,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==r.indent&&n(c,"BAD_INDENT",Ql)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Km.containsNewline(u))&&n(u??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Ql);i.atKey=!0;let g=h.end,N=u?e(i,u,h,n):t(i,g,f,null,h,n);i.schema.compat&&Xl.flowIndentCheck(r.indent,u,n),i.atKey=!1,Ym.mapIncludes(i,s.items,N)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let w=Yl.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!u||u.type==="block-scalar"});if(c=w.end,w.found){m&&(v?.type==="block-map"&&!w.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<w.found.offset-1024&&n(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(i,v,w,n):t(i,c,p,null,w,n);i.schema.compat&&Xl.flowIndentCheck(r.indent,v,n),c=k.range[2];let S=new Kl.Pair(N,k);i.options.keepSourceTokens&&(S.srcToken=d),s.items.push(S)}else{m&&n(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(N.comment?N.comment+=`
68
+ `+w.comment:N.comment=w.comment);let k=new Kl.Pair(N);i.options.keepSourceTokens&&(k.srcToken=d),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Zl.resolveBlockMap=Xm});var iu=y(tu=>{"use strict";var Qm=Ke(),Zm=Ri(),ev=go();function tv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Qm.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:d,value:f}of r.items){let u=Zm.resolveProps(d,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||f)f?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=f?e(i,f,u,n):t(i,u.end,d,null,u,n);i.schema.compat&&ev.flowIndentCheck(r.indent,f,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}tu.resolveBlockSeq=tv});var jt=y(ru=>{"use strict";function iv(e,t,i,r){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":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=c.substring(1)||" ";n?n+=o+d:n=d,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}ru.resolveEnd=iv});var su=y(ou=>{"use strict";var rv=P(),nv=Je(),nu=Ue(),av=Ke(),ov=jt(),au=Ri(),sv=an(),cv=wo(),yo="Block collections are not allowed within flow collections",No=e=>e&&(e.type==="block-map"||e.type==="block-seq");function lv({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?nu.YAMLMap:av.YAMLSeq),l=new c(i.schema);l.flow=!0;let d=i.atRoot;d&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let f=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let g=r.items[m],{start:N,key:w,sep:k,value:S}=g,E=au.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:w??k?.[0],offset:f,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){m===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
+ `+E.comment:l.comment=E.comment),f=E.end;continue}!o&&i.options.strict&&sv.containsNewline(w)&&n(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let C="";e:for(let b of N)switch(b.type){case"comma":case"space":break;case"comment":C=b.source.substring(1);break e;default:break e}if(C){let b=l.items[l.items.length-1];rv.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
70
+ `+C:b.comment=C,E.comment=E.comment.substring(C.length+1)}}if(!o&&!k&&!E.found){let C=S?e(i,S,E,n):t(i,E.end,k,null,E,n);l.items.push(C),f=C.range[2],No(S)&&n(C.range,"BLOCK_IN_FLOW",yo)}else{i.atKey=!0;let C=E.end,b=w?e(i,w,E,n):t(i,C,N,null,E,n);No(w)&&n(b.range,"BLOCK_IN_FLOW",yo),i.atKey=!1;let $=au.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:b.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if($.found){if(!o&&!E.found&&i.options.strict){if(k)for(let O of k){if(O===$.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<$.found.offset-1024&&n($.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n($.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Fe=S?e(i,S,$,n):$.found?t(i,$.end,k,null,$,n):null;Fe?No(S)&&n(Fe.range,"BLOCK_IN_FLOW",yo):$.comment&&(b.comment?b.comment+=`
71
+ `+$.comment:b.comment=$.comment);let kt=new nv.Pair(b,Fe);if(i.options.keepSourceTokens&&(kt.srcToken=g),o){let O=l;cv.mapIncludes(i,O.items,b)&&n(C,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(kt)}else{let O=new nu.YAMLMap(i.schema);O.flow=!0,O.items.push(kt);let rc=(Fe??b).range;O.range=[b.range[0],rc[1],rc[2]],l.items.push(O)}f=Fe?Fe.range[2]:$.end}}let u=o?"}":"]",[p,...v]=r.end,h=f;if(p?.source===u)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),g=d?`${m} must end with a ${u}`:`${m} in block collection must be sufficiently indented and end with a ${u}`;n(f,d?"MISSING_CHAR":"BAD_INDENT",g),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=ov.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
+ `+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}ou.resolveFlowCollection=lv});var lu=y(cu=>{"use strict";var uv=P(),dv=I(),fv=Ue(),hv=Ke(),pv=eu(),mv=iu(),vv=su();function bo(e,t,i,r,n,a){let o=i.type==="block-map"?pv.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?mv.resolveBlockSeq(e,t,i,r,a):vv.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function gv(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(i.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=r,v=u&&a?u.offset>a.offset?u:a:u??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===fv.YAMLMap.tagName&&s==="map"||o===hv.YAMLSeq.tagName&&s==="seq")return bo(e,t,i,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),bo(e,t,i,n,o)}let l=bo(e,t,i,n,o,c),d=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,f=uv.isNode(d)?d:new dv.Scalar(d);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}cu.composeCollection=gv});var So=y(uu=>{"use strict";var ko=I();function wv(e,t,i){let r=t.offset,n=yv(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?ko.Scalar.BLOCK_FOLDED:ko.Scalar.BLOCK_LITERAL,o=t.source?Nv(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,d=0;for(let h=0;h<s;++h){let[m,g]=o[h];if(g===""||g==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),d=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+g.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let f="",u="",p=!1;for(let h=0;h<d;++h)f+=o[h][0].slice(c)+`
74
+ `;for(let h=d;h<s;++h){let[m,g]=o[h];l+=m.length+g.length+1;let N=g[g.length-1]==="\r";if(N&&(g=g.slice(0,-1)),g&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-g.length-(N?2:1),"BAD_INDENT",k),m=""}a===ko.Scalar.BLOCK_LITERAL?(f+=u+m.slice(c)+g,u=`
75
+ `):m.length>c||g[0]===" "?(u===" "?u=`
76
+ `:!p&&u===`
77
+ `&&(u=`
78
+
79
+ `),f+=u+m.slice(c)+g,u=`
80
+ `,p=!0):g===""?u===`
81
81
  `?f+=`
82
- `:d=`
83
- `:(f+=d+w,d=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)f+=`
82
+ `:u=`
83
+ `:(f+=u+g,u=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)f+=`
84
84
  `+o[h][0].slice(c);f[f.length-1]!==`
85
85
  `&&(f+=`
86
86
  `);break;default:f+=`
87
- `}let m=n+r.length+t.source.length;return{value:f,type:a,comment:r.comment,range:[n,m,m]}}function Cb({offset:e,props:t},i,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=t[0],a=r[0],o=0,s="",c=-1;for(let d=1;d<r.length;++d){let p=r[d];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=e+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,u="",f=r.length;for(let d=1;d<t.length;++d){let p=t[d];switch(p.type){case"space":l=!0;case"newline":f+=p.source.length;break;case"comment":i&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=p.source.length,u=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),f+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:f}}function Rb(e){let t=e.split(/\n( *)/),i=t[0],n=i.match(/^( *)/),a=[n?.[1]?[n[1],i.slice(n[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}nh.resolveBlockScalar=Eb});var kc=R(ah=>{"use strict";var bc=ne(),Pb=Di();function Ab(e,t,i){let{offset:n,type:r,source:a,end:o}=e,s,c,l=(d,p,m)=>i(n+d,p,m);switch(r){case"scalar":s=bc.Scalar.PLAIN,c=xb(a,l);break;case"single-quoted-scalar":s=bc.Scalar.QUOTE_SINGLE,c=Tb(a,l);break;case"double-quoted-scalar":s=bc.Scalar.QUOTE_DOUBLE,c=Ib(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let u=n+a.length,f=Pb.resolveEnd(o,u,t,i);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function xb(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),rh(e)}function Tb(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),rh(e.slice(1,-1)).replace(/''/g,"'")}function rh(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=r+n.length+t.source.length;return{value:f,type:a,comment:n.comment,range:[r,v,v]}}function yv({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let u=1;u<n.length;++u){let p=n[u];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+u)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,d="",f=n.length;for(let u=1;u<t.length;++u){let p=t[u];switch(p.type){case"space":l=!0;case"newline":f+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),f+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:d,length:f}}function Nv(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}uu.resolveBlockScalar=wv});var Po=y(fu=>{"use strict";var Eo=I(),bv=jt();function kv(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(u,p,v)=>i(r+u,p,v);switch(n){case"scalar":s=Eo.Scalar.PLAIN,c=Sv(a,l);break;case"single-quoted-scalar":s=Eo.Scalar.QUOTE_SINGLE,c=Ev(a,l);break;case"double-quoted-scalar":s=Eo.Scalar.QUOTE_DOUBLE,c=Pv(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let d=r+a.length,f=bv.resolveEnd(o,d,t,i);return{value:c,type:s,comment:f.comment,range:[r,d,f.offset]}}function Sv(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),du(e)}function Ev(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),du(e.slice(1,-1)).replace(/''/g,"'")}function du(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
- `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let r=n[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;n=i.exec(e);)n[1]===""?a===`
90
- `?r+=a:a=`
91
- `:(r+=a+n[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(e),r+a+(n?.[1]??"")}function Ib(e,t){let i="";for(let n=1;n<e.length-1;++n){let r=e[n];if(!(r==="\r"&&e[n+1]===`
92
- `))if(r===`
93
- `){let{fold:a,offset:o}=_b(e,n);i+=a,n=o}else if(r==="\\"){let a=e[++n],o=Ob[a];if(o)i+=o;else if(a===`
94
- `)for(a=e[n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="\r"&&e[n+1]===`
95
- `)for(a=e[++n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=jb(e,n+1,s,t),n+=s}else{let s=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(r===" "||r===" "){let a=n,o=e[n+1];for(;o===" "||o===" ";)o=e[++n+1];o!==`
96
- `&&!(o==="\r"&&e[n+2]===`
97
- `)&&(i+=n>a?e.slice(a,n+1):r)}else i+=r}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function _b(e,t){let i="",n=e[t+1];for(;(n===" "||n===" "||n===`
98
- `||n==="\r")&&!(n==="\r"&&e[t+2]!==`
99
- `);)n===`
89
+ `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
90
+ `?n+=a:a=`
91
+ `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function Pv(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
92
+ `))if(n===`
93
+ `){let{fold:a,offset:o}=xv(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Rv[a];if(o)i+=o;else if(a===`
94
+ `)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
95
+ `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=Cv(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
96
+ `&&!(o==="\r"&&e[r+2]===`
97
+ `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function xv(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
98
+ `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
99
+ `);)r===`
100
100
  `&&(i+=`
101
- `),t+=1,n=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Ob={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function jb(e,t,i,n){let r=e.substr(t,i),o=r.length===i&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}ah.resolveFlowScalar=Ab});var ch=R(sh=>{"use strict";var ui=F(),oh=ne(),$b=Nc(),Hb=kc();function Fb(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?$b.resolveBlockScalar(e,t,n):Hb.resolveFlowScalar(t,e.options.strict,n),c=i?e.directives.tagName(i.source,f=>n(i,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ui.SCALAR]:c?l=Lb(e.schema,r,c,i,n):t.type==="scalar"?l=Mb(e,r,t,n):l=e.schema[ui.SCALAR];let u;try{let f=l.resolve(r,d=>n(i??t,"TAG_RESOLVE_FAILED",d),e.options);u=ui.isScalar(f)?f:new oh.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(i??t,"TAG_RESOLVE_FAILED",d),u=new oh.Scalar(r)}return u.range=s,u.source=r,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Lb(e,t,i,n,r){if(i==="!")return e[ui.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)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[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[ui.SCALAR])}function Mb({atKey:e,directives:t,schema:i},n,r,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||i[ui.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[ui.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(r,"TAG_RESOLVE_FAILED",u,!0)}}return o}sh.composeScalar=Fb});var uh=R(lh=>{"use strict";function Db(e,t,i){if(t){i??(i=t.length);for(let n=i-1;n>=0;--n){let r=t[n];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++n];r?.type==="space";)e+=r.source.length,r=t[++n];break}}return e}lh.emptyScalarPosition=Db});var hh=R(Ec=>{"use strict";var Bb=En(),qb=F(),Vb=ih(),fh=ch(),Wb=Di(),zb=uh(),Jb={composeNode:dh,composeEmptyNode:Sc};function dh(e,t,i,n){let r=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=Gb(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=fh.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Vb.composeCollection(Jb,e,t,i,n),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);n(t,"RESOURCE_EXHAUSTION",d)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=Sc(e,t.offset,void 0,null,i,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!qb.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Sc(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:zb.emptyScalarPosition(t,i,n),indent:-1,source:""},f=fh.composeScalar(e,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Gb({options:e},{offset:t,source:i,end:n},r){let a=new Bb.Alias(i.substring(1));a.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&r(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Wb.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ec.composeEmptyNode=Sc;Ec.composeNode=dh});var vh=R(mh=>{"use strict";var Ub=Dn(),ph=hh(),Kb=Di(),Yb=Wn();function Xb(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new Ub.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Yb.resolveProps(n,{indicator:"doc-start",next:r??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?ph.composeNode(l,r,u,o):ph.composeEmptyNode(l,u.end,n,null,u,o);let f=c.contents.range[2],d=Kb.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[i,f,d.offset],c}mh.composeDoc=Xb});var Rc=R(yh=>{"use strict";var Qb=Jr("process"),Zb=fs(),ek=Dn(),zn=Vn(),gh=F(),tk=vh(),ik=Di();function Jn(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:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function wh(e){let t="",i=!1,n=!1;for(let r=0;r<e.length;++r){let a=e[r];switch(a[0]){case"#":t+=(t===""?"":n?`
101
+ `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Rv={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Cv(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}fu.resolveFlowScalar=kv});var mu=y(pu=>{"use strict";var ct=P(),hu=I(),Av=So(),_v=Po();function Tv(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Av.resolveBlockScalar(e,t,r):_v.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,f=>r(i,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ct.SCALAR]:c?l=Iv(e.schema,n,c,i,r):t.type==="scalar"?l=jv(e,n,t,r):l=e.schema[ct.SCALAR];let d;try{let f=l.resolve(n,u=>r(i??t,"TAG_RESOLVE_FAILED",u),e.options);d=ct.isScalar(f)?f:new hu.Scalar(f)}catch(f){let u=f instanceof Error?f.message:String(f);r(i??t,"TAG_RESOLVE_FAILED",u),d=new hu.Scalar(n)}return d.range=s,d.source=n,a&&(d.type=a),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Iv(e,t,i,r,n){if(i==="!")return e[ct.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)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[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[ct.SCALAR])}function jv({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[ct.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[ct.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),d=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}pu.composeScalar=Tv});var gu=y(vu=>{"use strict";function $v(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}vu.emptyScalarPosition=$v});var Nu=y(Ro=>{"use strict";var Ov=si(),Hv=P(),Dv=lu(),wu=mu(),Bv=jt(),Lv=gu(),Fv={composeNode:yu,composeEmptyNode:xo};function yu(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,d=!0;switch(t.type){case"alias":l=Mv(e,t,r),(s||c)&&r(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=wu.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Dv.composeCollection(Fv,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(f){let u=f instanceof Error?f.message:String(f);r(t,"RESOURCE_EXHAUSTION",u)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",f),d=!1}}return l??(l=xo(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Hv.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(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&&d&&(l.srcToken=t),l}function xo(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let d={type:"scalar",offset:Lv.emptyScalarPosition(t,i,r),indent:-1,source:""},f=wu.composeScalar(e,d,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Mv({options:e},{offset:t,source:i,end:r},n){let a=new Ov.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Bv.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ro.composeEmptyNode=xo;Ro.composeNode=yu});var Su=y(ku=>{"use strict";var Vv=Si(),bu=Nu(),qv=jt(),Wv=Ri();function zv(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Vv.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=Wv.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?bu.composeNode(l,n,d,o):bu.composeEmptyNode(l,d.end,r,null,d,o);let f=c.contents.range[2],u=qv.resolveEnd(a,f,!1,o);return u.comment&&(c.comment=u.comment),c.range=[i,f,u.offset],c}ku.composeDoc=zv});var Ao=y(xu=>{"use strict";var Jv=dr("process"),Gv=ha(),Uv=Si(),Ci=xi(),Eu=P(),Kv=Su(),Yv=jt();function Ai(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:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Pu(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),i=!0,n=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),i=!1;break;default:i||(n=!0),i=!1}}return{comment:t,afterEmptyLine:n}}var Cc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=Jn(i);a?this.warnings.push(new zn.YAMLWarning(o,n,r)):this.errors.push(new zn.YAMLParseError(o,n,r))},this.directives=new Zb.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=wh(this.prelude);if(n){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
- ${n}`:n;else if(r||t.directives.docStart||!a)t.commentBefore=n;else if(gh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];gh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
107
- ${s}`:n}else{let o=a.commentBefore;a.commentBefore=o?`${n}
108
- ${o}`:n}}if(i){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:wh(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,n=-1){for(let r of t)yield*this.next(r);yield*this.end(i,n)}*next(t){switch(Qb.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,n,r)=>{let a=Jn(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=tk.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new zn.YAMLParseError(Jn(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new zn.YAMLParseError(Jn(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=ik.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
109
- ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new zn.YAMLParseError(Jn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),r=new ek.Document(void 0,n);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,i,i],this.decorate(r,!1),yield r}}};yh.Composer=Cc});var kh=R(Fa=>{"use strict";var nk=Nc(),rk=kc(),ak=Vn(),Nh=xn();function ok(e,t=!0,i){if(e){let n=(r,a,o)=>{let s=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(i)i(s,a,o);else throw new ak.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return rk.resolveFlowScalar(e,t,n);case"block-scalar":return nk.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function sk(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=Nh.stringifyString({type:o,value:e},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
105
+ `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Co=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Ai(i);a?this.warnings.push(new Ci.YAMLWarning(o,r,n)):this.errors.push(new Ci.YAMLParseError(o,r,n))},this.directives=new Gv.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Pu(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
+ ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Eu.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Eu.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
107
+ ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
108
+ ${o}`:r}}if(i){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:Pu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(Jv.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Ai(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=Kv.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Ci.YAMLParseError(Ai(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Ci.YAMLParseError(Ai(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Yv.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
+ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Ci.YAMLParseError(Ai(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new Uv.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};xu.Composer=Co});var Au=y(on=>{"use strict";var Xv=So(),Qv=Po(),Zv=xi(),Ru=fi();function eg(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new Zv.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Qv.resolveFlowScalar(e,t,r);case"block-scalar":return Xv.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function tg(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Ru.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
- `),u=s.substring(0,l),f=s.substring(l+1)+`
112
- `,d=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return bh(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
113
- `}),{type:"block-scalar",offset:a,indent:n,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function ck(e,t,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Nh.stringifyString({type:o,value:t},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":lk(e,c);break;case'"':Pc(e,c,"double-quoted-scalar");break;case"'":Pc(e,c,"single-quoted-scalar");break;default:Pc(e,c,"scalar")}}function lk(e,t){let i=t.indexOf(`
114
- `),n=t.substring(0,i),r=t.substring(i+1)+`
115
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,e.source=r}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];bh(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:r})}}function bh(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Pc(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),r=t.length;e.props[0].type==="block-scalar-header"&&(r-=e.props[0].source.length);for(let a of n)a.offset+=r;delete e.props,Object.assign(e,{type:i,source:t,end:n});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:i,source:t,end:[r]});break}default:{let n="indent"in e?e.indent:-1,r="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:i,indent:n,source:t,end:r})}}}Fa.createScalarToken=sk;Fa.resolveAsScalar=ok;Fa.setScalarValue=ck});var Eh=R(Sh=>{"use strict";var uk=e=>"type"in e?Ma(e):La(e);function Ma(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Ma(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=La(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=La(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=La(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function La({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=Ma(t)),i)for(let a of i)r+=a.source;return n&&(r+=Ma(n)),r}Sh.stringify=uk});var Ah=R(Ph=>{"use strict";var Ac=Symbol("break visit"),fk=Symbol("skip children"),Ch=Symbol("remove item");function fi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Rh(Object.freeze([]),e,t)}fi.BREAK=Ac;fi.SKIP=fk;fi.REMOVE=Ch;fi.itemAtPath=(e,t)=>{let i=e;for(let[n,r]of t){let a=i?.[n];if(a&&"items"in a)i=a.items[r];else return}return i};fi.parentCollection=(e,t)=>{let i=fi.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],r=i?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Rh(e,t,i){let n=i(t,e);if(typeof n=="symbol")return n;for(let r of["key","value"]){let a=t[r];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Rh(Object.freeze(e.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Ac)return Ac;s===Ch&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}Ph.visit=fi});var Da=R(Re=>{"use strict";var xc=kh(),dk=Eh(),hk=Ah(),Tc="\uFEFF",Ic="",_c="",Oc="",pk=e=>!!e&&"items"in e,mk=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function vk(e){switch(e){case Tc:return"<BOM>";case Ic:return"<DOC>";case _c:return"<FLOW_END>";case Oc:return"<SCALAR>";default:return JSON.stringify(e)}}function gk(e){switch(e){case Tc:return"byte-order-mark";case Ic:return"doc-mode";case _c:return"flow-error-end";case Oc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
111
+ `),d=s.substring(0,l),f=s.substring(l+1)+`
112
+ `,u=[{type:"block-scalar-header",offset:a,indent:r,source:d}];return Cu(u,c)||u.push({type:"newline",offset:-1,indent:r,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:r,props:u,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function ig(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&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=Ru.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">":rg(e,c);break;case'"':_o(e,c,"double-quoted-scalar");break;case"'":_o(e,c,"single-quoted-scalar");break;default:_o(e,c,"scalar")}}function rg(e,t){let i=t.indexOf(`
114
+ `),r=t.substring(0,i),n=t.substring(i+1)+`
115
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,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:r}];Cu(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Cu(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function _o(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="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:i,indent:r,source:t,end:n})}}}on.createScalarToken=tg;on.resolveAsScalar=eg;on.setScalarValue=ig});var Tu=y(_u=>{"use strict";var ng=e=>"type"in e?cn(e):sn(e);function cn(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=cn(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=sn(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=sn(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=sn(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function sn({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=cn(t)),i)for(let a of i)n+=a.source;return r&&(n+=cn(r)),n}_u.stringify=ng});var Ou=y($u=>{"use strict";var To=Symbol("break visit"),ag=Symbol("skip children"),Iu=Symbol("remove item");function lt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),ju(Object.freeze([]),e,t)}lt.BREAK=To;lt.SKIP=ag;lt.REMOVE=Iu;lt.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};lt.parentCollection=(e,t)=>{let i=lt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function ju(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;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=ju(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===To)return To;s===Iu&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}$u.visit=lt});var ln=y(Q=>{"use strict";var Io=Au(),og=Tu(),sg=Ou(),jo="\uFEFF",$o="",Oo="",Ho="",cg=e=>!!e&&"items"in e,lg=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function ug(e){switch(e){case jo:return"<BOM>";case $o:return"<DOC>";case Oo:return"<FLOW_END>";case Ho:return"<SCALAR>";default:return JSON.stringify(e)}}function dg(e){switch(e){case jo:return"byte-order-mark";case $o:return"doc-mode";case Oo:return"flow-error-end";case Ho:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(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}Re.createScalarToken=xc.createScalarToken;Re.resolveAsScalar=xc.resolveAsScalar;Re.setScalarValue=xc.setScalarValue;Re.stringify=dk.stringify;Re.visit=hk.visit;Re.BOM=Tc;Re.DOCUMENT=Ic;Re.FLOW_END=_c;Re.SCALAR=Oc;Re.isCollection=pk;Re.isScalar=mk;Re.prettyToken=vk;Re.tokenType=gk});var Hc=R(Th=>{"use strict";var Gn=Da();function Je(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var xh=new Set("0123456789ABCDEFabcdef"),wk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ba=new Set(",[]{}"),yk=new Set(` ,[]{}
121
- \r `),jc=e=>!e||yk.has(e),$c=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,i=!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=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Q.createScalarToken=Io.createScalarToken;Q.resolveAsScalar=Io.resolveAsScalar;Q.setScalarValue=Io.setScalarValue;Q.stringify=og.stringify;Q.visit=sg.visit;Q.BOM=jo;Q.DOCUMENT=$o;Q.FLOW_END=Oo;Q.SCALAR=Ho;Q.isCollection=cg;Q.isScalar=lg;Q.prettyToken=ug;Q.tokenType=dg});var Lo=y(Du=>{"use strict";var _i=ln();function me(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Hu=new Set("0123456789ABCDEFabcdef"),fg=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),un=new Set(",[]{}"),hg=new Set(` ,[]{}
121
+ \r `),Do=e=>!e||hg.has(e),Bo=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,i=!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=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
122
122
  `?!0:i==="\r"?this.buffer[t+1]===`
123
- `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let n=0;for(;i===" ";)i=this.buffer[++n+t];if(i==="\r"){let r=this.buffer[n+t+1];if(r===`
124
- `||!r&&!this.atEnd)return t+n+1}return i===`
125
- `||n>=this.indentNext||!i&&!this.atEnd?t+n:-1}if(i==="-"||i==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&Je(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Gn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,n=t.indexOf("#");for(;n!==-1;){let a=t[n-1];if(a===" "||a===" "){i=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let r=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield Gn.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 i=this.peek(3);if((i==="---"||i==="...")&&Je(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Je(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Je(i)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);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(jc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,n=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=n=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&r[0]!=="#"||n===0&&(r.startsWith("---")||r.startsWith("..."))&&Je(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Gn.FLOW_END,yield*this.parseLineStart();let a=0;for(;r[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),r[a]){case void 0:return"flow";case"#":return yield*this.pushCount(r.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(jc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Je(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),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let n=this.buffer.substring(0,i),r=n.indexOf(`
127
- `,this.pos);if(r!==-1){for(;r!==-1;){let a=this.continueScalar(r+1);if(a===-1)break;r=n.indexOf(`
128
- `,a)}r!==-1&&(i=r-(n[r-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Je(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":i+=1;break;case`
123
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
124
+ `||!n&&!this.atEnd)return t+r+1}return i===`
125
+ `||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&me(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===_i.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield _i.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 i=this.peek(3);if((i==="---"||i==="...")&&me(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!me(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&me(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);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(Do),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&me(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield _i.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(Do),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||me(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),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
127
+ `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
128
+ `,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>me(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
129
129
  `:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
- `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
- `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(n=this.buffer[r];n===" ";)n=this.buffer[++r];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
132
- `;)n=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield Gn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===":"){let a=this.buffer[n+1];if(Je(a)||t&&Ba.has(a))break;i=n}else if(Je(r)){let a=this.buffer[n+1];if(r==="\r"&&(a===`
134
- `?(n+=1,r=`
135
- `,a=this.buffer[n+1]):i=n),a==="#"||t&&Ba.has(a))break;if(r===`
136
- `){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&Ba.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Gn.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(i&&(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(jc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(Je(n)||i&&Ba.has(n)){i?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,i=this.buffer[t];for(;!Je(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(wk.has(i))i=this.buffer[++t];else if(i==="%"&&xh.has(this.buffer[t+1])&&xh.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
130
+ `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
+ `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
132
+ `;)r=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===`
133
+ `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield _i.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(me(a)||t&&un.has(a))break;i=r}else if(me(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
134
+ `?(r+=1,n=`
135
+ `,a=this.buffer[r+1]):i=r),a==="#"||t&&un.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&un.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield _i.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(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(Do),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(me(r)||i&&un.has(r)){i?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,i=this.buffer[t];for(;!me(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(fg.has(i))i=this.buffer[++t];else if(i==="%"&&Hu.has(this.buffer[t+1])&&Hu.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,n;do n=this.buffer[++i];while(n===" "||t&&n===" ");let r=i-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(t){let i=this.pos,n=this.buffer[i];for(;!t(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Th.Lexer=$c});var Lc=R(Ih=>{"use strict";var Fc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,n=this.lineStarts.length;for(;i<n;){let a=i+n>>1;this.lineStarts[a]<t?i=a+1:n=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let r=this.lineStarts[i-1];return{line:i,col:t-r+1}}}};Ih.LineCounter=Fc});var Dc=R(Hh=>{"use strict";var Nk=Jr("process"),_h=Da(),bk=Hc();function Dt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Oh(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 $h(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 qa(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 Va(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function jh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Dt(t.start,"explicit-key-ind")&&!Dt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,$h(t.value)?t.value.end?Va(t.value.end,t.sep):t.value.end=t.sep:Va(t.start,t.sep),delete t.sep)}var Mc=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 bk.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,i))yield*this.next(n);i||(yield*this.end())}*next(t){if(this.source=t,Nk.env.LOG_TOKENS&&console.log("|",_h.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=_h.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let n=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in n?n.indent:0:i.type==="flow-collection"&&n.type==="document"&&(i.indent=0),i.type==="flow-collection"&&jh(i),n.type){case"document":n.value=i;break;case"block-scalar":n.props.push(i);break;case"block-map":{let r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=i;else{Object.assign(r,{key:i,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:i}):r.value=i;break}case"flow-collection":{let r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:i,sep:[]}):r.sep?r.value=i:Object.assign(r,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let r=i.items[i.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Oh(r.start)===-1&&(i.indent===0||r.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(n.type==="document"?n.end=r.start:n.items.push({start:r.start}),i.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":{Oh(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 i=this.startBlockValue(t);i?this.stack.push(i):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 i=qa(this.peek(2)),n=Bi(i),r;t.end?(r=t.end,r.push(this.sourceToken),delete t.end):r=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:r}]};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 i=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Du.Lexer=Bo});var Mo=y(Bu=>{"use strict";var Fo=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Bu.LineCounter=Fo});var qo=y(qu=>{"use strict";var pg=dr("process"),Lu=ln(),mg=Lo();function Ye(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Fu(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 Vu(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 dn(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 $t(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 fn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function Mu(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ye(t.start,"explicit-key-ind")&&!Ye(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Vu(t.value)?t.value.end?fn(t.value.end,t.sep):t.value.end=t.sep:fn(t.start,t.sep),delete t.sep)}var Vo=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 mg.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,pg.env.LOG_TOKENS&&console.log("|",Lu.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Lu.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){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 r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,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 i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Mu(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Fu(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.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":{Fu(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 i=this.startBlockValue(t);i?this.stack.push(i):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 i=dn(this.peek(2)),r=$t(i),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:r,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 i=this.source.indexOf(`
139
139
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
140
- `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Va(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,r=n&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.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=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):r||i.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(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Dt(i.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($h(i.key)&&!Dt(i.sep,"newline")){let o=Bi(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Dt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Bi(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||r?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Dt(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{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);r||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Dt(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Va(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Dt(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:r,sep:[]}):i.sep?this.stack.push(r):Object.assign(i,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=qa(n),a=Bi(r);jh(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 i=this.source.indexOf(`
140
+ `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.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=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.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(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ye(i.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(Vu(i.key)&&!Ye(i.sep,"newline")){let o=$t(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Ye(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=$t(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Ye(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{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||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Ye(i.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 r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fn(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Ye(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=dn(r),a=$t(n);Mu(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 i=this.source.indexOf(`
141
141
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
142
- `,i)+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 i=qa(t),n=Bi(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=qa(t),n=Bi(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Hh.Parser=Mc});var Bh=R(Kn=>{"use strict";var Fh=Rc(),kk=Dn(),Un=Vn(),Sk=Es(),Ek=F(),Ck=Lc(),Lh=Dc();function Mh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Ck.LineCounter||null,prettyErrors:t}}function Rk(e,t={}){let{lineCounter:i,prettyErrors:n}=Mh(t),r=new Lh.Parser(i?.addNewLine),a=new Fh.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(Un.prettifyError(e,i)),s.warnings.forEach(Un.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Dh(e,t={}){let{lineCounter:i,prettyErrors:n}=Mh(t),r=new Lh.Parser(i?.addNewLine),a=new Fh.Composer(t),o=null;for(let s of a.compose(r.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Un.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Un.prettifyError(e,i)),o.warnings.forEach(Un.prettifyError(e,i))),o}function Pk(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Dh(e,i);if(!r)return null;if(r.warnings.forEach(a=>Sk.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Ak(e,t,i){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=i??t??{};if(!r)return}return Ek.isDocument(e)&&!n?e.toString(i):new kk.Document(e,n,i).toString(i)}Kn.parse=Pk;Kn.parseAllDocuments=Rk;Kn.parseDocument=Dh;Kn.stringify=Ak});var za=R(q=>{"use strict";var xk=Rc(),Tk=Dn(),Ik=oc(),Bc=Vn(),_k=En(),Bt=F(),Ok=Ht(),jk=ne(),$k=Lt(),Hk=Mt(),Fk=Da(),Lk=Hc(),Mk=Lc(),Dk=Dc(),Wa=Bh(),qh=Nn();q.Composer=xk.Composer;q.Document=Tk.Document;q.Schema=Ik.Schema;q.YAMLError=Bc.YAMLError;q.YAMLParseError=Bc.YAMLParseError;q.YAMLWarning=Bc.YAMLWarning;q.Alias=_k.Alias;q.isAlias=Bt.isAlias;q.isCollection=Bt.isCollection;q.isDocument=Bt.isDocument;q.isMap=Bt.isMap;q.isNode=Bt.isNode;q.isPair=Bt.isPair;q.isScalar=Bt.isScalar;q.isSeq=Bt.isSeq;q.Pair=Ok.Pair;q.Scalar=jk.Scalar;q.YAMLMap=$k.YAMLMap;q.YAMLSeq=Hk.YAMLSeq;q.CST=Fk;q.Lexer=Lk.Lexer;q.LineCounter=Mk.LineCounter;q.Parser=Dk.Parser;q.parse=Wa.parse;q.parseAllDocuments=Wa.parseAllDocuments;q.parseDocument=Wa.parseDocument;q.stringify=Wa.stringify;q.visit=qh.visit;q.visitAsync=qh.visitAsync});import{randomUUID as Mx}from"crypto";import{promises as Dx}from"fs";import wn from"path";import{isDeepStrictEqual as Bx}from"util";import{createHash as fw}from"crypto";function Ku(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Yu(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Yu(e[t]);return Object.freeze(e)}function It(e){return Yu(structuredClone(e))}function os(e,t,i,n){return e.resolveStep({pkg:It(t),state:It(i),context:It(n)})}function Xu(e,t,i,n,r,a){return e.resolveNext({pkg:It(t),state:It(i),step:It(n),outcome:It(r),context:It(a)})}function dw(e,t,i){return fw("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function ss(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Qu(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=os(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=ss(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:dw(s.runId,s.iteration,o.id),stepId:o.id};return hw(e,s,c,i)}function hw(e,t,i,n){let r=Ku(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function Zu(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?os(n,e,t,r):void 0,o=a?ss(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Xu(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!ss(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Dl}from"fs";import $m from"path";var xo=as(za(),1);import{promises as Rm}from"fs";import Nt from"path";import{createHash as Wk}from"node:crypto";import{promises as Ge}from"node:fs";import Me from"node:path";import{TextDecoder as zk}from"node:util";import qc from"path";var Bk=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),qk=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Vk(e){return e.toLowerCase().startsWith(".env")}function ot(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Vk(n))?"environment-file":i.some(n=>qk.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Bk.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Vh(e,t){let i=ot(t);if(i)return i;let n=qc.resolve(e.projectRoot,...t.split("/")),r=qc.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===qc.resolve(e.configFile)?"native-runtime":null}function qt(e){return e!==0&&e!==0n&&e!=="0"}function me(e,t){return qt(e.dev)&&qt(t.dev)&&qt(e.ino)&&qt(t.ino)}function j(e,t){let i=qt(e.dev)&&qt(t.dev);if(i&&e.dev!==t.dev)return!1;let n=qt(e.ino)&&qt(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var Yn=1024*1024;function Vc(e,t){let i=Me.relative(e,t);return i===""||!Me.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Me.sep}`)}function Jk(e){let t=Me.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Me.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 i=e.toLowerCase(),n=ot(e);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function Gk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Uk(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ja(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return me(i,n)?j(i,n):j(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Wh(e){let t=await Ge.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ge.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Kk(e,t){let i=Me.resolve(e),n=Me.resolve(t);if(!Vc(i,n))throw new Error("Native artifact path is outside its root");let r=[await Wh(i)],a=i;for(let o of Me.relative(i,n).split(Me.sep).filter(Boolean)){a=Me.join(a,o);let s=await Wh(a);if(!Vc(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function zh(e){for(let t of e){let i=await Ge.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Uk(t,i)||await Ge.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ye(e){let t=Jk(e.ref),i=Gk(e.maxBytes??Yn),n=Me.resolve(e.root,...t.split("/")),r=await Kk(e.root,Me.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Ge.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Ge.realpath(n);if(!Vc(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ge.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ge.lstat(n),Ge.realpath(n)]);if(await zh(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ja(a,c)||!Ja(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let b=i+1-d,N=await s.read(p,0,Math.min(p.length,b),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),Ge.lstat(n),Ge.realpath(n)]);if(await zh(r),!h.isFile()||h.isSymbolicLink()||v!==o||!Ja(c,m)||!Ja(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(f,d),y;try{y=new zk("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:d,hash:Wk("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as Yk}from"crypto";import{promises as ve}from"fs";import Ue from"path";function zc(e,t){let i=Ue.relative(e,t);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function Xk(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Wc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return me(i,n)?j(i,n):j(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Jh(e){let t=await ve.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 ve.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Xn(e){for(let t of e){let i=await ve.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Xk(t,i)||await ve.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Qk(e,t){let i=Ue.resolve(e),n=Ue.resolve(t);if(!zc(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await Jh(i)],a=Ue.relative(i,n).split(Ue.sep).filter(Boolean),o=i;for(let s of a){await Xn(r),o=Ue.join(o,s);try{await ve.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Jh(o);if(!zc(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Xn(r),r}async function Zk(e){let t;try{t=await ve.open(e,"r"),await t.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await t?.close()}}async function Gh(e,t,i={}){let n=Ue.dirname(e),r=i.containedRoot?await Qk(i.containedRoot,n):null;r||await ve.mkdir(n,{recursive:!0});let a=Ue.join(n,`.${Ue.basename(e)}.${Yk()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await ve.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([ve.lstat(a),ve.realpath(a)]);if(await Xn(r),!c.isFile()||c.isSymbolicLink()||!Wc(s,c)||!zc(r[0].realPath,l))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(),!Wc(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),r){await Xn(r);let c=await ve.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Wc(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await ve.link(a,e),await ve.unlink(a)):await ve.rename(a,e),await Zk(n)}catch(c){if(await o?.close(),!r)await ve.rm(a,{force:!0});else try{await Xn(r),await ve.rm(a,{force:!0})}catch{}throw c}}async function vt(e,t,i={}){await Gh(e,t,i)}async function Uh(e,t,i={}){await Gh(e,t,i)}async function Ne(e,t,i={}){await vt(e,JSON.stringify(t,null,2)+`
143
- `,i)}var Gc=as(za(),1);import Ga from"path";var Zn=64*1024,Ua=1024,Ka=64,Uc=5,eS=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Pe={include:["**/*"],exclude:[...eS],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function tS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Ga.posix.isAbsolute(i)||Ga.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function di(e){let t=tS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Yh(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Kc(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||Ga.posix.isAbsolute(n)||Ga.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function Qn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xh(e,t,i){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Ya(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>Ua)throw new Error(`${t} exceeds ${Ua} characters`);let i=0;for(let n=0;n<e.length;n+=1)e[n]==="?"?i+=1:e[n]==="*"&&(i+=1,e[n+1]==="*"&&(n+=1));if(i>Ka)throw new Error(`${t} contains more than ${Ka} wildcard tokens`);return e}function Kh(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>Ya(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function Jc(e,t,i){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function iS(e){if(e===void 0)return{...Pe,include:[...Pe.include],exclude:[...Pe.exclude]};let t=Qn(e,"native.snapshot");return{include:Kh(t.include,"native.snapshot.include",Pe.include),exclude:Kh(t.exclude,"native.snapshot.exclude",Pe.exclude),max_files:Jc(t.max_files,Pe.max_files,"native.snapshot.max_files"),max_total_bytes:Jc(t.max_total_bytes,Pe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Jc(t.max_duration_ms,Pe.max_duration_ms,"native.snapshot.max_duration_ms")}}function nS(e){if(e===void 0)return;let t=Qn(e,"native.pending_root_move"),i=t.id,n=t.from_artifact_root,r=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="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=Qn(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:i,fromArtifactRoot:di(n),toArtifactRoot:di(r),stage:a,...o?{cleanup:o}:{}}}function rS(e,t={}){let i=Qn(e,"native"),n=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Uc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=nS(i.pending_root_move);return{artifact_root:di(n),language:Xh(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:iS(i.snapshot),...s?{pending_root_move:s}:{}}}function aS(e){let t=Qn(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Yh(t.artifact_layout),language:Xh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function oS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function sS(e,t,i,n,r){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!a)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 s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:n,...t?{native:t}:{},...i?{classic:i}:{}}}function er(e,t={}){let i=(0,Gc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=oS(r.ambient_resume),o=r.native===void 0?void 0:rS(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:aS(r.classic),c=sS(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Xa(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:di(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Uc,snapshot:{...Pe,include:[...Pe.include],exclude:[...Pe.exclude]}}}}import{createHash as lS}from"crypto";import{promises as eo}from"fs";import Vt from"path";import{constants as Qa,promises as hi}from"fs";var Ke=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function Yc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Qh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function tr(e){return{dev:e.dev,ino:e.ino,birthtime:Yc(e)}}function Za(e,t){let i=tr(e),n=tr(t);return me(i,n)?j(i,n):j(i,n)&&Yc(e)===Yc(t)&&Qh(e)===Qh(t)&&e.size===t.size}async function pi(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await hi.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Ke("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ke("too-large",`${n} exceeds ${t} bytes`);let o=await hi.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:tr(a)});let s=process.platform==="win32"?Qa.O_RDONLY:Qa.O_RDONLY|Qa.O_NOFOLLOW|Qa.O_NONBLOCK,c;try{c=await hi.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ke("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:r}),hi.lstat(e,{bigint:r}),hi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Za(a,l)||!Za(a,u))throw new Ke("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:tr(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:b}=await c.read(m,0,Math.min(m.length,y),null);if(b===0)break;if(p+=b,p>t)throw new Ke("too-large",`${n} exceeds ${t} bytes`);d.push(Buffer.from(m.subarray(0,b)))}await i.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:r}),hi.lstat(e,{bigint:r}),hi.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!Za(a,h)||!Za(a,v))throw new Ke("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:tr(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:w}}finally{await c.close()}}function cS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Xc(e,t){let i=Vt.relative(e,t);return i===""||!Vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Vt.sep}`)}async function Zh(e,t){let i=Vt.resolve(e),n=await eo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return eo.realpath(i)}async function ep(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=Vt.join(r,i[a]);let o;try{o=await eo.lstat(r)}catch(u){if(cS(u))return{exists:!1,kind:"missing"};throw u}let s=Vt.relative(e,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await eo.realpath(r);if(!Xc(t,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function ir(e,t,i){let n=Kc(t,i.label),r=Vt.resolve(e),a=await Zh(r,i.label),o=n.split("/"),s=Vt.resolve(r,...o);if(!Xc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await ep(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function mi(e,t,i,n){let r=await ir(e,t,{label:n.label,expected:"file"});if(!r.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await Zh(r.projectRoot,n.label);return pi(r.target,i,{...n,verify:async(o,s)=>{if(!Xc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await ep(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var nr=".comet/config.yaml";function uS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Qc(e,t={}){return(await to(e,t)).document}async function fS(e){try{return(await mi(e,nr,Zn,{label:nr})).bytes}catch(t){if(uS(t))return null;throw t}}function dS(e){return e?{exists:!0,sha256:lS("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function to(e,t={}){let i=await fS(e);return{document:i?er(i.toString("utf8"),t):null,identity:dS(i)}}var l_=16*1024;import{promises as qi}from"fs";import G from"path";import gS from"os";var no=".comet/config.yaml";async function tl(e){try{return await qi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wS(e){try{let t=await qi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function rr(e,t){let i=G.relative(e,t);return i===""||!G.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${G.sep}`)}async function ar(e){let t=[],i=e;for(;!await tl(i);){let r=G.dirname(i);if(r===i)break;t.push(G.basename(i)),i=r}let n=await qi.realpath(i);return G.resolve(n,...t.reverse())}async function ip(e){try{return(await qi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ro(e){let t=G.resolve(e);try{(await qi.stat(t)).isDirectory()||(t=G.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=G.resolve(gS.homedir());for(;;){if(!(t===n&&i!==n)){let o=G.join(t,...no.split("/")),s=t===i||await wS(o);if(await tl(o)&&s)return t}if(await tl(G.join(t,".git")))return t;let a=G.dirname(t);if(a===t)return i;t=a}}function ao(e){return di(e)}async function yS(e,t){let i=ao(t),n=G.resolve(e,...i.split("/")),r=await qi.realpath(e),a=await ar(n);if(!rr(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function il(e,t){let i=ao(t),n=await yS(e,i),r=G.join(n,"comet");if(await ip(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ar(n),ar(r)]);if(!rr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:G.resolve(e),configFile:G.join(e,...no.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:G.join(r,"specs"),changesDir:G.join(r,"changes"),archiveDir:G.join(r,"archive"),runtimeDir:G.join(r,"runtime"),locksDir:G.join(r,"runtime","locks"),transactionsDir:G.join(r,"runtime","transactions")}}function U(e,t){return rr(G.resolve(e),G.resolve(t))}async function $(e,t){let i=G.resolve(e),n=G.resolve(t);if(!rr(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await ip(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([ar(i),ar(n)]);if(!rr(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var nl=Pe;var oo=Ya;function bS(e="docs",t="en"){return Xa(e,t)}async function Wt(e){let t=(await Qc(e))?.config??null;return t?.native?t:null}async function Vi(e){let t=await Wt(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 np(e){let t=await ro(e.startPath),i=await Wt(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${no} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?ao(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??bS(n??"docs"),a=await il(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as tE}from"fs";import iE from"path";import{AsyncLocalStorage as kS}from"async_hooks";import{randomUUID as op}from"crypto";import{promises as De}from"fs";import sp from"os";import be from"path";var rp=16*1024,cp=".coordinator",SS=5e3,ap=new kS,so=new Map;function ES(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function CS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function lp(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 rl(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return me(i,n)?j(i,n):j(i,n)&&e.size===t.size}function al(e,t){return rl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function gt(e){let t,i;try{let n=await pi(e,rp,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Ke?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${rp} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:CS(JSON.parse(t.toString("utf8")),e),identity:lp(i)}}async function RS(e){return(await gt(e))?.owner??null}function up(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==sp.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=_S(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function PS(e,t){try{await De.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await De.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ol(e,t){let i=await gt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!al(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await De.mkdir(t,{recursive:!0});let n=be.join(t,`${be.basename(e.file)}.${e.owner.id}.${op()}.removed`);try{await De.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await gt(n);if(!r||r.owner.id!==e.owner.id||!rl(r.identity,e.identity))throw await PS(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await De.rm(n,{force:!0}),"removed"}function fp(e){return{id:op(),pid:process.pid,hostname:sp.hostname(),createdAt:new Date().toISOString(),operation:e}}async function dp(e,t){let i;try{i=await De.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await RS(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
144
- `,"utf8"),await i.sync(),lp(await i.stat({bigint:!0}))}finally{await i.close()}}async function AS(e,t){let i=await $(e.nativeRoot,e.locksDir);await De.mkdir(i,{recursive:!0});let n=await $(e.nativeRoot,be.join(i,cp));await De.mkdir(n,{recursive:!0});let r=fp(t),a=be.join(n,`.${r.id}.tmp`),o=be.join(n,`${r.id}.claim`);try{let s=await dp(a,r);await De.rename(a,o);let c=await gt(o);if(!c||!rl(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await De.rm(a,{force:!0})}}async function xS(e){let t=be.dirname(e.file),i=!1,n=be.basename(e.file);for(let r of await De.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=be.join(t,r.name);if(be.resolve(a)!==be.resolve(e.file))try{let o=await gt(a),s=up(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ol(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function hp(e){let t=await gt(e.file);if(t){if(t.owner.id!==e.owner.id||!al(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ol(t,be.dirname(e.file))}}async function TS(e,t){let i=Date.now()+SS;for(;;){let n=await AS(e,t);if(!await xS(n))return n;if(await hp(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function IS(e){let t=so.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return so.set(e,r),await t,()=>{i(),so.get(e)===r&&so.delete(e)}}async function pp(e,t,i){let n=be.resolve(e.locksDir),r=ap.getStore();if(r?.has(n))return i();let a=await IS(n);try{let o=await TS(e,t),s=new Map(r??[]);return s.set(n,o),await ap.run(s,async()=>{try{return await i()}finally{await hp(o)}})}finally{a()}}async function Wi(e,t,i){return pp(e,`acquire ${t}`,async()=>{let n=await $(e.nativeRoot,e.locksDir);await De.mkdir(n,{recursive:!0});let r=await $(e.nativeRoot,be.join(n,ES(t))),a=fp(i),o=await dp(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function zi(e){await gt(e.file)&&await pp(e,`release ${be.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(!al(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=be.join(e.locksDir,cp);await ol(t,i)})}function _S(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function mp(e){return up(await gt(e))}import{promises as ul}from"fs";import ke from"path";import{TextDecoder as HS}from"util";import{createHash as OS}from"node:crypto";import{constants as co,promises as V}from"node:fs";import Q from"node:path";import{TextDecoder as jS}from"node:util";function je(e,t){let i=Q.relative(e,t);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function vp(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function sl(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function gp(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ji(e,t){return j({...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 Gi(e,t){let i=await V.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await V.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ui(e,t,i){let n=Q.resolve(e),r=Q.resolve(t);if(!je(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Gi(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await ue(a,i),o=Q.join(o,s);let c=await Gi(o,i);if(!je(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ue(a,i),a}async function ue(e,t){for(let i of e){let n=await V.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!sl(i,n)||await V.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function $S(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function re(e){let t=vp(e.maxBytes),i=Q.resolve(e.file),n=await Ui(e.root,Q.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Gi(Q.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ue(n,e.label);let a=await V.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=gp(a),s=await V.realpath(i);if(!je(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>je(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?co.O_RDONLY:co.O_RDONLY|co.O_NOFOLLOW|co.O_NONBLOCK,l=await V.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([V.lstat(i),V.realpath(i)]);if(await ue(n,e.label),await ue(r,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!Ji(o,u)||!Ji(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await $S(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),V.lstat(i),V.realpath(i)]);if(await ue(n,e.label),await ue(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Ji(o,m)||!Ji(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:OS("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function wp(e){let t=await re(e),i;try{i=new jS("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:i}}async function zt(e){let t=await Ui(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await V.readdir(e.directory,{withFileTypes:!0});else{let n=vp(e.maxEntries);i=[];let r=await V.opendir(e.directory);try{for await(let a of r)if(i.push(a),i.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await r.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ue(t,e.label),{entries:i,verify:()=>ue(t,e.label)}}async function or(e){let t=await Ui(e.root,e.directory,e.label);return{verify:()=>ue(t,e.label)}}async function yp(e){let t=Q.resolve(e.file),i=await Ui(e.root,Q.dirname(t),e.label),n=await V.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=gp(n),a=await V.realpath(t);if(!je(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([V.lstat(t),V.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Ji(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ue(i,e.label);let[l,u]=await Promise.all([V.lstat(t),V.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Ji(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await V.rm(t),await ue(i,e.label)}async function vi(e){let t=Q.resolve(e.root),i=Q.resolve(e.directory);if(!je(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await Gi(t,e.label)],r=t;for(let a of Q.relative(t,i).split(Q.sep).filter(Boolean)){await ue(n,e.label),r=Q.join(r,a);try{await V.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Gi(r,e.label);if(!je(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await ue(n,e.label)}async function Np(e){let t=Q.resolve(e.root),i=Q.resolve(e.source),n=Q.resolve(e.target);if(i===n||!je(t,i)||!je(t,n)||je(i,n)||je(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await vi({root:t,directory:Q.dirname(n),label:`${e.label} target parent`});let r=await Ui(t,Q.dirname(i),e.label),a=await Ui(t,Q.dirname(n),e.label),o=await Gi(i,e.label);if(!je(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await V.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ue(r,e.label),ue(a,e.label)]);let s=await V.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!sl(o,s)||await V.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await V.rename(i,n),await Promise.all([ue(r,e.label),ue(a,e.label)]);let c=await V.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!sl(o,c)||!je(r[0].realPath,await V.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await V.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function gi(e){let t=await re({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Uh(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await V.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var FS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),LS=new Set(["id","type","source","target","staged","backup"]),MS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),DS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),BS=new Set(["sequence","timestamp","type","operationId"]),Ep=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Cp=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),qS=256*1024,VS=1024*1024,Rp=16*1024,uo=1024,fl=64*1024*1024,WS=2e4,Pp=new HS("utf-8",{fatal:!0});function cr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function lr(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Yi(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function cl(e,t){if(typeof e!="string"||e.length===0||ke.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function lo(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function bp(e,t){if(cl(e,t),e.includes("\\")||e!==ke.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 zS(e,t){let i=cr(e,`transaction operations[${t}]`);if(lr(i,LS,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);cl(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&cl(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function ur(e){let t=cr(e,"Native Archive transaction journal");if(lr(t,MS,"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"||!Ep.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(!Yi(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(lo(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 i=t.operations.map((s,c)=>{let l=cr(s,`Archive transaction operations[${c}]`);if(lr(l,DS,`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`);bp(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&bp(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&lo(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(lo(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`);lo(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${t.id}`,a=i.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)||i.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 i.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(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/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:i}}function Ap(e){let t=cr(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return ur(t);if(lr(t,FS,"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"||!Ep.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ke.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ke.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(!Yi(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 i=t.operations.map(zS),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function xp(e,t){let i=cr(e,`Native transaction event at line ${t}`);if(lr(i,BS,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Yi(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Cp.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=i.type==="operation-started"||i.type==="operation-completed";if(n&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!n&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function JS(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;n<e.length;n+=1){let r=t[n],a=e[n];if(r==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==r)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[n,r,a,o]of i){if(e.length<=n)continue;let s=e.slice(n,Math.min(n+r,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(r,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Yi(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Yi(e)}function Ki(e,t){return e.length<t.length&&t.startsWith(e)}function GS(e){let t='","operationId":"';if(Ki(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),n=i.indexOf('"');if(n===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let r=i.slice(0,n);return/^[a-z0-9][a-z0-9-]*$/u.test(r)?Ki(i.slice(n),'"}'):!1}function US(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Rp)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Ki(e,i))return!0;if(!e.startsWith(i))return!1;let n=e.slice(i.length),r=n.slice(0,Math.min(24,n.length));if(!JS(r))return!1;if(n.length<24)return!0;if(!Yi(r))return!1;let a='","type":"',o=n.slice(24);if(Ki(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Cp){if(Ki(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(GS(l))return!0}else if(Ki(l,'"}'))return!0}return!1}function KS(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Rp)throw new Error(`Native transaction event at line ${t} is too large`);return xp(JSON.parse(e),t)}function YS(e){let t=e.split(`
145
- `),i=t.at(-1)==="";if(i&&t.pop(),t.length>uo)throw new Error(`Native transaction event log exceeds ${uo} events`);let n=[];for(let r=0;r<t.length;r+=1){let a=r+1,o=t[r],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&r===t.length-1;try{n.push(KS(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&US(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return n}function Tp(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
146
- `)}
147
- `}function XS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ke.join(e.transactionsDir,t)}function Ip(e,t){let i=XS(e,t);return{directory:i,journal:ke.join(i,"transaction.json"),events:ke.join(i,"events.jsonl"),staged:ke.join(i,"staged"),backups:ke.join(i,"backups")}}async function Ye(e,t){let i=Ip(e,t);return await Promise.all(Object.values(i).map(n=>$(e.nativeRoot,n))),i}function QS(e,t){if(t.length===0||ke.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=ke.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!U(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function sr(e,t){return $(e.nativeRoot,QS(e,t))}async function fo(e){try{return await ul.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dl(e,t,i={}){let n=await Ye(e,t);try{await ul.lstat(n.events)}catch(r){if(r.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw r}try{let r=await re({root:e.nativeRoot,file:n.events,maxBytes:VS,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=Pp.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=YS(a),s=Tp(o);return{exists:!0,hash:r.hash,size:r.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:r}):r}}async function kp(e,t,i){let n=await dl(e,t);if(n.exists!==i.exists||n.hash!==i.hash||n.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Jt(e,t,i,n){let r=await Ye(e,t),a=await dl(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await vt(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>kp(e,t,a)}),o;if(a.events.length>=uo)throw new Error(`Native transaction event log ${t} exceeds ${uo} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return xp(s,s.sequence),await ul.mkdir(r.directory,{recursive:!0}),await vt(r.events,Tp([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>kp(e,t,a)}),s}async function ho(e,t,i={}){let n=await Ye(e,t),r=await re({root:e.nativeRoot,file:n.journal,maxBytes:qS,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Pp.decode(r.bytes)),o=Ap(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Xi(e,t,i={}){return(await dl(e,t,i)).events}async function _p(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=Ap({...t,status:i});return await Ne((await Ye(e,t.id)).journal,n),n}async function ll(e,t,i){try{return await re({root:e.nativeRoot,file:t,maxBytes:fl,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Op(e,t,i,n){let r=await ll(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await ll(e,i,`${n} target`);await vi({root:e.nativeRoot,directory:ke.dirname(i),label:`${n} target parent`}),await gi({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:fl,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function ZS(e,t,i){let n=await ll(e,t,i);n&&await yp({root:e.nativeRoot,file:t,maxBytes:fl,expectedHash:n.hash,expectedSize:n.size,label:i})}async function Sp(e,t){if(!t.backup)return;let i=await sr(e,t.target),n=await sr(e,t.backup);!await fo(i)||await fo(n)||await Op(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function eE(e,t){let i=await sr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Sp(e,t),await Op(e,await sr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Sp(e,t),await ZS(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await sr(e,t.source),[r,a]=await Promise.all([fo(n),fo(i)]);if(!r&&a){await(await zt({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:WS})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!r)throw new Error(`Move source does not exist: ${t.source}`);await Np({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function jp(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await _p(e,t,"applying"):t,r=await Xi(e,t.id),a=new Set(r.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of n.operations)a.has(s.id)||(await Jt(e,n.id,"operation-started",s.id),await eE(e,s),await Jt(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await ho(e,n.id),n}async function po(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Jt(e,t.id,i),i==="commit"?_p(e,t,"committed"):t}function wt(e,t){let i=ke.resolve(t);if(!U(e.nativeRoot,i))throw new Error(`Path is outside the Native root: ${t}`);return ke.relative(e.nativeRoot,i).split(ke.sep).join("/")}async function nE(e,t){let i;try{i=await tE.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 r=await ho(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function rE(e,t){let i=Date.now()+5e3,n=iE.join(e.locksDir,"root-move.lock");for(;;)try{return await Wi(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await mp(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function st(e,t,i,n){let r=await rE(e,t);try{if(await Vi(e.projectRoot),await nE(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await zi(r)}}function $p(e){return Number.isSafeInteger(e)&&e>=1}async function Hp(e){if(!$p(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!$p(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as wo}from"crypto";import{spawn as Gp}from"node:child_process";import{promises as Z}from"fs";import H from"path";import{createHash as Fp}from"crypto";import{createReadStream as aE}from"fs";async function hl(e){let t=Fp("sha256");for await(let i of aE(e))t.update(i);return t.digest("hex")}function z(e){return Fp("sha256").update(e).digest("hex")}var mo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Up=1e3,oE=8*1024*1024,sE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cE=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),lE=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),uE=new Set(["schema","include","exclude","hash"]),fE=new Set(["provider","gitSelection","physicalSelection","projection"]),dE=new Set(["provider","selection"]),hE=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),pE=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),mE=new Set(["schema","status","before","after"]),vE=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),gE=new Set(["path","hash","size","type","gitObjectId"]),wE=new Set(["path","size","type","reason"]),yE=new Set(["ref","hash","count"]),NE=new Set(["change-created","legacy-migration","explicit"]),bE=new Set(["file","directory","other"]),kE=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"]),yo=/^[a-f0-9]{64}$/u,Kp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,SE=new Set(["EACCES","EPERM"]),nn=64*1024,wl=64*1024,EE=6e4,CE=1e3,RE=2,Yp={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},PE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function AE(e){let t=e.deadlineMs??EE;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 Xe(e){return Math.max(0,e.deadlineAt-Date.now())}function I(e){return Xe(e)>=1}function pl(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 xE(e){let t={...PE,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function TE(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&H.win32.isAbsolute(n)?H.win32.resolve(n):"C:\\Windows",a=H.win32.join(r,"System32","taskkill.exe");if(!H.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,f=(d,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(d))};try{l=Gp(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>f(!1)),l.once("close",d=>f(d===0)),u=setTimeout(()=>f(!1,!0),CE),u.unref()}catch{f(!1)}});for(let s=0;s<RE;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(-i,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}e.kill("SIGKILL")}function bl(e,t,i,n){let r=Xe(e);if(r<1)throw pl();let a=e.gitProcess,o=Gp(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[n?"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)}),f=setTimeout(()=>{c=!0,l=TE(o,a).then(()=>({error:null}),p=>({error:p}))},r);f.unref();let d=u.then(async p=>{if(clearTimeout(f),c){let m=await l;throw m?.error?pl(m.error):pl()}return{code:p,spawnError:s}});return{child:o,completion:d}}function IE(e){let t={...Yp,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function go(e,t,i,n=wl){let{child:r,completion:a}=bl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",p=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>n&&(u=!0)}),r.stderr.on("data",p=>{if(c>=nn)return;let m=nn-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:f,spawnError:d}=await a;if(f===0&&d===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${d?`: ${d.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function ml(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function vo(e,t,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=bl(e,t,i,n.stdin!==void 0),c=[],l=wo("sha256"),u=[],f=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,w=!1,y=!1,b=N=>{let E=0;for(;E<N.byteLength;){let g=N.indexOf(0,E),S=g<0?N.byteLength:g,k=N.subarray(E,S);if(!v&&k.byteLength>0&&(h.byteLength+k.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,w=!0):h=Buffer.concat([h,k])),g<0)break;m+=1,h.byteLength===0&&!v&&(y=!0);let C=h.byteLength+1;!v&&m<=n.maxRecords&&p+C<=n.maxBytes?(c.push(h),p+=C):w=!0,h=Buffer.alloc(0),v=!1,E=g+1}};o.stdout.on("data",N=>{l.update(N),d+=N.byteLength,d>n.maxBytes&&(w=!0);let E=n.outputChunkBytes;if(E===void 0){b(N);return}for(let g=0;g<N.byteLength;g+=E)b(N.subarray(g,Math.min(N.byteLength,g+E)))}),o.stderr.on("data",N=>{if(f>=nn)return;let E=nn-f,g=Buffer.from(N).subarray(0,E);u.push(g),f+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:E})=>{let g=n.acceptedExitCodes??[0];if(N!==null&&g.includes(N)&&E===null&&!y&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:w,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function yl(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 _E(e,t,i){let{child:n,completion:r}=bl(e,t,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=nn)return;let f=nn-o,d=Buffer.from(u).subarray(0,f);a.push(d),o+=d.byteLength});let{code:c,spawnError:l}=await r;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function tn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||H.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||H.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function OE(e,t){return e.map(i=>{let n=tn(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function jE(e){let t=H.resolve(e);for(;;){try{return await Z.lstat(H.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=H.dirname(t);if(i===t)return!1;t=i}}async function Xp(e,t,i,n={}){let r=H.resolve(t.projectRoot),a=H.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(d=>{let p=H.relative(r,H.resolve(d)).replaceAll("\\","/"),m=tn(p);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(d=>[`:(exclude)${d}`,`:(exclude)${d}/**`])],c={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},l=await vo(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await vo(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let f=await vo(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:f}}function Qp(e){return{stageBefore:ml(e.stagedBefore),combined:ml(e.combined),stageAfter:ml(e.stagedAfter)}}async function $E(e,t,i=Yp,n={}){let r=H.resolve(t.projectRoot);if(!await jE(r))return null;let a;try{a=await go(e,r,["rev-parse","--is-inside-work-tree"])}catch(y){throw en(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Xp(e,t,i,n)}catch(y){throw en(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,f=new Map,d=new Set,p=y=>{for(let b of y){let N=yl(b),E=N.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let g=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,E))?.groups;if(!g)throw new Error("Native Git snapshot provider returned a malformed staged header");let S=tn(N.slice(E+1));if(S===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(S),g.stage==="0"&&f.set(S,g.objectId),g.mode==="160000"&&g.stage==="0"&&d.add(S)}};p(s.records),p(l.records);let m=c.records.map(yl),h=OE(m,"combined"),v=new Set(h.filter(y=>!u.has(y))),w=new Set(h.filter((y,b)=>!u.has(y)&&m[b].endsWith("/")));for(let y of d)w.delete(y);return{tracked:u,trackedObjectIds:f,untracked:v,gitlinks:d,nestedRepositories:w,omissions:[],overflow:null,evidence:null,initialFence:Qp(o)}}function Ut(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Lp(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function HE(e,t){return!Ut(e.stageBefore,e.stageAfter)||!Ut(e.stageAfter,t.stageBefore)||!Ut(e.combined,t.combined)||!Ut(t.stageBefore,t.stageAfter)}async function FE(e,t,i,n,r){let a;try{a=await Xp(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw en(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=Qp(a),c=Lp(o)||Lp(s),l=HE(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:z(`comet.native.git-selection-overflow.v2
148
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var LE=(1n<<256n)-1n;function ME(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Mp(e){let t=H.resolve(e.paths.projectRoot),i=H.resolve(e.paths.nativeRoot),n=H.resolve(e.paths.configFile),r=H.join(t,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,u=0,f=0,d=!1,p=!1,m=!1,h=()=>Xe(e.execution)>=1?!0:(d=!0,m=!0,!1),v=b=>{let N=Buffer.from(`${b.type}\0${b.path}`,"utf8"),E=wo("sha256").update("comet.native.physical-selection-record.v1\0").update(N).digest();for(let g=0;g<s.length;g+=1)s[g]^=E[g];if(c=c+BigInt(`0x${E.toString("hex")}`)&LE,u+=1,f+=N.byteLength,Buffer.byteLength(b.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){d=!0,m=!0;return}a.push(b)},w=async b=>{if(m||!h())return;let N;try{N=await Z.opendir(b)}catch(C){if(!h())return;if(!oe(C)&&!ae(C)||b===t&&oe(C))throw C;p||=ae(C),d||=oe(C),m=!0;return}if(!h()){try{await N.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let E=!1,g;try{for(;!m&&h();){let C;try{C=await N.read()}catch(Y){if(!h())break;if(!oe(Y)&&!ae(Y)||b===t&&oe(Y))throw Y;p||=ae(Y),d||=oe(Y),m=!0;break}if(!h()||C===null)break;if(l+=1,l>e.limits.maxNodes){d=!0,m=!0;break}let B=H.join(b,C.name),K=VE(t,B);if(B===n||B===r||Kt(i,B)||e.denylist.some(Y=>Kt(Y,B))||ot(K)!==null)continue;if(!h())break;let D;try{D=await Z.lstat(B)}catch(Y){if(!h())break;if(!oe(Y)&&!ae(Y))throw Y;if(p=!0,v({path:K,type:"other"}),o.push({path:K,size:null,type:"file",reason:oe(Y)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(K),m||!h())break;continue}if(!h())break;let J=ME(D);if(J==="directory"){if(GE(e.policy,K))continue;if(!h())break;let Y;try{Y=await Z.realpath(B)}catch(it){if(!h())break;if(!oe(it)&&!ae(it))throw it;if(p=!0,v({path:K,type:J}),o.push({path:K,size:null,type:"directory",reason:oe(it)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(K),m||!h())break;continue}if(!h())break;if(!U(e.physicalProjectRoot,Y)||Kt(e.physicalNativeRoot,Y))continue;if(v({path:K,type:J}),await e.hooks?.afterNode?.(K),!h()||(await w(B),m))break;continue}if(v({path:K,type:J}),await e.hooks?.afterNode?.(K),!h()||m)break}}catch(C){E=!0,g=C}let S;try{await N.close()}catch(C){S=C}let k=h();if(E)throw g;if(k&&S!==void 0&&S.code!=="ERR_DIR_CLOSED")throw S};await w(t),h(),d?(a.length=0,u=0,f=0):(a.sort((b,N)=>b.path.localeCompare(N.path,"en")),o.sort((b,N)=>b.path.localeCompare(N.path,"en")));let y=d?z(`comet.native.physical-selection-incomplete.v1
149
- ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):z(`comet.native.physical-selection.v1
150
- ${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:f,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:y,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:f,overflow:d,unstable:p}}}function Zp(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 DE(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!Zp(e,t),r=[];return i&&r.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),n&&r.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:r,evidence:i||n?{schema:"comet.native.physical-selection.v1",status:i&&n?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function BE(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Dp(e,t){let n=(await go(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Kp.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return z(`gitlink:${n}`)}async function Bp(e,t){let i=await Dp(e,t),n=await _E(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await Dp(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function qE(e,t){if(ot(t)!==null)return!1;let i=H.resolve(e.projectRoot,...t.split("/"));return!Kt(H.resolve(e.nativeRoot),i)}function VE(e,t){return H.relative(e,t).split(H.sep).join("/")}function WE(e,t){return t.map(i=>H.resolve(e,...i.split(/[\\/]/u)))}function Kt(e,t){let i=H.resolve(e),n=H.resolve(t);return n===i||U(i,n)}function oe(e){return SE.has(e.code??"")}function ae(e){return e.code==="ENOENT"}function em(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
151
- `)}function zE(e,t){return z(`comet.native.snapshot-policy.v1
152
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function vl(e,t,i){let n=new Set(t),r=[...t];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function JE(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function qp(e){let t=oo(e,"Native snapshot pattern"),i=[];for(let n=0;n<t.length;n+=1){let r=t[n];r==="*"&&t[n+1]==="*"?(n+=1,t[n+1]==="/"?(n+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):r==="*"?i.push({kind:"star"}):r==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:r})}return(n,r)=>{let a=r?JE(r):void 0;if(a&&!a())return!1;let o=vl(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[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=vl(i,c,a),o===null||o.size===0)return!1}return vl(i,o,a)?.has(i.length)??!1}}function tm(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>oo(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>oo(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=zE(t,i);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:n},includeMatchers:t.map(qp),excludeMatchers:i.map(qp),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function GE(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Vp(e,t,i){if(!e)return!0;let n=()=>I(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function gl(e,t,i){let n=JSON.stringify(i);return z(`${e}
153
- ${Buffer.byteLength(t)}:${t}
154
- ${Buffer.byteLength(n)}:${n}`)}function Nl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Wp(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Nl(i))return e.splice(t,1),i}return null}function Gt(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return me(i,n)?j(i,n):j(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function UE(e,t,i,n){if(!I(n))return{status:"budget-exhausted"};let r;try{r=await Z.open(e,"r")}catch(c){if(!I(n))return{status:"budget-exhausted"};throw c}if(!I(n))return await r.close(),{status:"budget-exhausted"};let a=wo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!I(n))return{status:"budget-exhausted"};let c=await r.stat();if(!I(n))return{status:"budget-exhausted"};if(!c.isFile()||!Gt(i,c))return{status:"changed"};for(;;){if(!I(n))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!I(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!I(n))return{status:"budget-exhausted"};let f=await r.stat();return I(n)?!f.isFile()||!Gt(c,f)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:f}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function Be(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qe(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Zi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ct(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function im(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 i=H.posix.normalize(e);if(i!==e||H.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function KE(e,t){let i=Be(e,`Native snapshot entry ${t}`);qe(i,gE,`Native snapshot entry ${t}`);let n=im(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!yo.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let r={path:n,hash:i.hash,size:ct(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Kp.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function YE(e,t){let i=Be(e,`Native snapshot omission ${t}`);if(qe(i,wE,`Native snapshot omission ${t}`),!bE.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!kE.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:im(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ct(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function XE(e){let t=Be(e,"Native snapshot omission overflow");if(qe(t,yE,"Native snapshot omission overflow"),typeof t.hash!="string"||!yo.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Zi(t.count,"Native snapshot omission overflow count")}}function Qi(e,t){let i=Be(e,t);if(qe(i,pE,t),typeof i.hash!="string"||!yo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=ct(i.recordCount,`${t} recordCount`),r=ct(i.storedRecordCount,`${t} storedRecordCount`),a=ct(i.stdoutBytes,`${t} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function zp(e){let t=Be(e,"Native Git selection evidence");if(qe(t,hE,"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 i=Qi(t.stageBefore,"Native Git selection stageBefore"),n=Qi(t.combined,"Native Git selection combined"),r=Qi(t.stageAfter,"Native Git selection stageAfter"),a=Qi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Qi(t.finalCombined,"Native Git selection finalCombined"),s=Qi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(f=>f.overflow),l=!Ut(i,r)||!Ut(r,a)||!Ut(n,o)||!Ut(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:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Jp(e,t){let i=Be(e,t);if(qe(i,vE,t),typeof i.hash!="string"||!yo.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=ct(i.visitedNodeCount,`${t} visitedNodeCount`),r=ct(i.recordCount,`${t} recordCount`),a=ct(i.storedRecordCount,`${t} storedRecordCount`),o=ct(i.encodedBytes,`${t} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function QE(e){let t=Be(e,"Native physical selection evidence");if(qe(t,mE,"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 i=Jp(t.before,"Native physical selection before"),n=Jp(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Zp(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"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:i,after:n}}function fr(e){let t=Be(e,"Native content snapshot manifest");if(qe(t,cE,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!NE.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let g=Be(t.capture,"Native content snapshot capture");if(qe(g,fE,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let S=g.gitSelection===void 0?void 0:zp(g.gitSelection),k=g.physicalSelection===void 0?void 0:QE(g.physicalSelection),C=null;if(g.projection!==void 0){let B=Be(g.projection,"Native content snapshot projection");if(qe(B,dE,"Native content snapshot projection"),B.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");C={provider:"git",...B.selection===void 0?{}:{selection:zp(B.selection)}}}if(g.provider==="git"){if(k||C)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...S?{gitSelection:S}:{}}}else{if(S)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&C)throw new Error("Native physical-tree capture cannot combine selection and projection");i=C?{provider:"physical-tree",projection:C}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Be(t.limits,"Native content snapshot limits");qe(n,lE,"Native content snapshot limits");let r={maxFiles:Zi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Zi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Zi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Zi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Zi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=Be(t.policy,"Native snapshot policy");if(qe(g,uE,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=tm({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(KE),s=t.omitted.map(YE),c=ct(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:XE(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>r.maxFileBytes)||o.reduce((g,S)=>g+S.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Up||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 f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,b=y?.status==="overflow"||y?.status==="overflow-and-changed",N=y?.status==="changed"||y?.status==="overflow-and-changed";if(b!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(em(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function ZE(e,t){if(!sE.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=H.join(e.changesDir,t);if(!U(e.changesDir,i))throw new Error("Native change path escaped");return H.join(i,"runtime","baseline-manifest.json")}async function nm(e,t={}){let i={maxFiles:t.limits?.maxFiles??mo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??mo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??mo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??mo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=tm(t.policy),r=AE({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=IE(t.gitSelectionLimits),o=xE(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=H.resolve(e.projectRoot),c=await Z.realpath(s),l=H.resolve(e.nativeRoot),u=await Z.realpath(l),f=H.resolve(e.configFile),d=H.join(s,".comet","current-change.json"),p=WE(s,t.denylist??[]),m=[],h=[],v=new Map,w=new Map,y=0,b=0,N=z("comet.native.snapshot-omission-overflow.v1"),E=0,g=!1,S=null,k=x=>{b+=1,N=gl(N,"omission",x)},C=x=>{if(y+=1,h.length<Up){h.push(x);return}if(Nl(x)){let A=Wp(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");k(A),h.push(x);return}k(x)},B=x=>{y+=x.count,b+=x.count,N=gl(N,"git-selection",{source:"git-selection",...x})},K=x=>{b+=1,N=gl(N,"manifest-entry",{reason:"manifest-size",entry:x})},D=async(x,A)=>{m.push(x),E+=x.size,v.set(x.path,A),g||(g=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},J=(x,A)=>{let T=m.findIndex(X=>X.path===x);if(T<0)return;let[O]=m.splice(T,1);E-=O.size,v.delete(x),C(A)},Y=async(x,A,T,O)=>{if(!T.isFile()||T.isSymbolicLink()||!I(r))return;let X;try{X=await Z.realpath(x)}catch(P){if(!I(r))return;if(!oe(P)&&!ae(P))throw P;C({path:A,size:T.size,type:"file",reason:ae(P)?"changed-during-read":"unreadable"});return}if(!I(r)||!U(c,X)||Kt(u,X))return;if(m.length>=i.maxFiles){C({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){C({path:A,size:T.size,type:"file",reason:"file-size"});return}if(E+T.size>i.maxTotalBytes){C({path:A,size:T.size,type:"file",reason:"total-size"});return}let L,_,ee;try{if(L=await UE(X,T.size,T,r),L.status==="budget-exhausted"||!I(r))return;if(L.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!I(r)||(ee=await Z.realpath(x),!I(r)))return;_=await Z.lstat(x)}catch(P){if(!I(r))return;if(!oe(P)&&!ae(P))throw P;C({path:A,size:T.size,type:"file",reason:ae(P)?"changed-during-read":"unreadable"});return}if(I(r)){if(L.bytes!==T.size||ee!==X||!Gt(T,L.finalStat)||!Gt(L.finalStat,_)||!_.isFile()||_.isSymbolicLink()||_.size!==T.size||_.mtimeMs!==T.mtimeMs||_.ctimeMs!==T.ctimeMs){C({path:A,size:_.isFile()?_.size:null,type:_.isFile()?"file":"other",reason:"changed-during-read"});return}I(r)&&await D({path:A,hash:L.hash,size:_.size,type:"file",...O===void 0?{}:{gitObjectId:O}},{kind:"file",target:x,realTarget:X,stat:_})}},it=async(x,A,T)=>{if(!I(r))return;let O,X,L;try{if(O=await Z.readlink(x,{encoding:"buffer"}),!I(r)||(L=await Z.lstat(x),!I(r)))return;X=await Z.readlink(x,{encoding:"buffer"})}catch(P){if(!I(r))return;if(!oe(P)&&!ae(P))throw P;C({path:A,size:null,type:"other",reason:ae(P)?"changed-during-read":"unreadable"});return}if(!I(r))return;if(!L.isSymbolicLink()||!Gt(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!O.equals(X)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let _=O.byteLength;if(m.length>=i.maxFiles){C({path:A,size:_,type:"other",reason:"file-count"});return}if(_>i.maxFileBytes){C({path:A,size:_,type:"other",reason:"file-size"});return}if(E+_>i.maxTotalBytes){C({path:A,size:_,type:"other",reason:"total-size"});return}let ee=wo("sha256").update("symlink\0").update(O).digest("hex");I(r)&&await D({path:A,hash:ee,size:_,type:"file"},{kind:"symlink",target:x,rawTarget:O,stat:L})},nt=async()=>{for(let[x,A]of[...v]){if(!I(r))return;if(A.kind==="file"){let _,ee;try{if(_=await Z.realpath(A.target),!I(r))return;ee=await Z.lstat(A.target)}catch(P){if(!I(r))return;if(!oe(P)&&!ae(P))throw P;J(x,{path:x,size:null,type:"file",reason:oe(P)?"unreadable":"changed-during-read"});continue}if(!I(r))return;(_!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!Gt(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&J(x,{path:x,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let _,ee;try{if(_=await Z.lstat(A.target),!I(r))return;ee=await Z.readlink(A.target,{encoding:"buffer"})}catch(P){if(!I(r))return;if(!oe(P)&&!ae(P))throw P;J(x,{path:x,size:null,type:"other",reason:oe(P)?"unreadable":"changed-during-read"});continue}if(!I(r))return;(!_.isSymbolicLink()||!Gt(A.stat,_)||_.mtimeMs!==A.stat.mtimeMs||_.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&J(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,O;try{if(T=await Z.realpath(A.target),!I(r))return;O=await Z.lstat(A.target)}catch{if(!I(r))return;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!I(r))return;if(!(T===A.realTarget&&O.isDirectory()&&!O.isSymbolicLink()&&Gt(A.stat,O)&&U(c,T)&&!Kt(u,T))){J(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!I(r))return;L=await Bp(r,T)}catch(_){if(en(_))throw _;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!I(r))return;L.dirty?J(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&J(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of w){if(!I(r))return;try{let T=await Z.lstat(A);if(!I(r))return;C({path:x,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!I(r))return;if(ae(T))continue;if(!oe(T))throw T;C({path:x,size:null,type:"file",reason:"unreadable"})}}},_e=await $E(r,e,a,t.gitSelectionHooks);if(_e===null){let x=await Mp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let O of x.records){if(O.type!=="file"&&O.type!=="symlink"||v.has(O.path))continue;if(Xe(r)<1)break;if(!Vp(n,O.path,r))continue;if(Xe(r)<1)break;let X=H.resolve(s,...O.path.split("/")),L;try{L=await Z.lstat(X)}catch(_){if(!I(r))break;if(!oe(_)&&!ae(_))throw _;C({path:O.path,size:null,type:"file",reason:ae(_)?"changed-during-read":"unreadable"});continue}if(Xe(r)<1)break;if(O.type==="symlink"&&L.isSymbolicLink()){if(await it(X,O.path,L),Xe(r)<1)break;continue}if(O.type!=="file"||!L.isFile()||L.isSymbolicLink()){C({path:O.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Y(X,O.path,L),Xe(r)<1)break}Xe(r)>=1&&await nt();let A=await Mp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=DE(x.evidence,A.evidence);S=T.evidence;for(let O of[...x.omissions,...A.omissions,...T.omissions])h.some(X=>X.path===O.path&&X.reason===O.reason)||C(O)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,T=!1;if(x){let P=fr(x);for(let te of P.entries)te.gitObjectId!==void 0&&A.set(te.path,te);T=A.size>0}let O=new Set,X=!0;try{let P=await vo(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)T=!1,X=!1,A.clear();else for(let te of P.records){let ie=yl(te),we=ie.indexOf(" "),pe=we<0?null:tn(ie.slice(we+1));if(we!==1||pe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ie[0]!=="H"&&O.add(pe)}}catch(P){if(en(P))throw P;T=!1,X=!1,A.clear()}let L=new Set;try{let P=await go(r,s,["ls-files","--modified","-z"],wl);for(let te of P.toString("utf8").split("\0")){let ie=tn(te);ie!==null&&L.add(ie)}}catch{T=!1,X=!1,A.clear()}let _=new Set,ee=new Set;for(let P of BE(_e)){if(v.has(P)||!qE(e,P))continue;if(Xe(r)<1)break;if(!Vp(n,P,r))continue;if(Xe(r)<1)break;let te=H.resolve(s,...P.split("/"));if(te===f||te===d||p.some(Oe=>Kt(Oe,te)))continue;if(_e.gitlinks.has(P)){if(m.length>=i.maxFiles){C({path:P,size:0,type:"file",reason:"file-count"});continue}let Oe,zr;try{[Oe,zr]=await Promise.all([Z.realpath(te),Z.lstat(te)])}catch{C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(zr.isSymbolicLink()||!zr.isDirectory()||!U(c,Oe)||Kt(u,Oe)){C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ti=await Bp(r,Oe);if(Ti.dirty){C({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await D({path:P,hash:Ti.hash,size:0,type:"file"},{kind:"gitlink",target:te,realTarget:Oe,stat:zr,hash:Ti.hash})}catch(Ti){if(en(Ti))throw Ti;C({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ie;try{ie=await Z.lstat(te)}catch(Oe){if(ae(Oe)&&_e.tracked.has(P)){w.set(P,te);continue}if(!oe(Oe)&&!ae(Oe))throw Oe;C({path:P,size:null,type:"file",reason:ae(Oe)?"changed-during-read":"unreadable"});continue}if(ie.isSymbolicLink()){await it(te,P,ie);continue}if(!ie.isFile()){_e.nestedRepositories.has(P)||C({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let we=_e.trackedObjectIds.get(P),pe=we?A.get(P):void 0;if(T&&pe?.gitObjectId!==void 0&&pe.gitObjectId===we&&!O.has(P)&&!L.has(P)){if(m.length>=i.maxFiles){C({path:P,size:pe.size,type:"file",reason:"file-count"});continue}if(pe.size>i.maxFileBytes){C({path:P,size:pe.size,type:"file",reason:"file-size"});continue}if(E+pe.size>i.maxTotalBytes){C({path:P,size:pe.size,type:"file",reason:"total-size"});continue}m.push({...pe}),E+=pe.size,_.add(P);continue}let Gu=X&&!O.has(P)&&!L.has(P)?we:void 0;await Y(te,P,ie,Gu),Gu!==void 0&&ee.add(P)}if(await nt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await FE(r,e,a,_e,t.gitSelectionHooks?.outputChunkBytes),_.size>0||T&&ee.size>0){let P=await go(r,s,["ls-files","--modified","-z"],wl),te=new Set;for(let ie of P.toString("utf8").split("\0")){let we=tn(ie);we!==null&&te.add(we)}for(let ie of _){if(!te.has(ie))continue;let we=m.find(pe=>pe.path===ie);J(ie,{path:ie,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let ie of ee){if(!te.has(ie))continue;let we=m.find(pe=>pe.path===ie);we&&delete we.gitObjectId}}for(let P of _e.omissions)C(P);_e.overflow&&B(_e.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let rw=_e===null?{provider:"physical-tree",...S?{physicalSelection:S}:{}}:{provider:"git",..._e.evidence?{gitSelection:_e.evidence}:{}},Ju=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:rw,createdAt:(t.now??new Date).toISOString(),complete:y===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:y,...b>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:b}}:{}}),rs=Ju();for(;em(rs)>i.maxManifestBytes;){if(h.filter(A=>!Nl(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let O=Wp(h);if(O===null)break;k(O)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))y+=1,K(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");rs=Ju()}return rs}async function kl(e,t,i={}){let r=(await Wt(e.projectRoot))?.native.snapshot??nl;return nm(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:r.max_files,maxFileBytes:r.max_total_bytes,maxTotalBytes:r.max_total_bytes,maxDurationMs:r.max_duration_ms},deadlineMs:r.max_duration_ms})}async function rm(e,t){let i=ZE(e,t);await $(e.nativeRoot,i);try{let n=await wp({root:e.nativeRoot,file:i,maxBytes:oE,label:"Native baseline snapshot manifest"});return fr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as gC}from"crypto";import Pl from"path";var lt=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"});import{constants as bo,promises as Se}from"node:fs";import He from"node:path";import{TextDecoder as fC}from"node:util";import sC from"path";var aC=as(za(),1);var am=(e,t)=>{let i=e[t];return i==null?null:String(i)};function hr(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function dr(e,t){let i=hr(e,t);if(sC.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function cC(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(i))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function om(e){if(!e.run_id)return null;let t=hr(e,"run_id"),i=hr(e,"skill"),n=hr(e,"skill_version"),r=hr(e,"skill_hash"),a=dr(e,"pending_ref"),o=dr(e,"trajectory_ref"),s=dr(e,"context_ref"),c=dr(e,"artifacts_ref"),l=dr(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:i,skillVersion:n,skillHash:r,orchestration:e.orchestration,currentStep:am(e,"current_step"),iteration:u,pending:am(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:cC(e)}}var kj=256*1024;var lC=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function uC(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)},i=om(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function No(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(n=>!lC.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);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 uC(t)}var $e={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function mr(e,t){let i=He.relative(e,t);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function cm(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function pr(e,t){return j({...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 dC(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function rn(e,t,i){let n=lt[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=He.resolve(e),a=He.resolve(r,...n.split("/"));if(!mr(r,a))throw new Error("Native Run path must stay inside its change");return a}async function sm(e){let t=await Se.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Se.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Sl(e,t){let i=He.resolve(e),n=He.resolve(t);if(!mr(i,n))throw new Error("Native Run path is outside its change");let r=[await sm(i)],a=i;for(let o of He.relative(i,n).split(He.sep).filter(Boolean)){a=He.join(a,o);let s;try{s=await sm(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!mr(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function ko(e){for(let t of e){let i=await Se.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!dC(t,i)||await Se.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function hC(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function vr(e,t,i,n,r){let a=await Sl(e,He.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await Se.lstat(t)}catch(f){if(f.code==="ENOENT")return null;throw f}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(o.size>i)throw new Error(`${n} exceeds ${i} bytes`);let s=cm(o),c=await Se.realpath(t);if(!mr(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?bo.O_RDONLY:bo.O_RDONLY|bo.O_NOFOLLOW|bo.O_NONBLOCK,u;try{u=await Se.open(t,l)}catch(f){throw new Error(`${n} changed while opening`,{cause:f})}try{let[f,d,p]=await Promise.all([u.stat(),Se.lstat(t),Se.realpath(t)]);if(await ko(a),!f.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!pr(s,f)||!pr(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await hC(u,i,n);await r?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([u.stat(),Se.lstat(t),Se.realpath(t)]);if(await ko(a),!v.isFile()||v.isSymbolicLink()||w!==c||!pr(s,h)||!pr(s,v))throw new Error(`${n} changed while reading`);let y;try{y=new fC("utf-8",{fatal:!0}).decode(m)}catch(b){throw new Error(`${n} is not valid UTF-8`,{cause:b})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function pC(e,t,i){let n=await Sl(e,He.dirname(t));if(!n)return{exists:!1};let r;try{r=await Se.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Se.realpath(t);if(!mr(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await ko(n),{exists:!0,identity:cm(r),realPath:a}}async function mC(e,t,i,n){let r=await Sl(e,He.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await Se.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!pr(i.identity,a)||await Se.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await ko(r)}async function El(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await pC(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await vt(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await mC(e.changeDir,e.file,i,e.label)}});let n=await vr(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function vC(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function lm(e){return`${JSON.stringify(e,null,2)}
155
- `}function Cl(e){return No(e)}async function an(e,t){let i=rn(e,"stateRef"),n=await vr(e,i,$e.runStateBytes,"Native Run state",t);return n?No(vC(n.text,"Native Run state")):null}async function So(e,t,i){let n=No(t);await El({changeDir:e,file:rn(e,"stateRef"),content:lm(n),maxBytes:$e.runStateBytes,label:"Native Run state",hooks:i})}async function wi(e,t,i){let n=rn(e,"trajectoryRef",t),r=await vr(e,n,$e.trajectoryBytes,"Native Run trajectory",i);if(!r)return[];let a=r.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>$e.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${$e.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 um(e,t,i){return(await vr(e,rn(e,"trajectoryRef",t),$e.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function fm(e,t,i,n){let r=rn(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
156
- `;if(Buffer.byteLength(a,"utf8")>$e.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${$e.trajectoryEventBytes} bytes`);let o=await vr(e,r,$e.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=$e.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${$e.trajectoryEvents} events`);await El({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:$e.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function dm(e,t,i,n){await El({changeDir:e,file:rn(e,"checkpointRef",t),content:lm(i),maxBytes:$e.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var wC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Al=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Rl(e){return gC("sha256").update(e).digest("hex")}function yC(e,t){if(!wC.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Pl.join(e.changesDir,t);if(!U(e.changesDir,i))throw new Error("Native change path escaped");return Pl.join(i,"runtime","trajectory.jsonl")}function NC(e){let t=e.split(/\n/u),i=0;for(let n=0;n<t.length;n+=1){let r=t[n].endsWith("\r")?t[n].slice(0,-1):t[n];if(r.length!==0){i=n+1;try{JSON.parse(r)}catch(a){return{status:"invalid",line:n+1,message:a.message}}}}return{status:"valid",count:i}}function bC(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function kC(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=NC(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:e,line:r.line,message:r.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=r.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
157
- `)])}catch(f){if(!bC(f,o))return{status:"invalid",file:e,line:s,message:f.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Rl(t),targetHash:Rl(l),tailHash:Rl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function SC(e,t){let i=yC(e,t);await $(e.nativeRoot,i);let n=Pl.join(e.changesDir,t),r=await um(n,lt.trajectoryRef);return r===null?{status:"clean",file:i}:kC(i,Buffer.from(r))}async function EC(e,t){let i=await SC(e,t);return"inspection"in i?i.inspection:i}async function Eo(e,t){let i=await EC(e,t);if(i.status!=="clean")throw new Al(i)}import{createHash as PC}from"node:crypto";import{promises as Ro}from"node:fs";import Yt from"node:path";import{execFileSync as CC}from"child_process";import Co from"path";function xl(e,t){return CC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function RC(e,t){let i=Co.normalize(e),n=Co.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function hm(e){try{let t=Co.resolve(xl(e,["rev-parse","--show-toplevel"])),n=xl(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?Co.resolve(n.slice(9)):t,a=null;try{a=xl(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!RC(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var gr=/^[a-f0-9]{64}$/u,AC=16*1024,Tl=process.platform,xC=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function gm(e){return xC.has(e)}function wm(e,t){let i=Yt.relative(e,t);return Yt.isAbsolute(i)||i===".."||i.startsWith(`..${Yt.sep}`)?null:i.replaceAll("\\","/")||"."}function ym(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Nm(e,t){if(e.length===0||ym(e)||e.includes("\\")||Yt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Yt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Il(e,t){return PC("sha256").update(`${e}
158
- ${t}`).digest("hex")}async function pm(e,t){let i=await Ro.realpath(t),n=await Ro.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Tl==="win32"?Yt.normalize(i).toLowerCase():i;return Il(e,`${r}
159
- ${n.dev}
160
- ${n.ino}
161
- ${n.birthtimeMs}`)}async function mm(e,t){let i=await Ro.realpath(t),n=await Ro.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Tl==="win32"?Yt.normalize(i).toLowerCase():i;return Il(e,r)}function TC(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 vm(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ym(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function bm(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(vm(e.changeBranch,"Native workspace change branch"),vm(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 wr(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!gr.test(String(t.projectRootId))||!gr.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");TC(t.capturedAt),Nm(t.nativeRootRef,"Native workspace root ref");let r=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!gr.test(String(t.projectRootPathId))||a&&!gr.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!gr.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(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(bm(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 km(e,t){return Yt.join(e.changesDir,t,"runtime","workspace.json")}function IC(e,t){let i=wm(e.nativeRoot,km(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Nm(i,"Native workspace file ref")}async function _C(e,t){try{let i=await ye({root:e.nativeRoot,ref:IC(e,t),maxBytes:AC});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function OC(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=wm(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([pm("comet.native.workspace-project-root.v2",e.paths.projectRoot),pm("comet.native.workspace-native-root.v2",e.paths.nativeRoot),mm("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),mm("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),o=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&bm(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:Il("comet.native.workspace-session.v2",`${i}
162
- ${n}
163
- ${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return wr(c),c}async function Sm(e,t,i){return st(e,`set workspace finish for ${t}`,async()=>{let n=await _l(e,t);if(n===null||n.schema!=="comet.native.workspace.v3")throw new Error(`Native change ${t} has no workspace finishing contract`);if(n.isolation==="current")throw new Error("Native current isolation does not use a workspace finishing action");let r={...n,finish:i};wr(r);let a=km(e,t);return await $(e.nativeRoot,a),await Ne(a,r,{containedRoot:e.nativeRoot}),r})}async function yt(e,t){let i=await _C(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(wr(i),i)}async function Em(e){wr(e.identity);let t=await OC({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Tl==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}async function Cm(e){if(wr(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 Em(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=hm(e.paths.projectRoot);return e.identity.changeBranch===null?i.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}:i.isGitWorktree?i.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 ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.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 _l(e,t){let i=await yt(e,t);if(i===null)return null;let n=await Cm({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var Xt="comet.native.v3",yi="comet.native.v2",Ni="comet.native.v1",on="comet.native.transition.v3",sn="comet.native.transition.v2",yr="comet.native.transition.v1";var Pm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],jC=new Set(Pm),Am=new Set([...Pm,"minimum_runtime_version","revision"]),$C=new Set([...Am,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),HC=new Set(["capability","operation","source","base_hash"]),FC=new Set(["shape","build","verify","archive"]),LC=new Set(["implicit","confirmed"]),MC=new Set(["pending","pass","fail"]),bt="comet-state.yaml",$l=/^[a-f0-9]{64}$/u,xm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DC=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Nr=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},bi=class extends Error{constructor(i,n){super(i!==Xt||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},br=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Po=class extends Error{constructor(i,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ao=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;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"},S0=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
164
- `);function Sr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Tm(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Hl(e){if(!xm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function BC(e){if(!xm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Im(e,t){if(e.length===0||Nt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function qC(e,t){let i=Sr(e,`spec_changes[${t}]`);if(Tm(i,HC,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(BC(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&Im(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!$l.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!$l.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function VC(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 Fl(e,t){if(Tm(e,t,bt),typeof e.name!="string")throw new Error("Native change name is required");if(Hl(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"||!FC.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&&!LC.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 i=e.spec_changes.map(qC),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof e.verification_result!="string"||!MC.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"&&Im(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!VC(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:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Er(e){let t=Sr(e,bt);if(t.schema!==Ni)throw new Error(`Expected ${Ni}`);return{schema:Ni,...Fl(t,jC)}}function kr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ol(e,t,i){if(e===null)return null;let n=typeof e=="string"?DC.exec(e):null;if(!n||n[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function WC(e){if(e==null)return null;if(typeof e!="string"||!$l.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function zC(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 Cr(e){let t=Sr(e,bt);if(t.schema!==yi)throw new Error(`Expected ${yi}`);if(kr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${yi} minimum_runtime_version must be 2`);return{schema:yi,minimum_runtime_version:2,revision:kr(t.revision,"Native v2 revision"),...Fl(t,Am)}}function ut(e){let t=Sr(e,bt);if(t.schema!==Xt){if(t.schema===Ni||t.schema===yi){let o=t.schema===Ni?Er(t):Cr(t);throw new Nr(o.name,o.schema)}throw new bi(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=kr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new bi(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=kr(t.revision,"Native revision"),r=Fl(t,$C),a=WC(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Xt,minimum_runtime_version:3,revision:n,verification_protocol:zC(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Ol(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ol(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ol(t.partial_allowance,"Native partial_allowance","allowances")}}function JC(e){let t=Sr(e,bt);if(t.schema===Ni){let r=Er(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Xt}`}}if(t.schema===yi){let r=Cr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Xt}`}}if(t.schema!==Xt){let r=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:r,state:null,message:new bi(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=kr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new bi(t.schema,i).message};let n=ut(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function jl(e){let t=ut(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function W(e,t){Hl(t);let i=Nt.join(e.changesDir,t);if(!U(e.changesDir,i))throw new Error("Native change path escaped");return i}async function cn(e,t){let i=Nt.join(W(e,t),"runtime","schema-migration.json");await $(e.nativeRoot,i);try{return await Rm.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Ll(e,t){let i=Nt.join(W(e,t),"runtime","checkpoint-journal.json");await $(e.nativeRoot,i);try{return await Rm.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var GC=256*1024;async function Ml(e,t=Nt.dirname(e)){let i=Nt.relative(t,e).split(Nt.sep).join("/"),n=await ye({root:t,ref:i,maxBytes:GC}),r=(0,xo.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${r.errors[0].message}`);return r.toJS()}async function UC(e,t){let i=Nt.join(W(e,t),bt);await $(e.nativeRoot,i);let n=JC(await Ml(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await cn(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(n.status==="current"&&n.state&&await KC(e,n.state),n)}async function KC(e,t){if(await rm(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function de(e,t){let i=await UC(e,t);if(i.status==="migration-required")throw new Nr(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new bi(i.schema,i.minimumRuntimeVersion);return await _l(e,t),i.state}async function _m(e,t,i){let n={...t,schema:Xt,minimum_runtime_version:3,revision:i+1},r=await Hp({expectedRevision:i,next:n,read:async()=>{let a=ut(await Ml(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>vt(e,(0,xo.stringify)(jl(a))),equals:(a,o)=>JSON.stringify(jl(a))===JSON.stringify(jl(o)),conflict:a=>new br(t.name,i,a)});return Object.assign(t,r),r}async function To(e,t,i,n){if(await Vi(e.projectRoot),await cn(e,t.name))throw new Nr(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await Ll(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await de(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Eo(e,t.name);let a=Nt.join(W(e,t.name),bt);return await $(e.nativeRoot,a),_m(a,t,i)}async function Om(e,t){return _m(e,t,t.revision)}async function jm(e){return ut(await Ml(e))}var Hm=["Outcome","Scope","Non-goals","Acceptance examples"],YC=[...Hm,"Constraints and invariants","Decisions","Open questions","Verification expectations"],XC=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Fm={maxFileBytes:Yn};function Lm(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
165
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(r(),i=o[1].trim(),n=[]):i!==null&&n.push(a)}return r(),t}async function QC(e,t){let i=$m.resolve(e,...t.split(/[\\/]/u));if(!U(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Dl.realpath(e),r=await Dl.realpath(i);if(!U(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Dl.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Io(e){return{valid:e.length===0,findings:e}}async function Mm(e,t){let i=[],n;try{n=(await ye({root:e,ref:t,maxBytes:Fm.maxFileBytes})).text}catch(o){return Io([{code:"brief-missing",message:o.message,path:t}])}let r=Lm(n);for(let o of YC)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Hm)(r.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=r.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Io(i)}async function Dm(e,t){let i=[],n;try{n=(await ye({root:e,ref:t,maxBytes:Fm.maxFileBytes})).text}catch(a){return Io([{code:"verification-missing",message:a.message,path:t}])}let r=Lm(n);for(let a of XC)r.has(a)?(r.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Io(i)}function Rr(e,t){return $m.join(e.specsDir,t,"spec.md")}async function Bm(e,t){return QC(e,t)}import{promises as ux}from"node:fs";import Ag from"node:path";import qm from"node:path";import{createHash as ZC}from"crypto";function Qe(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function eR(e,t){t.has(e)&&Qe("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||Qe("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&Qe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Qe("symbol properties are not supported"),`[${e.map(n=>Bl(n,t)).join(",")}]`}finally{t.delete(e)}}function tR(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Qe("only plain objects are supported"),t.has(e)&&Qe("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Qe("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Qe("accessor properties are not supported"),`${JSON.stringify(o)}:${Bl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Bl(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)||Qe("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?eR(e,t):tR(e,t);case"bigint":case"function":case"symbol":case"undefined":return Qe(`${typeof e} values are not supported`)}return Qe("unsupported value type")}function Pr(e){return Bl(e,new Set)}function M(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 ZC("sha256").update(`${e}
166
- ${Pr(t)}`).digest("hex")}var iR="comet.native.archive-preflight.v1",nR="comet.native.archive-preflight.v1",rR="comet.native.archive-operation.v1",aR=/^[a-f0-9]{64}$/u,Vm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function _o(e,t){return e<t?-1:e>t?1:0}function sR(e,t){if(typeof e!="string"||!aR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kt(e,t){return e===null?null:sR(e,t)}function cR(e,t){let i=qm.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||qm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function lR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function uR(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,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===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 fR(e,t){if(!Vm.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 i=kt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=kt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=kt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(r===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:n,proposedHash:r}}function dR(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:kt(e.contractHash,"Native archive contract hash"),acceptanceHash:kt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:kt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:kt(e.reportHash,"Native archive report hash"),envelopeHash:kt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:kt(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(i=>i===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 hR(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!oR.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(_o);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function pR(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 i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(_o)}function Wm(e){if(!Vm.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(fR).sort((l,u)=>_o(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 i=t.map(l=>({...l,operationHash:M(rR,l)})),n=dR(e.evidence),r=uR(e.workspace),a=[...new Set([...hR(e.findingCodes??[]),...pR({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(_o),o=lR(e.revision),s=cR(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:i,evidence:n,workspace:r,findingCodes:a};return{schema:iR,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,workspace:r,findingCodes:a,preflightHash:M(nR,c)}}import{createHash as mR}from"node:crypto";import zm from"node:path";var vR="comet.native.conflict-radar.v1",xe=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}),gR="comet.native.conflict-radar.v1",wR="comet.native.conflict-radar-signals.v1",yR=/^[a-f0-9]{64}$/u,Um=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NR=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),bR=new Set(["capability","operation","baseHash"]),kR=new Set(["path","kind"]);function ln(e,t){return e<t?-1:e>t?1:0}function ql(e){return Buffer.byteLength(e,"utf8")}function Vl(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let n=e,r=Object.keys(n).filter(a=>!t.has(a));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);return n}function Wl(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(ql(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function SR(e,t){let i=Wl(e,t,xe.maxArtifactPathBytes),n=zm.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||zm.posix.isAbsolute(n)||i.split("/").includes("..")||n!==i||n==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Km(e,t){if(typeof e!="string"||!yR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ER(e,t){let i=Vl(e,bR,t),n=Wl(i.capability,`${t} capability`,xe.maxCapabilityBytes);if(!Um.test(n))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let r=i.baseHash===null?null:Km(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&r!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&r===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:n,operation:i.operation,baseHash:r}}function CR(e,t){let i=Vl(e,kR,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:SR(i.path,`${t} path`),kind:i.kind}}function RR(e,t){let i=Vl(e,NR,`Conflict radar change ${t}`),n=Wl(i.name,`Conflict radar change ${t} name`,xe.maxNameBytes);if(!Um.test(n))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${n} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${n} specs must be an array`);if(i.specs.length>xe.maxSpecsPerChange)throw new Error(`Conflict radar change ${n} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${n} declared artifacts must be an array`);if(i.declaredArtifacts.length>xe.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>ER(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>ln(c.capability,l.capability));if(new Set(r.map(c=>c.capability)).size!==r.length)throw new Error(`Conflict radar change ${n} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>CR(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>ln(c.path,l.path)||ln(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${n} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Km(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function PR(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>xe.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(RR).sort((r,a)=>ln(r.name,a.name));if(new Set(t.map(r=>r.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((r,a)=>r+a.specs.length,0)>xe.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>xe.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function AR(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function xR(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),n=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),r=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!n&&!r?null:{kind:"artifact",certainty:r?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function TR(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function IR(e,t){let i=[],n=mR("sha256").update(`${wR}
167
- [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Pr(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<xe.maxSignalsPerRelationship&&i.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(AR(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let f=xR(l,u);f&&o(f)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:TR(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Jm(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function _R(e,t){return Jm(e.classification)-Jm(t.classification)||ln(e.left,t.left)||ln(e.right,t.right)}function Gm(e,t,i,n){let r={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:vR,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:r,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:n}}function Ym(e){let t=PR(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(IR(t[s],t[c]));i.sort(_R);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=M(gR,{changes:t,relationships:n}),a=i.slice(0,xe.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Gm(t,i,a,r);for(;a.length>0&&ql(JSON.stringify(o))>xe.maxSerializedBytes;)a=a.slice(0,-1),o=Gm(t,i,a,r);if(ql(JSON.stringify(o))>xe.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as VP}from"node:crypto";import{promises as tt}from"node:fs";import ft from"node:path";import{createHash as nv}from"node:crypto";import Xm from"path";var zl="comet.native.implementation-scope.v2",rv="comet.native.content-snapshot-projection.v1",Ar="comet.native.content-snapshot-projection.v1",av="comet.native.implementation-scope.v2",OR="comet.native.unresolved-scope-id.v1",jR="comet.native.scope-detail-overflow.v1",$R="comet.native.snapshot-projection-overflow.v2",Kl=/^[a-f0-9]{64}$/u,Si=1024*1024,HR=128,FR=128;function ge(e,t){return e<t?-1:e>t?1:0}function Jl(e){if(!Kl.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function LR(e,t){return e===t?0:e===null?-1:t===null?1:ge(e,t)}function Zt(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 i=Xm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Xm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function ov(e,t){return e==="."?e:Zt(e,t)}function un(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function MR(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:Zt(e.path,`${t} path`),hash:e.hash,size:un(e.size,`${t} size`),type:"file"}}function DR(e,t){return{path:ov(e.path,`${t} path`),size:e.size===null?null:un(e.size,`${t} size`),type:e.type,reason:e.reason}}function BR(e,t){return ge(e.path,t.path)||ge(e.hash,t.hash)||e.size-t.size}function qR(e,t){return ge(e.path,t.path)||ge(e.reason,t.reason)||ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function xr(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
168
- `,"utf8")}function Qt(e,t,i){let n=`${t}
169
- ${Pr(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function VR(e){if(xr(e)<=Si)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=nv("sha256");a.update(`${$R}
170
- `),e.omissionOverflow&&Qt(a,"existing-overflow",e.omissionOverflow);let o=(d,p)=>{p||(n+=1),r+=1,Qt(a,"omission",d)},s=d=>{n+=1,r+=1,Qt(a,"entry",d)},c=()=>{for(let d=i.length-1;d>=0;d-=1){let p=i[d];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(d,1),p}return null},l=()=>({...e,complete:n===0,entries:t,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;xr(u)>Si;){if(i.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(i.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 f=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${f}`,hash:f,count:r}}}function Gl(e){let t=fr(e),i=t.entries.map((r,a)=>MR(r,`Snapshot entry ${a}`));if(i.sort(BR),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=t.omitted.map((r,a)=>DR(r,`Snapshot omission ${a}`));return n.sort(qR),VR({schema:rv,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:i,omitted:n,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function $o(e){let t=new Map;for(let[i,n]of e.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:Zt(n.path,`Declared artifact ${i} path`),kind:n.kind},a=t.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);t.set(r.path,r)}return[...t.values()].sort((i,n)=>ge(i.path,n.path)||ge(i.kind,n.kind))}function Ho(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Qm(e){return e?{hash:e.hash,size:e.size}:null}function sv(e,t,i){let n=0,r=0;for(;n<e.entries.length||r<t.entries.length;){let a=e.entries[n],o=t.entries[r],s=a===void 0?1:o===void 0?-1:ge(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(n+=1),s>=0&&(r+=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&&i({path:u,kind:c?l?"modified":"removed":"added",before:Qm(c),after:Qm(l)})}}function WR(e,t){return{...e,attributedTo:t.filter(i=>Ho(i,e.path))}}function St(e,t){return{id:`scope:${M(OR,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function zR(e,t){let i=t.omitted.map(n=>St({kind:"snapshot-omission",source:e,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${e} snapshot omitted ${n.path}: ${n.reason}`));return t.complete||i.push(St({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(St({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`)),i}function Zm(e,t){return zR(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Ul(e,t){return ge(e.kind,t.kind)||ge(e.source,t.source)||LR(e.path,t.path)||ge(e.id,t.id)}function JR(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Ul)}function GR(e){return[...new Set(e.map((t,i)=>Zt(t,`Git path ${i}`)))].sort(ge)}function cv(e){if(typeof e.contractHash!="string"||!Kl.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:$o(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:GR(e.gitChangedPaths)}}}function UR(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return sv(e,t,f=>{let d=i.some(p=>Ho(p,f.path));if(l+=1,d||(u+=1),a?.has(f.path)&&o.push(f.path),!c&&r.length<HR){let p=WR(f,i),m=xr(p);s+m<=Si?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function lv(e,t){return St({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 KR(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 i={changes:un(Number(t[1]),"Scope overflow change count"),unresolved:un(Number(t[2]),"Scope overflow unresolved count"),unattributed:un(Number(t[3]),"Scope overflow unattributed count")},n=ki(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(lv(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function YR(e){let t=nv("sha256");t.update(`${jR}
171
- `);let i=0;sv(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){Qt(t,"change",r);let a=0;for(let o of e.declaredArtifacts)Ho(o,r.path)&&(a+=1,Qt(t,"change-attribution",o));Qt(t,"change-end",{attributionCount:a}),a===0&&Qt(t,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)n>=e.detailedOmissionCount&&Qt(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function uv(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=UR(e,t,r,i.gitChangedPaths),s=M(Ar,e),c=M(Ar,t),l=[];for(let[g,S]of[["baseline",e],["current",t]])for(let k of S.omitted){if(l.length>=FR)break;l.push(St({kind:"snapshot-omission",source:g,path:k.path,evidence:{reason:k.reason,size:k.size,type:k.type}},`${g} snapshot omitted ${k.path}: ${k.reason}`))}let u=e.omitted.length+t.omitted.length,f=[...Zm("baseline",e),...Zm("current",t),...o.totalChanges===0&&a===null?[St({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")]:[]],d=()=>{if(i.gitChangedPaths===void 0)return;let g=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(S=>g.has(S)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(S=>!g.has(S))}},p=g=>{let S=o.candidates.slice(0,g.detailedChangeCount),k=S.filter(nt=>nt.attributedTo.length===0),C=o.totalChanges-S.length,B=o.totalUnattributed-k.length,K=u-g.detailedOmissionCount,D=B+K,J=[...k.map(nt=>St({kind:"unattributed-change",source:"implementation-scope",path:nt.path,evidence:{after:nt.after,before:nt.before,changeKind:nt.kind}},`Changed path is not covered by a declared artifact: ${nt.path}`)),...l.slice(0,g.detailedOmissionCount),...f,...C>0||D>0?[lv(g.overflowHash,{changes:C,unattributed:B,unresolved:D})]:[]],Y=JR(J),it=g.includeGitAdvisory?d():void 0;return{schema:zl,contractHash:n,baselineProjectionRef:Jl(s),baselineProjectionHash:s,currentProjectionRef:Jl(c),currentProjectionHash:c,complete:Y.length===0,declaredArtifacts:r,changes:S,unattributed:k,unresolvedScopes:Y,noCodeReason:a,...it?{gitAdvisory:it}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:w});if(xr({...g,scopeHash:w})<=Si)break;if(v){v=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let b=o.totalChanges>m||u>h?YR({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):w,N=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:b}),E={...N,scopeHash:M(av,N)};if(xr(E)>Si)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return E}function Yl(e){let t=Gl(e.baseline),i=Gl(e.current),n=cv(e);return{authority:n,baseline:t,current:i,scope:uv(t,i,n)}}var XR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Et(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ct(e,t,i,n){let r=new Set([...t,...i]),a=Object.keys(e).filter(s=>!r.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${n} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${n} is missing field(s): ${o.join(", ")}`)}function ki(e,t){if(typeof e!="string"||!Kl.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ev(e,t,i){let n=Jl(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function jo(e,t){let i=Et(e,"Native snapshot projection");if(Ct(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==rv)throw new Error("Native snapshot projection schema is invalid");let n=fr({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),r=Gl(n);if(M(Ar,i)!==M(Ar,r))throw new Error("Native snapshot projection is not canonical");let a=M(Ar,r);if(t!==void 0&&ki(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Xl(e,t){let i=Et(e,`Declared artifact ${t}`);if(Ct(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Zt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function tv(e,t){if(e===null)return null;let i=Et(e,t);return Ct(i,["hash","size"],[],t),{hash:ki(i.hash,`${t} hash`),size:un(i.size,`${t} size`)}}function iv(e,t){let i=Et(e,`Implementation change ${t}`);if(Ct(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let n=i.attributedTo.map(Xl),r=$o(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=tv(i.before,`Implementation change ${t} before`),o=tv(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.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:Zt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function QR(e,t){let i=Et(e,`Unresolved scope ${t}`);Ct(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let n=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!n.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?ov(i.path,`Unresolved scope ${t} path`):Zt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Oo(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((r,a)=>Zt(r,`${t} ${a}`)),n=[...new Set(i)].sort(ge);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function Fo(e){let t=Et(e,"Native implementation scope"),i=[...XR].filter(S=>S!=="gitAdvisory");if(Ct(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==zl)throw new Error("Native implementation scope schema is invalid");let n=ki(t.contractHash,"Implementation scope contractHash"),r=ki(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=ev(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=ki(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=ev(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(Xl);if(JSON.stringify(c)!==JSON.stringify($o(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(iv),u=[...l].sort((S,k)=>ge(S.path,k.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(S=>S.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(S=>`${S.kind}:${S.path}`));if(l.some(S=>S.attributedTo.some(k=>!f.has(`${k.kind}:${k.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(S=>JSON.stringify(S.attributedTo)!==JSON.stringify(c.filter(k=>Ho(k,S.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(iv),p=l.filter(S=>S.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(QR),h=m.filter(S=>S.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=h[0]===void 0?null:KR(h[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let w=t.noCodeReason,y=[...p.map(S=>St({kind:"unattributed-change",source:"implementation-scope",path:S.path,evidence:{after:S.after,before:S.before,changeKind:S.kind}},`Changed path is not covered by a declared artifact: ${S.path}`)),...l.length+(v?.changes??0)===0&&w===null?[St({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],b=m.filter(S=>S.kind==="unattributed-change"||S.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Ul))||new Set(m.map(S=>S.id)).size!==m.length||JSON.stringify(b)!==JSON.stringify(y.sort(Ul))||t.complete!==(m.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 N;if(t.gitAdvisory!==void 0){let S=Et(t.gitAdvisory,"Implementation scope Git advisory");if(Ct(S,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),S.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let k=Oo(S.changedPaths,"Git changed paths"),C=Oo(S.pathsPresentInSnapshotChanges,"Git present paths"),B=Oo(S.pathsAbsentFromSnapshotChanges,"Git absent paths"),K=[...C,...B].sort(ge),D=new Set(l.map(J=>J.path));if(JSON.stringify(K)!==JSON.stringify(k)||(v?.changes??0)===0&&C.some(J=>!D.has(J))||B.some(J=>D.has(J)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:k,pathsPresentInSnapshotChanges:C,pathsAbsentFromSnapshotChanges:B}}let E={schema:zl,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:w,...N?{gitAdvisory:N}:{}},g=ki(t.scopeHash,"Implementation scope scopeHash");if(M(av,E)!==g)throw new Error("Implementation scope content hash mismatch");return{...E,scopeHash:g}}function ZR(e){let t=Et(e,"Native implementation scope authority");if(Ct(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Xl);if(JSON.stringify(i)!==JSON.stringify($o(i)))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 n;t.gitChangedPaths!==void 0&&(n=Oo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=cv({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Lo(e){let t=Et(e,"Native implementation scope bundle");Ct(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=ZR(t.authority),n=jo(t.baseline),r=jo(t.current),a=Fo(t.scope),o=uv(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function fv(e){let t=Fo(e.scope);return Lo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}import dv from"node:path";var eP=/\b(Bearer|Basic)\s+[^\s"']+/giu,tP=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,iP=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,nP=/\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,rP=/("(?:[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,aP=/(["'])((?:[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,oP=/\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;function Ze(e){return e.replace(eP,"$1 [REDACTED]").replace(tP,"[REDACTED PRIVATE KEY]").replace(iP,"$1[REDACTED]@").replace(nP,"[REDACTED TOKEN]").replace(rP,'$1"[REDACTED]"').replace(aP,"$1$2$1$3$4[REDACTED]$4").replace(oP,"$1$2[REDACTED]")}var pv=/^[a-f0-9]{64}$/u;var sP="comet.native.acceptance-trace.v2",cP="comet.native.partial-allowance.v1",lP="comet.native.verification-evidence.v2";function Rt(e,t){if(!pv.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mv(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function vv(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 Ql(e,t,i=2e3){let n=Ze(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function Tr(e,t){let i=dv.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||dv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function uP(e,t,i){let n=Tr(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=ot(n),a=n.toLowerCase(),o=i?Tr(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Zl(e){let t=Tr(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 Mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Do(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function gv(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function hv(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let n=`runtime/evidence/${t}/${i}.json`;if(e!==n)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function fP(e){let t=Mo(e,"Native acceptance trace");if(Do(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"||!pv.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 i=Tr(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=Mo(o,`Native acceptance trace entry ${s}`);if(Do(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(f=>typeof f!="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(f=>Zl(f)),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:Tr(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Ql(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>fn(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||t.total!==n.length||t.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:n},a=Rt(t.traceHash,"Native acceptance trace hash");if(M(sP,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function wv(e){let t=Mo(e,"Native partial allowance");if(Do(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(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||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 i={schema:"comet.native.partial-allowance.v1",change:vv(t.change),scopeHash:Rt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Ql(t.reason,"Partial allowance reason"),confirmedSummary:Ql(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:mv(t.sourceRevision),confirmedAt:gv(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=Rt(t.allowanceHash,"Native partial allowance hash");if(M(cP,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function eu(e){let t=Mo(e,"Native verification evidence");if(Do(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 i=Rt(t.implementationScopeHash,"Native verification implementation scope hash"),n=fP(t.acceptanceTrace),r=Rt(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)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:Rt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>Zl(d));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(n.entries.flatMap(d=>d.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(d=>Zl(d));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:vv(t.change),sourceRevision:mv(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Rt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:hv(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:uP(t.reportRef,"Native verification report ref"),reportHash:Rt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:hv(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:gv(t.createdAt,"Native verification timestamp")},f=Rt(t.envelopeHash,"Native verification envelope hash");if(M(lP,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}import yv from"node:path";var Nv="comet.native.check-receipt.v1",dP="comet.native.check-receipt.v1",dn="scoped-text-safety",tu=1,Ve=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),hP=/^[a-f0-9]{64}$/u,pP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mP="comet.native.checker-policy.v1",vP="comet.native.check-input.v1",gP=2048,bv=M(mP,{policy:dn,version:tu,limits:Ve,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),wP=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),kv=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Ev=["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"],yP=new Set(Ev);function Ci(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ri(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Pt(e,t){if(typeof e!="string"||!hP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ei(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Cv(e,t){let i=Ei(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Sv(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function NP(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>gP||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 i=yv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||yv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function bP(e){let t=Ci(e,"Native check receipt checker");Ri(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Ci(t.limits,"Native check receipt limits");if(Ri(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==dn||t.version!==tu||t.hash!==bv||i.maxFiles!==Ve.maxFiles||i.maxFileBytes!==Ve.maxFileBytes||i.maxTotalBytes!==Ve.maxTotalBytes||i.maxIssues!==Ve.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:dn,version:tu,hash:bv,limits:{...Ve}}}function kP(e){let t=Ci(e,"Native check receipt contract");return Ri(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Pt(t.expectedHash,"Native check expected contract hash"),beforeHash:Pt(t.beforeHash,"Native check before contract hash"),afterHash:Pt(t.afterHash,"Native check after contract hash")}}function SP(e){let t=Ci(e,"Native check receipt implementation");return Ri(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Pt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Pt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Pt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Pt(t.afterSnapshotHash,"Native check after snapshot hash")}}function EP(e){let t=Ci(e,"Native check receipt counts");Ri(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:Ei(t.filesSelected,"Native check filesSelected"),filesScanned:Ei(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ei(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ei(t.bytesScanned,"Native check bytesScanned"),issueCount:Ei(t.issueCount,"Native check issueCount"),recordedIssueCount:Ei(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Ve.maxFiles||i.bytesScanned>Ve.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ve.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function CP(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||kv.indexOf(e.kind)-kv.indexOf(t.kind)}function RP(e){if(!Array.isArray(e)||e.length>Ve.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=Ci(n,`Native check issue ${r}`);if(Ri(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!wP.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:NP(a.path,`Native check issue ${r} path`),line:Cv(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(CP);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function PP(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!yP.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Ev.filter(n=>t.includes(n));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function AP(e){return M(vP,e)}function Rv(e){let t=Ci(e,"Native check receipt");if(Ri(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Nv)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!pP.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Cv(t.sourceRevision,"Native check source revision"),n=bP(t.checker),r=kP(t.contract),a=SP(t.implementation),o=AP({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Pt(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=Sv(t.startedAt,"Native check receipt startedAt"),c=Sv(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=EP(t.counts),u=RP(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 f=PP(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==f.length>0)throw new Error("Native check receipt stale flag is inconsistent");let d=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==d)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Ve.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Ve.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:Nv,change:t.change,sourceRevision:i,checker:n,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:f},m=Pt(t.receiptHash,"Native check receipt content hash");if(M(dP,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var nu="comet.native.verification-receipt.v3",xP=nu,TP="comet.native.declared-artifacts.v1",IP=/^[a-f0-9]{64}$/u,_P=/^acceptance-[a-f0-9]{64}$/u,OP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jP=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,$P=4096,HP=256,FP=1024;function hn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function ei(e,t,i){let n=Object.keys(e).sort(),r=[...t].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function At(e,t){if(typeof e!="string"||!IP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function et(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Ze(e).trim();if(!i||i.length>$P||i!==e.trim())throw new Error(`${t} is invalid`);return i}function iu(e,t){let i=et(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Ir(e,t,i=et,n=!1,r=HP){if(!Array.isArray(e)||e.length>r||!n&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function LP(e,t){if(typeof e!="string"||!_P.test(e))throw new Error(`${t} is invalid`);return e}function MP(e){let t=hn(e,"Native verification receipt bindings");if(ei(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!OP.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:At(t.contractHash,"Native verification receipt contract hash"),scopeHash:At(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:At(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:At(t.artifactHash,"Native verification receipt artifact hash")}}function DP(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=jP.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function BP(e,t,i,n){let r=hn(t,`Native ${e} evidence`);if(e==="automated-check"){if(ei(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=iu(r.startedAt,"Native automated-check start time"),o=iu(r.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&r.exitCode!==0||i==="failed"&&r.exitCode===0||i==="passed"&&(r.timedOut||r.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=hn(r.worktree,"Native automated-check worktree");if(ei(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=hn(r.afterFence,"Native automated-check after fence");if(ei(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:et(r.executable,"Native automated-check executable"),args:Ir(r.args,"Native automated-check arguments",et,!0),cwd:et(r.cwd,"Native automated-check cwd"),exitCode:r.exitCode,signal:r.signal,timedOut:r.timedOut,timeoutMs:r.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:et(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:At(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:At(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:At(r.outputHash,"Native automated-check output hash"),outputSummary:et(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){ei(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=DP(r.checkReceiptRef);if(At(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Ir(r.subjects,"Native static inspection subjects",et,n==="required-check"),rule:et(r.rule,"Native static inspection rule"),resultSummary:et(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ei(r,["steps","observations"],"Native manual-evidence evidence"),{steps:Ir(r.steps,"Native manual evidence steps"),observations:Ir(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function qP(e){let t=hn(e,"Native verification receipt");if(ei(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 i=t.kind,n=t.role,r=t.status,a=et(t.actor,"Native verification receipt actor"),o=Ir(t.acceptanceIds,"Native receipt acceptance IDs",LP,n==="required-check",FP).sort();if(n==="required-check"&&o.length!==0||n==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(n==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:nu,kind:i,role:n,status:r,bindings:MP(t.bindings),acceptanceIds:o,actor:a,issuedAt:iu(t.issuedAt,"Native verification receipt issue time"),evidence:BP(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==dn||s.actor!==`native-runtime:${dn}`))throw new Error("Native required check policy identity is invalid");return s}function Pv(e){let t=hn(e,"Native verification receipt");if(ei(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==nu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=qP(n),a=At(t.receiptHash,"Native verification receipt hash");if(M(xP,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function ru(e){return M(TP,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Iv=/^[a-f0-9]{64}$/u,pn=Si,v$=3*pn;function au(e,t){let i=ft.relative(e,t);return i===""||!ft.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ft.sep}`)}function WP(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Bo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return me(i,n)?j(i,n):j(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Av(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zP(e,t){let i=ft.resolve(e),n=ft.resolve(t);if(!au(i,n))throw new Error("Native evidence path is outside its change");let r=[await Av(i)],a=i;for(let o of ft.relative(i,n).split(ft.sep).filter(Boolean)){a=ft.join(a,o);let s=await Av(a);if(!au(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function xv(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!WP(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function JP(e,t,i={}){let n=await zP(t,ft.dirname(e));await i.afterParentChainCaptured?.();let r=await tt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await tt.realpath(e);if(!au(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await tt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),tt.lstat(e),tt.realpath(e)]);if(await xv(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Bo(s,r)||!Bo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>pn)throw new Error(`Native evidence document exceeds ${pn} bytes`);await i.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=pn+1-f,w=await o.read(d,0,Math.min(d.length,v),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,f>pn)throw new Error(`Native evidence document exceeds ${pn} bytes`);u.push(Buffer.from(d.subarray(0,w.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),tt.lstat(e),tt.realpath(e)]);if(await xv(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Bo(s,p)||!Bo(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function _v(e,t){if(!Iv.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function GP(e,t,i,n,r){if(!Iv.test(i))throw new Error("Native report evidence hash is invalid");let a=await Pi({paths:e,name:t,kind:"reports",hash:i,hooks:n,changeDir:r});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!==i||typeof o.content!="string"||VP("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function mn(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function UP(e,t,i,n,r){return ft.join(r??W(e,t),..._v(i,n).split("/"))}async function Pi(e){let t=e.changeDir??W(e.paths,e.name),i=UP(e.paths,e.name,e.kind,e.hash,t);return await $(e.paths.nativeRoot,i),JP(i,t,e.hooks)}function Tv(e,t){return jo(e,t)}function KP(e,t){let i=Fo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function YP(e,t,i){let n=wv(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function XP(e,t,i){let n=eu(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function QP(e,t,i,n=!1,r){let a=await ou(e,t,i.implementationScopeRef,void 0,r);if(n&&await GP(e,t,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await Ov(e,t,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function qo(e,t,i,n,r){let a=mn(i,"scopes"),o=KP(await Pi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=mn(o.baselineProjectionRef,"snapshots"),c=mn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Pi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(f=>Tv(f,s)),Pi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(f=>Tv(f,c))]);return fv({baseline:l,current:u,scope:o})}async function ou(e,t,i,n,r){return(await qo(e,t,i,n,r)).scope}async function Ov(e,t,i,n,r){let a=mn(i,"allowances");return YP(await Pi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function su(e,t,i,n,r){let a=mn(i,"receipts"),o=Pv(await Pi({paths:e,name:t,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function jv(e,t,i,n,r){let a=mn(i,"verifications"),o=XP(await Pi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await QP(e,t,o,!1,r),o}var ZP=4096;async function eA(e,t=xe.maxChanges){try{let i=await zt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function $v(e,t){let i=await de(e,t),[n,r]=await Promise.all([i.implementation_scope?ou(e,t,i.implementation_scope):null,yt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:n?.declaredArtifacts??[],workspaceIdentityHash:r?.nativeRootId??null}}async function Hv(e,t,i={}){let r=(await eA(e,ZP)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!r.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await $v(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await $v(e,c).catch(f=>{if(i.tolerateInvalidSiblings)return null;throw f});if(!l)continue;let u=Ym([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"]:[]]}}import{promises as uA}from"fs";import fA from"path";import{isDeepStrictEqual as wu}from"util";var cu={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var tA=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function iA(e,t){return e<t?-1:e>t?1:0}function nA(e,t,i,n){if(!Array.isArray(e)||e.length>i||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let r=e.map(a=>{if(typeof a!="string"||!tA.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(iA)}function Fv(e=[]){return nA(e,"Native repair failed check IDs",cu.maxFailedCheckIds,!0)}function lu(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 rA=/^[a-f0-9]{64}$/u;var Lv=["disposition","overrideSummaryHash","signatureHash"],aA=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function fu(e,t){return e<t?-1:e>t?1:0}function oA(e,t,i){let n=Object.keys(e).sort(fu);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function sA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function uu(e,t){if(typeof e!="string"||!rA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function cA(e){if(!Array.isArray(e)||e.length>cu.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(fu)}function Mv(e){let t=sA(e,"Native repair trajectory projection"),i=Object.keys(t).sort(fu),n=i.length===Lv.length&&i.every((l,u)=>l===Lv[u]);n||oA(t,aA,"Native repair trajectory projection");let r=uu(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:uu(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(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=uu(t.contractHash,"Native repair trajectory contract hash"),s=cA(t.failedAcceptanceIds),c=Fv(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}var ti={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:[]},du=z("comet-native-runtime:v3:semantic-repair-budget"),lA=[{skillVersion:"2",skillHash:z("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:z("comet-native-runtime:v1")}];function Dv(e){return e.skillVersion===ti.definition.metadata.version&&e.skillHash===du||lA.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var hu={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function _r(e){let i={sequence:(await wi(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await fm(e.changeDir,e.run.trajectoryRef,i),i}async function Vo(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:z(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await dm(e.changeDir,e.run.checkpointRef,t),t}function Bv(e){return z(JSON.stringify({summary:e.summary,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}))}var Kv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],dA=new Set(Kv),Yv=new Set([...Kv,"minimum_runtime_version","revision"]),hA=new Set([...Yv,"operation"]),pA=512*1024,mu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),mA=new Set([...mu,"implementationScopeHash","repairScopeHash","repairStagnation"]),vu=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function zo(e,t){return fA.join(W(e,t),"runtime","transition.json")}function vA(e){return`transition-${e}`}async function gA(e,t,i){let n=vA(t);return Wi(e,n,i)}async function Jo(e,t,i,n){let r=await gA(e,t,i);try{return await n()}finally{await zi(r)}}function Go(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function yu(e,t){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Wo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function dt(e,t){return wu(e,t)}function gu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,n=Object.keys(i),r=n.find(u=>!mA.has(u)),a=[...mu].find(u=>!Object.hasOwn(i,u)),o=mu.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(lu(i.summary,"Native transition journal event summary"),Ze(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.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(i.noCodeReason!==null&&(lu(i.noCodeReason,"Native transition journal event no-code reason"),Ze(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Mv(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function wA(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return gu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return gu(e,t)}function Nu(e,t,i=!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 n=i?wA(e.eventData,e.evidenceHash):gu(e.eventData,e.evidenceHash),r=Cl(e.nextRun),a=e.previousRun===null?null:Cl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function qv(e,t,i=!1){if(e.skill!==ti.definition.metadata.name||(i?!Dv(e):e.skillVersion!==ti.definition.metadata.version||e.skillHash!==du)||e.orchestration!==ti.definition.orchestration.mode||e.pendingRef!==lt.pendingRef||e.trajectoryRef!==lt.trajectoryRef||e.contextRef!==lt.contextRef||e.artifactsRef!==lt.artifactsRef||e.checkpointRef!==lt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Vv(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 Wv(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 bu(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(qv(a,"next Run",n||r!==null),Wv(a,"next Run"),a.runId!==t.run_id||a.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(e.run_id!==null||e.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(qv(r,"previous Run",!0),Wv(r,"previous Run"),e.run_id!==r.runId||r.currentStep!==e.phase||t.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!wu(Vv(r),Vv(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function yA(e,t,i){return z(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Xv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function zv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function ku(e,t,i,n,r=!1){let a=i.eventData,o=zv(e),s=zv(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(n==="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&&wu(e.spec_changes,t.spec_changes),l=Bv({summary:a.summary});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||i.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(n==="spec-rebase"){let c=yA(e.name,a.summary,t.spec_changes),l=z(`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||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.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 NA(e,t){let i=Go(e);if(yu(i,hA),i.schema!==on)throw new Error(`Expected Native transition schema ${on}`);let n=Wo(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${on} minimum_runtime_version must be ${3}`);let r=Wo(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=Nu(i,t),o=ut(i.previousState),s=ut(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(ku(o,s,a,i.operation),bu(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:on,minimum_runtime_version:3,revision:r,operation:i.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 bA(e,t){let i=Go(e);if(yu(i,dA),i.schema!==yr)throw new Error(`Expected Native transition schema ${yr}`);let n=Nu(i,t,!0),r=Er(i.previousState),a=Er(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return ku(r,a,n,Xv(r,a,n.eventData),!0),bu(r,a,n,!0),{schema:yr,id:n.id,change:t,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function kA(e,t){let i=Go(e);if(yu(i,Yv),i.schema!==sn)throw new Error(`Expected Native transition schema ${sn}`);if(Wo(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${sn} minimum_runtime_version must be 2`);let r=Wo(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Nu(i,t,!0),o=Cr(i.previousState),s=Cr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(ku(o,s,a,Xv(o,s,a.eventData),!0),bu(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:sn,minimum_runtime_version:2,revision:r,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 SA(e,t){let i=Go(e);if(i.schema===on)return{status:"current",journal:NA(i,t)};if(i.schema===yr)return{status:"migration-required",journal:bA(i,t)};if(i.schema===sn)return{status:"migration-required",journal:kA(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function EA(e,t){let i=zo(e,t);await $(e.nativeRoot,i);try{let n=await re({root:e.nativeRoot,file:i,maxBytes:pA,label:`Native transition journal ${t}`});return SA(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function pu(e,t){let i=await EA(e,t);if(!i)return null;if(i.status==="migration-required")throw new vu(t);return i.journal}function Jv(e,t){if(dt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(dt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Gv(e,t){if(dt(e,t.nextState))return"next";if(dt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function CA(e){let{journal:t}=e;return Qv({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Qv(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Uv(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=CA({sequence:a.index+1,journal:t,type:a.event.type});if(!dt(Qv(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function Su(e,t,i){if(await cn(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Eo(e,t);let n=await pu(e,t);if(!n)return null;let r=W(e,t),a=Uv(await wi(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([an(r),de(e,t)]),c=Jv(o,n),l=Gv(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await So(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!dt(await an(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await To(e,n.nextState,n.previousState.revision);if(!dt(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!dt(await de(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await pu(e,t);if(!u||!dt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let f=Uv(await wi(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(f.started||await _r({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let d=f.transitioned;d||(d=await _r({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Vo({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([an(r),de(e,t)]);Jv(p,{...n,previousRun:n.nextRun}),Gv(m,{...n,previousState:n.nextState});let h=await pu(e,t);if(!h||!dt(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await uA.rm(zo(e,t),{force:!0}),n.nextState}import Zv from"node:path";var RA="comet.native.acceptance.v1",PA=/^acceptance-[a-f0-9]{64}$/u,AA=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),xA=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var mH=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Or=Object.freeze({maxCriteria:1024}),eg="<!-- comet-native:acceptance-evidence:start -->",tg="<!-- comet-native:acceptance-evidence:end -->";function Ru(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 Eu(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let n=i[1][0];return t===null?{marker:n,length:i[1].length}:n===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function ig(e){return e.includes("-->")||e.includes("--!>")}function*vn(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
142
+ `,i)+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 i=dn(t),r=$t(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=dn(t),r=$t(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.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())}}};qu.Parser=Vo});var Uu=y(Ii=>{"use strict";var Wu=Ao(),vg=Si(),Ti=xi(),gg=xa(),wg=P(),yg=Mo(),zu=qo();function Ju(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new yg.LineCounter||null,prettyErrors:t}}function Ng(e,t={}){let{lineCounter:i,prettyErrors:r}=Ju(t),n=new zu.Parser(i?.addNewLine),a=new Wu.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Ti.prettifyError(e,i)),s.warnings.forEach(Ti.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Gu(e,t={}){let{lineCounter:i,prettyErrors:r}=Ju(t),n=new zu.Parser(i?.addNewLine),a=new Wu.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 Ti.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Ti.prettifyError(e,i)),o.warnings.forEach(Ti.prettifyError(e,i))),o}function bg(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Gu(e,i);if(!n)return null;if(n.warnings.forEach(a=>gg.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:r},i))}function kg(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return wg.isDocument(e)&&!r?e.toString(i):new vg.Document(e,r,i).toString(i)}Ii.parse=bg;Ii.parseAllDocuments=Ng;Ii.parseDocument=Gu;Ii.stringify=kg});var ji=y(x=>{"use strict";var Sg=Ao(),Eg=Si(),Pg=co(),Wo=xi(),xg=si(),Xe=P(),Rg=Je(),Cg=I(),Ag=Ue(),_g=Ke(),Tg=ln(),Ig=Lo(),jg=Mo(),$g=qo(),hn=Uu(),Ku=ri();x.Composer=Sg.Composer;x.Document=Eg.Document;x.Schema=Pg.Schema;x.YAMLError=Wo.YAMLError;x.YAMLParseError=Wo.YAMLParseError;x.YAMLWarning=Wo.YAMLWarning;x.Alias=xg.Alias;x.isAlias=Xe.isAlias;x.isCollection=Xe.isCollection;x.isDocument=Xe.isDocument;x.isMap=Xe.isMap;x.isNode=Xe.isNode;x.isPair=Xe.isPair;x.isScalar=Xe.isScalar;x.isSeq=Xe.isSeq;x.Pair=Rg.Pair;x.Scalar=Cg.Scalar;x.YAMLMap=Ag.YAMLMap;x.YAMLSeq=_g.YAMLSeq;x.CST=Tg;x.Lexer=Ig.Lexer;x.LineCounter=jg.LineCounter;x.Parser=$g.Parser;x.parse=hn.parse;x.parseAllDocuments=hn.parseAllDocuments;x.parseDocument=hn.parseDocument;x.stringify=hn.stringify;x.visit=Ku.visit;x.visitAsync=Ku.visitAsync});import{randomUUID as qN}from"node:crypto";import{promises as q}from"node:fs";import U from"node:path";import{execFileSync as Jf}from"child_process";import ei from"path";function Zt(e,t){return Jf("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Gf(e,t){let i=ei.normalize(e),r=ei.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function F(e){try{let t=ei.resolve(Zt(e,["rev-parse","--show-toplevel"])),r=Zt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?ei.resolve(r.slice(9)):t,a=null;try{a=Zt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Gf(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function St(e){try{Zt(e,["rev-parse","--is-inside-work-tree"])}catch{return[]}return Zt(e,["worktree","list","--porcelain","-z"]).split("\0").filter(i=>i.startsWith("worktree ")).map(i=>ei.resolve(i.slice(9)))}import{randomUUID as Uf}from"crypto";import{promises as W}from"fs";import fe from"path";function Me(e){return e!==0&&e!==0n&&e!=="0"}function te(e,t){return Me(e.dev)&&Me(t.dev)&&Me(e.ino)&&Me(t.ino)}function A(e,t){let i=Me(e.dev)&&Me(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Me(e.ino)&&Me(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}function ca(e,t){let i=fe.relative(e,t);return i===""||!fe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${fe.sep}`)}function Kf(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function sa(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return te(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ac(e){let t=await W.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 W.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ti(e){for(let t of e){let i=await W.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kf(t,i)||await W.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Yf(e,t){let i=fe.resolve(e),r=fe.resolve(t);if(!ca(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await ac(i)],a=fe.relative(i,r).split(fe.sep).filter(Boolean),o=i;for(let s of a){await ti(n),o=fe.join(o,s);try{await W.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await ac(o);if(!ca(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ti(n),n}async function Xf(e){let t;try{t=await W.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function Qf(e,t,i={}){let r=fe.dirname(e),n=i.containedRoot?await Yf(i.containedRoot,r):null;n||await W.mkdir(r,{recursive:!0});let a=fe.join(r,`.${fe.basename(e)}.${Uf()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await W.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([W.lstat(a),W.realpath(a)]);if(await ti(n),!c.isFile()||c.isSymbolicLink()||!sa(s,c)||!ca(n[0].realPath,l))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(),!sa(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await ti(n);let c=await W.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!sa(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await W.link(a,e),await W.unlink(a)):await W.rename(a,e),await Xf(r)}catch(c){if(await o?.close(),!n)await W.rm(a,{force:!0});else try{await ti(n),await W.rm(a,{force:!0})}catch{}throw c}}async function K(e,t,i={}){await Qf(e,t,i)}async function Y(e,t,i={}){await K(e,JSON.stringify(t,null,2)+`
143
+ `,i)}import{createHash as ih}from"node:crypto";import{promises as he}from"node:fs";import ae from"node:path";import{TextDecoder as rh}from"node:util";var Zf=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),eh=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function th(e){return e.toLowerCase().startsWith(".env")}function ii(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>th(r))?"environment-file":i.some(r=>eh.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Zf.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}var pr=1024*1024;function la(e,t){let i=ae.relative(e,t);return i===""||!ae.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ae.sep}`)}function nh(e){let t=ae.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})||ae.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 i=e.toLowerCase(),r=ii(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function ah(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function oh(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return te(i,r)?A(i,r):A(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function oc(e){let t=await he.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await he.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sh(e,t){let i=ae.resolve(e),r=ae.resolve(t);if(!la(i,r))throw new Error("Native artifact path is outside its root");let n=[await oc(i)],a=i;for(let o of ae.relative(i,r).split(ae.sep).filter(Boolean)){a=ae.join(a,o);let s=await oc(a);if(!la(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function sc(e){for(let t of e){let i=await he.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!oh(t,i)||await he.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function B(e){let t=nh(e.ref),i=e.maxBytes===null?null:ah(e.maxBytes??pr),r=ae.resolve(e.root,...t.split("/")),n=await sh(e.root,ae.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await he.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await he.realpath(r);if(!la(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await he.open(r,"r");try{let[c,l,d]=await Promise.all([s.stat(),he.lstat(r),he.realpath(r)]);if(await sc(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!hr(a,c)||!hr(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],u=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let w=i===null?p.length:i+1-u,k=await s.read(p,0,Math.min(p.length,w),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,i!==null&&u>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),he.lstat(r),he.realpath(r)]);if(await sc(n),!h.isFile()||h.isSymbolicLink()||m!==o||!hr(c,v)||!hr(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(f,u),N;try{N=new rh("utf-8",{fatal:!0}).decode(g)}catch(w){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:w})}return{ref:t,size:u,hash:e.includeHash===!1?null:ih("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var Is=fr(ji(),1);import Jt from"path";var Jo=fr(ji(),1);import pn from"path";var Oi=64*1024,mn=1024,vn=64,Go=5,Og=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Hg=["**/.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"],Dg=[...Og,...Hg].sort((e,t)=>e.localeCompare(t,"en"));var ie={include:["**/*"],exclude:[...Dg],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Bg(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||pn.posix.isAbsolute(i)||pn.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function ut(e){let t=Bg(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Xu(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Uo(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||pn.posix.isAbsolute(r)||pn.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.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(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function $i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Qu(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Ko(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>mn)throw new Error(`${t} exceeds ${mn} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>vn)throw new Error(`${t} contains more than ${vn} wildcard tokens`);return e}function Yu(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Ko(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function zo(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function Lg(e){if(e===void 0)return{...ie,include:[...ie.include],exclude:[...ie.exclude]};let t=$i(e,"native.snapshot");return{include:Yu(t.include,"native.snapshot.include",ie.include),exclude:Yu(t.exclude,"native.snapshot.exclude",ie.exclude),max_files:zo(t.max_files,ie.max_files,"native.snapshot.max_files"),max_total_bytes:zo(t.max_total_bytes,ie.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:zo(t.max_duration_ms,ie.max_duration_ms,"native.snapshot.max_duration_ms")}}function Fg(e){if(e===void 0)return;let t=$i(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="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=$i(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=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 d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:ut(r),toArtifactRoot:ut(n),stage:a,...o?{cleanup:o}:{}}}function Mg(e,t={}){let i=$i(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Go;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Fg(i.pending_root_move);return{artifact_root:ut(r),language:Qu(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Lg(i.snapshot),...s?{pending_root_move:s}:{}}}function Vg(e){let t=$i(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="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");return{artifact_layout:Xu(t.artifact_layout),language:Qu(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function qg(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Wg(e,t,i,r,n){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!n.allowPartialProject&&e.native!==void 0)||n.allowPartialProject&&!a)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 s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:r,...t?{native:t}:{},...i?{classic:i}:{}}}function Hi(e,t={}){let i=(0,Jo.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=qg(n.ambient_resume),o=n.native===void 0?void 0:Mg(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=n.classic===void 0?void 0:Vg(n.classic),c=Wg(n,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function gn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:ut(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Go,snapshot:{...ie,include:[...ie.include],exclude:[...ie.exclude]}}}}import{createHash as Jg}from"crypto";import{promises as Nn}from"fs";import Qe from"path";import{constants as wn,promises as dt}from"fs";var ve=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Yo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Zu(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Di(e){return{dev:e.dev,ino:e.ino,birthtime:Yo(e)}}function yn(e,t){let i=Di(e),r=Di(t);return te(i,r)?A(i,r):A(i,r)&&Yo(e)===Yo(t)&&Zu(e)===Zu(t)&&e.size===t.size}async function ft(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await dt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ve("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ve("too-large",`${r} exceeds ${t} bytes`);let o=await dt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Di(a)});let s=process.platform==="win32"?wn.O_RDONLY:wn.O_RDONLY|wn.O_NOFOLLOW|wn.O_NONBLOCK,c;try{c=await dt.open(e,s)}catch(l){throw l.code==="ELOOP"?new ve("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,d,f]=await Promise.all([c.stat({bigint:n}),dt.lstat(e,{bigint:n}),dt.realpath(e)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||f!==o||!yn(a,l)||!yn(a,d))throw new ve("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:Di(l)}),await i.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:w}=await c.read(v,0,Math.min(v.length,N),null);if(w===0)break;if(p+=w,p>t)throw new ve("too-large",`${r} exceeds ${t} bytes`);u.push(Buffer.from(v.subarray(0,w)))}await i.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),dt.lstat(e,{bigint:n}),dt.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!yn(a,h)||!yn(a,m))throw new ve("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:g,identity:Di(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await c.close()}}function zg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Xo(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}async function ed(e,t){let i=Qe.resolve(e),r=await Nn.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Nn.realpath(i)}async function td(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Qe.join(n,i[a]);let o;try{o=await Nn.lstat(n)}catch(d){if(zg(d))return{exists:!1,kind:"missing"};throw d}let s=Qe.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Nn.realpath(n);if(!Xo(t,l))throw new Error(`${r.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 Ot(e,t,i){let r=Uo(t,i.label),n=Qe.resolve(e),a=await ed(n,i.label),o=r.split("/"),s=Qe.resolve(n,...o);if(!Xo(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await td(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Ze(e,t,i,r){let n=await Ot(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await ed(n.projectRoot,r.label);return ft(n.target,i,{...r,verify:async(o,s)=>{if(!Xo(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await td(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Bi=".comet/config.yaml";function Gg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Qo(e,t={}){return(await bn(e,t)).document}async function Ug(e){try{return(await Ze(e,Bi,Oi,{label:Bi})).bytes}catch(t){if(Gg(t))return null;throw t}}function Kg(e){return e?{exists:!0,sha256:Jg("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function bn(e,t={}){let i=await Ug(e);return{document:i?Hi(i.toString("utf8"),t):null,identity:Kg(i)}}var oE=16*1024;import{existsSync as rd,promises as ht}from"fs";import R from"path";import ew from"os";var kn=".comet/config.yaml",tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function ts(e){try{return await ht.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function iw(e){try{let t=await ht.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Dt(e,t){let i=R.relative(e,t);return i===""||!R.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${R.sep}`)}async function Ht(e){let t=[],i=e;for(;!await ts(i);){let n=R.dirname(i);if(n===i)break;t.push(R.basename(i)),i=n}let r=await ht.realpath(i);return R.resolve(r,...t.reverse())}async function is(e){try{return(await ht.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Sn(e){let t=R.resolve(e);try{(await ht.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=R.resolve(ew.homedir());for(;;){if(!(t===r&&i!==r)){let o=R.join(t,...kn.split("/")),s=t===i||await iw(o);if(await ts(o)&&s)return t}if(await ts(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return i;t=a}}function En(e){return ut(e)}async function rw(e,t){let i=En(t),r=R.resolve(e,...i.split("/")),n=await ht.realpath(e),a=await Ht(r);if(!Dt(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Bt(e,t){let i=En(t),r=await rw(e,i),n=R.join(r,"comet");if(await is(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ht(r),Ht(n)]);if(!Dt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(e),c=R.join(s,".comet","runtime","native");if(await is(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,d]=await Promise.all([ht.realpath(s),Ht(c)]);if(!Dt(l,d))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...kn.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:c,changesRuntimeDir:R.join(c,"changes"),locksDir:R.join(c,"locks"),transactionsDir:R.join(c,"transactions")}}function nd(e){if(!tw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ee(e,t){nd(t);let i=R.join(e.changesRuntimeDir,t);if(!D(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function rs(e,t){nd(t);let i=R.join(e.changesDir,t,"runtime");if(!D(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function Pe(e,t){let i=Ee(e,t);if(rd(i))return i;let r=rs(e,t);return rd(r)?r:i}function xe(e,t){let i=R.resolve(t);if(D(e.runtimeDir,i))return e.runtimeDir;if(D(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function D(e,t){return Dt(R.resolve(e),R.resolve(t))}async function T(e,t){let i=R.resolve(e),r=R.resolve(t);if(!Dt(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await is(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ht(i),Ht(r)]);if(!Dt(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}function aw(e="docs",t="en"){return gn(e,t)}async function Re(e){let t=(await Qo(e))?.config??null;return t?.native?t:null}async function Fi(e){let t=await Re(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 ad(e){let t=await Sn(e.startPath),i=await Re(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${kn} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?En(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??aw(r??"docs"),a=await Bt(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as jy}from"fs";import $y from"path";import{AsyncLocalStorage as ow}from"async_hooks";import{randomUUID as cd}from"crypto";import{promises as se}from"fs";import ld from"os";import G from"path";var od=16*1024,ud=".coordinator",sw=5e3,sd=new ow,Pn=new Map;function cw(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function lw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function dd(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 ns(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return te(i,r)?A(i,r):A(i,r)&&e.size===t.size}function as(e,t){return ns(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function $e(e){let t,i;try{let r=await ft(e,od,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof ve?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${od} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:lw(JSON.parse(t.toString("utf8")),e),identity:dd(i)}}async function uw(e){return(await $e(e))?.owner??null}function fd(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==ld.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vw(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dw(e,t){try{await se.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await se.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function os(e,t){let i=await $e(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!as(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await se.mkdir(t,{recursive:!0});let r=G.join(t,`${G.basename(e.file)}.${e.owner.id}.${cd()}.removed`);try{await se.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await $e(r);if(!n||n.owner.id!==e.owner.id||!ns(n.identity,e.identity))throw await dw(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await se.rm(r,{force:!0}),"removed"}function hd(e){return{id:cd(),pid:process.pid,hostname:ld.hostname(),createdAt:new Date().toISOString(),operation:e}}async function pd(e,t){let i;try{i=await se.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await uw(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
144
+ `,"utf8"),await i.sync(),dd(await i.stat({bigint:!0}))}finally{await i.close()}}async function fw(e,t){let i=await T(e.runtimeDir,e.locksDir);await se.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,G.join(i,ud));await se.mkdir(r,{recursive:!0});let n=hd(t),a=G.join(r,`.${n.id}.tmp`),o=G.join(r,`${n.id}.claim`);try{let s=await pd(a,n);await se.rename(a,o);let c=await $e(o);if(!c||!ns(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await se.rm(a,{force:!0})}}async function hw(e){let t=G.dirname(e.file),i=!1,r=G.basename(e.file);for(let n of await se.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=G.join(t,n.name);if(G.resolve(a)!==G.resolve(e.file))try{let o=await $e(a),s=fd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await os(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function md(e){let t=await $e(e.file);if(t){if(t.owner.id!==e.owner.id||!as(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await os(t,G.dirname(e.file))}}async function pw(e,t){let i=Date.now()+sw;for(;;){let r=await fw(e,t);if(!await hw(r))return r;if(await md(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function mw(e){let t=Pn.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Pn.set(e,n),await t,()=>{i(),Pn.get(e)===n&&Pn.delete(e)}}async function vd(e,t,i){let r=G.resolve(e.locksDir),n=sd.getStore();if(n?.has(r))return i();let a=await mw(r);try{let o=await pw(e,t),s=new Map(n??[]);return s.set(r,o),await sd.run(s,async()=>{try{return await i()}finally{await md(o)}})}finally{a()}}async function xn(e,t,i){return vd(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await se.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,G.join(r,cw(t))),a=hd(i),o=await pd(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Rn(e){await $e(e.file)&&await vd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${G.basename(e.file)}`,async()=>{let t=await $e(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!as(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=G.join(e.locksDir,ud);await os(t,i)})}function vw(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function gd(e){return fd(await $e(e))}import bs from"node:path";import Jw from"node:path";import yd from"node:path";import{createHash as gw}from"crypto";function ge(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function ww(e,t){t.has(e)&&ge("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||ge("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&ge("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ge("symbol properties are not supported"),`[${e.map(r=>ss(r,t)).join(",")}]`}finally{t.delete(e)}}function yw(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ge("only plain objects are supported"),t.has(e)&&ge("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ge("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&ge("accessor properties are not supported"),`${JSON.stringify(o)}:${ss(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ss(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||ge("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?ww(e,t):yw(e,t);case"bigint":case"function":case"symbol":case"undefined":return ge(`${typeof e} values are not supported`)}return ge("unsupported value type")}function cs(e){return ss(e,new Set)}function ce(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 gw("sha256").update(`${e}
145
+ ${cs(t)}`).digest("hex")}var Nw="comet.native.acceptance.v1";var LE=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),qi=Object.freeze({maxCriteria:1024});function us(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 ls(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function wd(e){return e.includes("-->")||e.includes("--!>")}function*Mi(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
172
146
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
173
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&n===null,index:s},s+=1,t!==null)t=Eu(l,t);else if(i)ig(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=Eu(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!ig(d))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&r.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(n=p[1])}}}if(c===-1)break;o=c+1}}function TA(e){return[...vn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Cu(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function IA(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Pu(e,t,i,n=[]){let r=Cu(i),a=t.replaceAll("\\","/").trim(),o=n.map(Cu);if(r.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:`acceptance-${M(RA,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function Au(e,t){let i=new Set;for(let n of e){if(i.has(n.id))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(n.id)}return e}function _A(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of vn(e)){r=s+1;let c=o?Ru(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(n+=1,n===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(n===0||t===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??r}}function ng(e,t="brief.md",i=Or.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=_A(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of vn(e)){if(u<n.start||u>=n.end)continue;let f=l?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(f===null)continue;let d=f[1].length;r=r===null?d:Math.min(r,d)}let a=[],o=null,s=()=>{if(o!==null){if(a.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);a.push(o)}};for(let{line:c,body:l,index:u}of vn(e)){if(u<n.start||u>=n.end)continue;let f=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;f&&f[1].length===r?(s(),o=[f[2]]):o!==null&&o.push(c)}return s(),Au(a.map(c=>Pu("brief-example",t,c.join(`
174
- `))),"Brief")}function rg(e,t="spec.md",i=Or.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=()=>{if(a!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Pu("spec-scenario",t,[a.title,...a.body].join(`
175
- `),a.context)),a=null}};for(let{line:s,body:c}of vn(e)){let l=c?Ru(s):null,u=l?/^Scenario\s*:\s*(.*)$/iu.exec(l.text):null;if(u){for(o();r.at(-1)&&r.at(-1).level>=l.level;)r.pop();let f=Cu(u[1]);if(f.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:f,body:[],context:r.map(d=>d.text)}}else if(l){for(a!==null&&l.level<=a.level?o():a!==null&&a.body.push(s);r.at(-1)&&r.at(-1).level>=l.level;)r.pop();r.push(l)}else a!==null&&c&&a.body.push(s)}return o(),Au(n,"Specification")}function ag(e,t="spec.md",i=Or.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Pu("spec-must",t,o.parts.join(" "),o.context)),o=null}},c=()=>r.some(l=>/^(?:non-?goals?|非目标)$/iu.test(l.text.trim()));for(let{line:l,body:u}of vn(e)){let f=u?Ru(l):null;if(f){for(s(),a!==null&&f.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=f.level;)r.pop();r.push(f),/^Scenario\s*:/iu.test(f.text)&&(a=f.level);continue}let d=l.trim();if(!u||a!==null||c()){s();continue}if(d.length===0||Eu(l,null)!==null||d.startsWith("<!--")||d==="-->"||d==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(d)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(d)||/^(?:[-*_]\s*){3,}$/u.test(d)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(d)){s();continue}let p=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(p){s(),o={parts:[p[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(d)){s(),o={parts:[d],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[d],context:r.map(m=>m.text)}:o.parts.push(d)}return s(),Au(n,"Specification mandatory requirements")}function OA(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||IA(i)||Zv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let n=Zv.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!xA.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function jA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,n=Object.keys(i).filter(r=>!AA.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function og(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,n)=>{let r=jA(i,n),a=r.acceptance_id;if(typeof a!="string"||!PA.test(a))throw new Error(`Acceptance evidence entry ${n} 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(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.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 OA(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.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 sg(e){let t=TA(e);if(t.some(({line:l,body:u})=>!u&&(l===eg||l===tg)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},f)=>u&&l===eg?[f]:[]),r=t.flatMap(({line:l,body:u},f)=>u&&l===tg?[f]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(n[0]+1,r[0]).map(({line:l})=>l).join(`
176
- `).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=og(o),c=$A(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function $A(e){let t=og([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(t,null,2)}import cg from"node:path";var HA="comet.native.contract.v1",FA="comet.native.acceptance-set.v1",lg=/^[a-f0-9]{64}$/u,jr={maxAcceptanceCriteria:Or.maxCriteria};function ug(e,t){let i=cg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||cg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function fg(e){return M("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
177
- `))}function LA(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(lg))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(lg))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=ug(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:fg(e.markdown)},markdown:e.markdown}}function MA(e,t){return dg(e.id,t.id)}function dg(e,t){return e<t?-1:e>t?1:0}function hg(e){let t=ug(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(LA).sort((f,d)=>dg(f.snapshot.capability,d.snapshot.capability)),n=i.map(({snapshot:f})=>f.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[t,...i.flatMap(({snapshot:f})=>f.source===null?[]:[f.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=ng(e.briefMarkdown,t,jr.maxAcceptanceCriteria);for(let{snapshot:f,markdown:d}of i)d===null||f.source===null||(a.push(...rg(d,f.source,jr.maxAcceptanceCriteria-a.length)),a.push(...ag(d,f.source,jr.maxAcceptanceCriteria-a.length)));if(a.sort(MA),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>jr.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${jr.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:f})=>f);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:fg(e.briefMarkdown)},c=i.map(({snapshot:f})=>f),l=M(FA,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(HA,u)}}var Uo={maxSpecs:64,maxFileBytes:Yn,maxTotalBytes:4*1024*1024};async function xu(e){if(e.specChanges.length>Uo.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ye({root:e.changeDir,ref:e.briefRef,maxBytes:Uo.maxFileBytes}),i=t.size,n=[];for(let r of e.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await ye({root:e.changeDir,ref:r.source,maxBytes:Uo.maxFileBytes});if(i+=a.size,i>Uo.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:hg({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as ex,spawn as r1}from"node:child_process";import{promisify as tx}from"node:util";import{promises as zA}from"fs";import $r from"path";var Ko={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},gn=/^[a-f0-9]{64}$/u;function Yo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xo(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function ii(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function pg(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Tu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function DA(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||$r.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=$r.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function BA(e,t){return $r.join(W(e,t),"runtime","checkpoints","progress.json")}function Iu(e,t){return $r.join(W(e,t),"runtime","checkpoint-journal.json")}function mg(e,t,i){if(!gn.test(i))throw new Error("Native checkpoint manifest hash is invalid");return $r.join(W(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function qA(e){if(!gn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function vg(e,t,i){let n=await re({root:e,file:t,maxBytes:Ko.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function VA(e,t){let i=Yo(e,`checkpoint manifest artifact ${t}`);Xo(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=DA(ii(i.path,`checkpoint artifact ${t} path`,4096)),r=ot(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!gn.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:Tu(i.size,`checkpoint artifact ${t} size`)}}function Qo(e,t){let i=Yo(e,"Native checkpoint manifest");if(Xo(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Ko.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(VA),r=[...n].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(n)!==JSON.stringify(r))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(n.map(o=>o.path)).size!==n.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Tu(i.totalBytes,"checkpoint manifest totalBytes");if(n.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Ko.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:n,totalBytes:a}}function _u(e){return z(JSON.stringify(Qo(e,e.change)))}function gg(e,t){let i=Yo(e,"Native progress checkpoint");if(Xo(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=pg(i.previousRevision,"Native checkpoint previousRevision"),a=pg(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ii(i.manifestHash,"Native checkpoint manifestHash",64);if(!gn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=qA(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ii(i.inputHash,"Native checkpoint inputHash",64);if(!gn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ii(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Tu(i.artifactCount,"Native checkpoint artifactCount");if(u>Ko.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let f=ii(i.summary,"Native checkpoint summary"),d=ii(i.nextAction,"Native checkpoint nextAction");if(Ze(f)!==f||Ze(d)!==d)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ii(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:f,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function WA(e,t){let i=Yo(e,"Native checkpoint journal");if(Xo(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let n=ut(i.previousState),r=ut(i.nextState),a=gg(i.checkpoint,t),o=Qo(i.manifest,t),s=ii(i.inputHash,"Native checkpoint journal inputHash",64),c=z(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!gn.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==t||r.name!==t||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==_u(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:n,nextState:r,checkpoint:a,manifest:o}}async function wg(e,t,i){let n=mg(e,t,i);await $(e.nativeRoot,n);let r=await vg(e.nativeRoot,n,"Native checkpoint manifest"),a=Qo(r,t);if(Ou(e,a),_u(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function yg(e,t){let i=Iu(e,t);await $(e.nativeRoot,i);try{let n=WA(await vg(e.nativeRoot,i,"Native checkpoint journal"),t);return Ou(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ng(e,t,i,n){let r=Qo(i,t);Ou(e,r);let a=_u(r),o=mg(e,t,a);await $(e.nativeRoot,o);try{let s=await wg(e,t,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await Ne(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Ou(e,t){for(let i of t.artifacts){let n=Vh(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function bg(e,t){let i=gg(t,t.change),n=await wg(e,i.change,i.manifestHash),r=z(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=BA(e,t.change);await $(e.nativeRoot,a),await Ne(a,i,{containedRoot:e.nativeRoot})}async function kg(e,t,i){let n=await yg(e,t);if(!n)return null;if(await Ng(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await To(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await bg(e,n.checkpoint),await i?.afterProgressWritten?.(n),await zA.rm(Iu(e,t),{force:!0}),n}async function ju(e,t){await Su(e,t),await kg(e,t)}import{constants as $u,promises as We}from"node:fs";import Ai from"node:path";var JA=/^[a-f0-9]{64}$/u,GA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Hr=512*1024;function UA(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Zo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return me(i,n)?j(i,n):j(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function KA(e,t){let i=Ai.resolve(e),n=Ai.resolve(t);if(!U(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...Ai.relative(i,n).split(Ai.sep).filter(Boolean)]){o&&(a=Ai.join(a,o));let s=await We.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await We.realpath(a);if(r.length>0&&!U(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function Sg(e){for(let t of e){let i=await We.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!UA(t,i)||await We.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function YA(e){if(!JA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function XA(e){let t=GA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function QA(e,t,i){return Ai.join(W(e,t),...YA(i).split("/"))}async function ZA(e,t,i){let n=await KA(i,Ai.dirname(e)),r=await We.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>Hr)throw new Error(`Native check receipt exceeds ${Hr} bytes`);let[a,o]=await Promise.all([We.realpath(t),We.realpath(e)]);if(!U(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":$u.O_RDONLY|$u.O_NOFOLLOW|$u.O_NONBLOCK,c=await We.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,f]=await Promise.all([c.stat(),We.lstat(e),We.realpath(e)]);if(await Sg(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Zo(r,l)||!Zo(l,u))throw new Error("Native check receipt changed while opening");let d=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let y=Hr+1-p,b=await c.read(m,0,Math.min(m.length,y),null);if(b.bytesRead===0)break;if(p+=b.bytesRead,p>Hr)throw new Error(`Native check receipt exceeds ${Hr} bytes`);d.push(Buffer.from(m.subarray(0,b.bytesRead)))}let[h,v,w]=await Promise.all([c.stat(),We.lstat(e),We.realpath(e)]);if(await Sg(n),!v.isFile()||v.isSymbolicLink()||w!==o||!U(a,w)||!Zo(l,h)||!Zo(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(d,p).toString("utf8"))}finally{await c.close()}}async function Eg(e,t,i){let n=XA(i),r=W(e,t),a=QA(e,t,n);await $(e.nativeRoot,a);let o=Rv(await ZA(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var Fr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var y1=64*1024;var N1=3600*1e3;var b1=tx(ex);var k1=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_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("; ");var ix=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Cg(e,t){let i=[];for(let n of ix){let r=e.bindings[n],a=t[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function Rg(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Eg(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}var ni=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function nx(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 rx(e){let t=nx(e.bundle.baseline),i=await kl(e.paths,t,{origin:"explicit",now:e.now});return Yl({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function ax(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await qo(e.paths,e.state.name,e.state.implementation_scope),i=await xu({changeDir:W(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await rx({paths:e.paths,bundle:t,now:e.now}),r=[];return i.contract.contractHash!==t.scope.contractHash&&r.push("verification-contract-stale"),n!==t.scope.currentProjectionHash&&r.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:r}}async function ox(e){let t=await ye({root:W(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:sg(t.text)}}function sx(e){let{receipt:t,implementationScope:i}=e,n=[],r=i.scope.changes.filter(o=>o.after!==null),a=r.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!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==r.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==r.length||t.counts.bytesScanned!==a))&&n.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&n.push("verification-receipt-outcome-mismatch"),n}function cx(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:ru(e.implementationScope.scope.declaredArtifacts)}}async function Pg(e){let t=await su(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Cg(t,e.expectedBindings);if(i.push(...n.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new ni([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let r=await Rg({paths:e.paths,state:e.state,receipt:t});if(r){let a=sx({receipt:r,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 lx(e){let t=cx({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Pg({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof ni)return i.push(...a.details),null;throw a});if(r!==null&&r.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let n of e.trace.entries)if(n.status!=="missing")for(let r of n.evidenceRefs){let a=await Pg({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof ni)return i.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(n.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new ni(i)}function Hu(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function es(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Hu(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([ax(e),jv(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Hu(e.state.verification_result,"stale"),envelope:null};let n=await ox({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),r=[...t.findingCodes];(n.hash!==i.reportHash||n.ref!==i.reportRef)&&r.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&r.push("verification-state-mismatch");try{await lx({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{r.push("verification-receipt-invalid")}let a=[...new Set(r)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Hu(e.state.verification_result,"invalid"),envelope:null}}}function fx(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function xg(e){try{return await ux.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dx(e,t){try{return(await ye({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function hx(e,t,i){let n=Rr(e,i.capability);if(!U(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=Ag.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await dx(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ye({root:W(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function px(e,t){return xg(zo(e,t))}async function Lr(e){let t=e.now??new Date,i=await de(e.paths,e.name),n=await yt(e.paths,e.name),r=await Wt(e.paths.projectRoot),a=fx(i.name,t),o=Ag.resolve(e.paths.nativeRoot,...a.split("/"));if(!U(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,f,d,p]=await Promise.all([Promise.all(i.spec_changes.map(m=>hx(e.paths,i.name,m))),es({paths:e.paths,state:i,now:t}),Hv(e.paths,i.name),cn(e.paths,i.name),Ll(e.paths,i.name),px(e.paths,i.name),xg(o)]);return Wm({change:i.name,archiveConfirmation:r?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||f||d,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:n?.schema==="comet.native.workspace.v3"?{schema:n.schema,isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Fu}from"node:fs";import xt from"node:path";var mx="comet.native.archive-tree.v1",vx={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function _g(e){let t={...vx,...e};for(let[i,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function Tg(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function Ig(e,t,i,n){if(i.entryCount+=1,i.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>n.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${n.maxRefBytes} bytes: ${t.ref}`);let r=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=r+(e.length===0?0:1),i.manifestBytes+2>n.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${n.maxManifestBytes} bytes`);e.push(t)}async function Og(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await zt({root:e,directory:t,label:`Native Archive content directory ${xt.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=Tg(o.entries),c=[...o.entries];c.sort((u,f)=>u.name.localeCompare(f.name));for(let u of c){await o.verify();let f=xt.join(t,u.name),d=xt.relative(e,f).replaceAll("\\","/"),p=await Fu.lstat(f);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${d}`);if(u.isDirectory()&&p.isDirectory()){Ig(i,{ref:d,kind:"directory"},n,r),await Og(e,f,i,n,r,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${d}`);let m=await re({root:e,file:f,maxBytes:r.maxFileBytes,label:`Native Archive content file ${d}`});if(n.totalBytes+=m.size,n.totalBytes>r.maxTotalBytes)throw new Error(`Native Archive content exceeds ${r.maxTotalBytes} total file bytes`);Ig(i,{ref:d,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await zt({root:e,directory:t,label:`Native Archive content directory ${xt.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(Tg(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${xt.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function Lu(e,t={}){let i=_g(t);e=xt.resolve(e);let n=await Fu.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await Og(e,e,r,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(r);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return z(`${mx}\0${o}`)}async function ri(e,t={}){let i=_g(t);e=xt.resolve(e);let n;try{n=await Fu.lstat(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await re({root:xt.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${xt.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await Lu(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Ie}from"node:fs";import le from"node:path";var Du=16*1024*1024,gx=256*1024,wx=16*1024,Dr="comet.native.archive-cas.v1";function yx(e,t){let i=le.resolve(e.nativeRoot,...t.split("/"));if(le.relative(e.nativeRoot,i).split(le.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function Te(e,t){return $(e.nativeRoot,yx(e,t))}function Br(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function ts(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function Fe(e){let t=await ri(e.target);if(!Br(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ts(t)}`);return t}async function Lg(e,t){let i=ur(t),n=await Ye(e,i.id);await Ie.mkdir(n.staged,{recursive:!0}),await Ie.mkdir(n.backups,{recursive:!0}),await Ne(n.journal,i,{containedRoot:e.nativeRoot}),await Jt(e,i.id,"prepared")}async function Mg(e,t){let i=await Ye(e,t),n=await re({root:e.nativeRoot,file:i.journal,maxBytes:gx,label:`Native Archive transaction journal ${t}`}),r=ur(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function Dg(e,t,i){let n=ur({...t,status:i}),r=await Ye(e,n.id);return await Ne(r.journal,n,{containedRoot:e.nativeRoot}),n}function is(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function jg(e){return{...is(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function xi(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function Nx(e,t){return xi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function he(e){try{return await Ie.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ai(e){let t=await Ie.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=jg(t),n=await re({root:e.paths.nativeRoot,file:e.file,maxBytes:Du,label:e.label}),r=await Ie.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!Nx(i,jg(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:is(r),size:n.size}}function bx(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let r=e;if(Object.keys(r).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=r.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(r.schema!==Dr||r.operationId!==t.id||r.role!==i||r.hash!==n)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Dr,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Tt(e,t,i,n){let r=await Ye(e,t.id),a=le.join(r.backups,".cas"),o=`.${le.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:le.join(a,`${i.id}.original.json`),postRecord:le.join(a,`${i.id}.post.json`),candidate:le.join(a,`${i.id}.candidate`),originalQuarantine:le.join(le.dirname(n),`${o}.original`),rollbackQuarantine:le.join(le.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>$(e.nativeRoot,c))),s}async function ht(e){if(!await he(e.file))return null;let t=await re({root:e.paths.nativeRoot,file:e.file,maxBytes:wx,label:`Archive CAS ${e.operation.id} ${e.role} record`});return bx(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Mu(e){let t=await ht(e);if(t){if(!xi(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await vi({root:e.paths.nativeRoot,directory:le.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Dr,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await Ne(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await ht(e);if(!n||!xi(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function Ee(e){let t=await ai({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!xi(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function kx(e){let t=await ai({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Mu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Ee({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function Sx(e){if(!await he(e.quarantine)||await he(e.target))return;let t=await or({root:e.paths.nativeRoot,directory:le.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Ie.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([Ie.lstat(e.quarantine),Ie.lstat(e.target)]);if(!xi(is(i),is(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Ie.unlink(e.quarantine),await t.verify()}async function Ex(e){if(await he(e.quarantine)){await Ee({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await or({root:e.paths.nativeRoot,directory:le.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Ee({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Ee({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Ie.rename(e.target,e.quarantine),await t.verify(),await Ee({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await Sx(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Mr(e){if(!await he(e.file))return;await Ee(e);let t=await or({root:e.paths.nativeRoot,directory:le.dirname(e.file),label:e.label});await t.verify(),await Ee(e),await Ie.unlink(e.file),await t.verify()}async function $g(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await Te(e,t.target),r=await Te(e,t.backup),a=await ri(r);if(a!==null){if(!Br(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await Fe({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await gi({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:Du,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await Fe({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function Bg(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Tt(e.paths,e.journal,e.operation,e.target),n=await ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await he(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Ee({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await $g(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await he(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await kx({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Ee({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await $g(e.paths,e.operation,e.hooks),await Ex({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:i.originalQuarantine}}async function Hg(e){let t=await Tt(e.paths,e.journal,e.operation,e.target);return await he(t.candidate)?(await ai({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await vi({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await gi({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:Du,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function Cx(e){let t=e.operation.stagedHash,i=await Tt(e.paths,e.journal,e.operation,e.target),n=await ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await he(e.target))return await Ee({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await he(i.candidate)&&await Mr({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await he(e.target)){let c=await Hg(e),l=await ai({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await ai({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xi(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await Mu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Mr({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await Hg(e),a=await ai({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await vi({root:e.paths.nativeRoot,directory:le.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await or({root:e.paths.nativeRoot,directory:le.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Ee({paths:e.paths,file:r,operation:e.operation,record:{schema:Dr,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Ie.link(r,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await ai({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xi(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await Mu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Mr({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function Rx(e,t,i,n){let r=await Te(e,i.target),a=await Te(e,i.staged);if(await Fe({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Tt(e,t,i,r);(!await ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await he(r))&&await Bg({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await ri(r);if(o!==null&&!Br(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${ts(o)}`)}await Cx({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await Fe({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function Px(e,t,i,n){let r=await Te(e,i.target);await Bg({paths:e,journal:t,operation:i,target:r,hooks:n}),await Fe({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function Ax(e,t){let i=await Te(e,t.source),n=await Te(e,t.target),[r,a]=await Promise.all([ri(i),ri(n)]);if(!(r===null&&Br(a,t.expectedSourceHash,"directory"))){if(!Br(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ts(r)}, target=${ts(a)}`);await Ie.mkdir(le.dirname(n),{recursive:!0}),await Ie.rename(i,n),await Fe({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function xx(e,t,i,n){return i.type==="write"?Rx(e,t,i,n):i.type==="remove"?Px(e,t,i,n):Ax(e,i)}function Tx(e){let t=0,i=!1,n=[];for(let r of e.events){if(r.type!=="operation-started"&&r.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||r.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(r.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(a.id),t+=1,i=!1}return n}async function Ix(e,t,i,n){let r=await Te(e,i.target);if(i.type==="write"){let a=await Te(e,i.staged);await Fe({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Tt(e,t,i,r),s=await ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Ee({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await Fe({target:await Te(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await ht({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await he(o.originalQuarantine))await Ee({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await Fe({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await Fe({target:await Te(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Tt(e,t,i,r),o=await ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await he(a.originalQuarantine))await Ee({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}n||(await Fe({target:await Te(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await Fe({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function qg(e,t,i){let n=t.status==="prepared"?await Dg(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await Xi(e,n.id),a=Tx({journal:n,events:r}),o=new Set(a),s=r.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,a.length))await Ix(e,n,l,s);let c=o.size;for(let l of n.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Jt(e,n.id,"operation-started",l.id),await xx(e,n,l,i),await Jt(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await Mg(e,n.id),n}async function _x(e){if(e.operation.type!=="write")return;let t=await Tt(e.paths,e.journal,e.operation,e.target);if(!await he(t.candidate))return;let i=await ai({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Mr({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Dr,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function Fg(e,t,i){let n=await Te(e,i.target);if(i.type==="write"){let r=await Tt(e,t,i,n),a=await ht({paths:e,file:r.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Ee({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await Fe({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function Ox(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await Te(e,i.target),r=await Tt(e,t,i,n);if(await he(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await Fg(e,t,i),i.expectedTargetHash!==null){let a=await ht({paths:e,file:r.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await he(r.originalQuarantine)&&await Mr({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await _x({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await Fg(e,t,i)}async function ns(e,t,i){return i==="commit"&&await Ox(e,t),await Jt(e,t.id,i),i==="commit"?Dg(e,t,"committed"):t}import{promises as jx}from"fs";import $x from"path";var Bu="comet.selection.v2",Hx=16*1024;function qu(e){return $x.join(e,".comet","current-change.json")}function Fx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Vg(e){return e===null||typeof e=="string"}function Lx(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!Fx(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&&!Vg(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Bu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Bu)throw new Error(`current change selection schema must be ${Bu}`);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(!Vg(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 Wg(e){let t;try{let n=qu(e),{bytes:r}=await pi(n,Hx,{label:"current change selection"});t=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...Lx(t)}}async function zg(e){await jx.rm(qu(e),{force:!0})}async function Jg(e,t,i){let n=await Wg(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await zg(e),!0)}var bF=16*1024;async function Gg(e,t){return await Vi(e.projectRoot),Jg(e.projectRoot,"native",t)}var qx=16*1024*1024,qr=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},yn=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};async function Vx(e){try{return await hl(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function Wx(e){if(e.phase!=="archive")throw new Error(`Native change ${e.name} is not in Archive`);if(e.verification_result!=="pass")throw new Error(`Native change ${e.name} has not passed verification`);if(!e.verification_report)throw new Error(`Native change ${e.name} has no verification report`);if(e.archived)throw new Error(`Native change ${e.name} is already archived`)}async function zx(e,t){let i=W(e,t.name),n=await Mm(i,t.brief),r=await Dm(i,t.verification_report),a=[...n.findings,...r.findings];if(a.length>0)throw new Error(`Native archive artifacts are invalid: ${a[0].message}`)}async function Jx(e,t){let i=Rr(e,t.capability);await $(e.nativeRoot,i);let n=await Vx(i),r=t.operation==="create"?null:t.base_hash;if(n!==r)throw new qr(t.capability,r,n,i)}function Gx(e,t,i){return wn.join(e.archiveDir,`${i.toISOString().slice(0,10)}-${t}`)}async function Ux(e){try{return await Dx.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Kx(e){let{paths:t,state:i,now:n,transactionId:r,preflight:a}=e,o=Gx(t,i.name,n);if(await Ux(o))throw new Error(`Native archive target already exists: ${o}`);if(wt(t,o)!==a.targetRef)throw new Error("Native Archive target changed after preflight");let s=await Ye(t,r),c=[];for(let[u,f]of i.spec_changes.entries()){await Jx(t,f);let d=Rr(t,f.capability),p=a.operations.find(N=>N.capability===f.capability&&N.operation===f.operation);if(!p)throw new Error(`Native Archive preflight has no operation for ${f.capability}`);if(f.operation!=="remove"&&p.proposedHash===null)throw new Error(`Native Archive preflight has no proposed hash for ${f.capability}`);let m=wn.join(s.backups,"specs",f.capability,"spec.md");if(f.operation==="remove"){c.push({id:`spec-${u+1}-${f.capability}`,type:"remove",target:wt(t,d),backup:wt(t,m),expectedTargetHash:f.base_hash});continue}let h=W(t,i.name);await Bm(h,f.source);let v=wn.resolve(h,...f.source.split(/[\\/]/u)),w=wn.join(s.staged,"specs",f.capability,"spec.md"),b=(await gi({sourceRoot:h,source:v,targetRoot:t.nativeRoot,target:w,maxBytes:qx,label:`Native Archive proposed spec ${f.capability}`,expectedHash:p.proposedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("stage",f.source)}})).hash;if(b!==p.proposedHash)throw new Error(`Proposed Native spec changed after preflight: ${f.capability}`);c.push({id:`spec-${u+1}-${f.capability}`,type:"write",target:wt(t,d),staged:wt(t,w),...f.operation==="replace"?{backup:wt(t,m)}:{},expectedTargetHash:f.operation==="create"?null:f.base_hash,stagedHash:b})}let l=W(t,i.name);return c.push({id:"archive-change",type:"move",source:wt(t,l),target:wt(t,o),expectedSourceHash:await Lu(l),expectedTargetHash:null}),{schema:"comet.native.transaction.v2",id:r,kind:"archive",status:"prepared",change:i.name,createdAt:n.toISOString(),preflightHash:a.preflightHash,operations:c}}function Vu(e,t){let i=t.operations.find(n=>n.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return wn.resolve(e.nativeRoot,...i.target.split("/"))}async function Ug(e,t,i){let n=await Xi(e,t.id);if(n.some(h=>h.type==="archive-finalized"))return;let r=n.some(h=>h.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!r){let h=t.operations.find(w=>w.id==="archive-change");if(!h||h.type!=="move"||!h.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await ri(Vu(e,t));if(v?.kind!=="directory"||v.hash!==h.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Vu(e,t),o=wn.join(a,bt),s=await jm(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await an(a);if(!c||c.runId!==s.run_id||c.currentStep!=="archive"&&!(c.currentStep===null&&c.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let l=c;if(c.currentStep==="archive"){let h=Qu(ti,c,new Set,hu,void 0);if(!h.action)throw new Error(h.reason??"Native archive produced no action");l=Zu(ti,h.state,{actionId:h.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},hu,void 0)}let u=z(`archive:${t.id}:${s.name}`),f=await wi(a,l.trajectoryRef),d=f.filter(h=>h.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(d.length>1||d.some(h=>h.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let p=d.find(h=>h.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:u,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(p&&t.schema==="comet.native.transaction.v2"&&(!Bx(p.data,m)||p.runId!==l.runId||p.timestamp!==t.createdAt||p!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!r&&(s.archived||c.currentStep===null||d.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(r||(t.schema==="comet.native.transaction.v2"?(await ns(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await po(e,t,"archive-finalization-started")),!s.archived){let h={...s,archived:!0};await Om(o,h)}p||(p=await _r({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await Vo({changeDir:a,run:l,trajectoryOffset:p.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await So(a,l),await Gg(e,s.name),t.schema==="comet.native.transaction.v2"?await ns(e,t,"archive-finalized"):await po(e,t,"archive-finalized")}async function Yx(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Xi(e,t.id)).some(o=>o.type==="operation-started")){let o=await Lr({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new yn(o,"Native Archive facts changed before the first transaction operation")}let a=await qg(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await de(e,t.change),c=await es({paths:e,state:s,now:new Date(t.createdAt)});if(s.phase!=="archive"||s.archived||s.verification_result!=="pass"||!["complete","partial"].includes(c.freshness)||c.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${c.findingCodes.join(", ")||c.freshness}`)}});return await Ug(e,a,i),ns(e,a,"commit")}let n=await jp(e,t);return await Ug(e,n,i),po(e,n,"commit")}async function Kg(e){return st(e.paths,`archive ${e.name}`,()=>Jo(e.paths,e.name,`archive ${e.name}`,async()=>{await ju(e.paths,e.name);let t=await Wi(e.paths,"archive",`archive ${e.name}`);try{if(!/^[a-f0-9]{64}$/u.test(e.expectedPreflightHash))throw new Error("Native Archive expected preflight must be a SHA-256 hash");let i=e.now??new Date,n=await Lr({paths:e.paths,name:e.name,now:i});if(!n.ready||n.preflightHash!==e.expectedPreflightHash)throw new yn(n);let r=await de(e.paths,e.name);Wx(r),await zx(e.paths,r);let a=Mx(),o=await Kx({paths:e.paths,state:r,now:i,transactionId:a,preflight:n,hooks:e.hooks});return await Lg(e.paths,o),await e.hooks?.afterPrepared?.(o),await Yx(e.paths,o,e.hooks),{archiveDir:Vu(e.paths,o),transactionId:a,preflightHash:n.preflightHash}}finally{await zi(t)}}))}var Xx=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function Qx(e){return e.phase==="shape"?["summary","shared-understanding-confirmation"]:e.phase==="build"?e.approval==="confirmed"?["summary","artifact-or-no-code-reason"]:["summary","artifact-or-no-code-reason","shared-understanding-confirmation"]:e.phase==="verify"?["summary","verification-result","verification-report"]:[]}function Wu(e){let i=(e.findings??[]).filter(u=>!gm(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||Xx.test(u.code)),a=i.find(u=>u.code==="repair-iteration-limit"||u.code==="repair-override-exhausted"),o=i.find(u=>u.code==="repair-stagnation-stop"),s=i.find(u=>u.requiredAction==="return-to-bound-working-directory"||u.requiredAction==="repair-workspace-binding"),c=[...new Set(i.map(u=>u.requiredAction))].sort();if(e.done)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"done",action:"none",command:null,requiresUserDecision:!1,requiredInputs:[]};if(a)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"]};if(n)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:c};if(o)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:null,requiresUserDecision:!1,requiredInputs:["new-repair-hypothesis"]};if(s)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:c};if(r)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:r.repairCommand,requiresUserDecision:!1,requiredInputs:c};if(e.evidenceRetreat)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"`,requiresUserDecision:!1,requiredInputs:["summary"]};if(e.state.phase==="build"&&e.state.verification_result==="fail")return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:["repair-verification-gaps"]};if(i.length>0)return e.state.phase==="archive"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:c}:c.includes("refresh-verification-receipts")?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:`comet native receipt refresh ${e.state.name} --apply`,requiresUserDecision:!1,requiredInputs:c}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:c};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");return e.archiveConfirmation==="required"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"archive",command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"]}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"archive",command:`comet native archive ${e.state.name} --expect-preflight ${e.archivePreflightHash}`,requiresUserDecision:!1,requiredInputs:[]}}return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",command:e.archiveReady?`comet native archive ${e.state.name} --dry-run`:null,requiresUserDecision:!1,requiredInputs:e.archiveReady?[]:["archive-readiness"]}}let l=e.state.phase==="shape"||e.state.phase==="build"&&e.state.approval!=="confirmed"?" --confirmed":"";return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"${l}`,requiresUserDecision:!1,requiredInputs:Qx(e.state)}}import Zx from"path";var aL=10*1024*1024,se=class extends Error{};function Vr(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new se(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Wr(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new se(`${t} may only be provided once`);if(i.length===0)return;let n=i[0],r=e[n+1];if(r===void 0||r.startsWith("--"))throw new se(`${t} requires a value`);return e.splice(n,2),r}function Yg(e){if(e.length>0)throw new se(`Unexpected argument: ${e[0]}`)}function Xg(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new se(`${t} is required`);return i}async function Qg(e){return e?Zx.resolve(e):ro(process.cwd())}async function Zg(e){let t=await np({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function zu(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
178
- `}}function ew(e,t){if(t instanceof se)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof qr)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 yn)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof br)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 Po)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 Ao)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 ni)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Fr)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function tw(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
179
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function iw(e,t){let i=Xg(e,"change name"),n=Vr(e,"--dry-run"),r=Wr(e,"--expect-preflight"),a=Vr(e,"--confirmed"),s=Wr(e,"--finish");if(s!==void 0&&s!=="merge"&&s!=="push"&&s!=="pull-request"&&s!=="keep")throw new se("--finish must be merge, push, pull-request, or keep");if(n&&r)throw new se("--dry-run and --expect-preflight cannot be combined");if(n&&a)throw new se("--confirmed is only valid with --expect-preflight");if(!n&&s)throw new se("--finish is only valid with --dry-run");if(!n&&!r)throw new se("archive requires --dry-run or --expect-preflight <sha256>");if(r&&!/^[a-f0-9]{64}$/u.test(r))throw new se("--expect-preflight must be a SHA-256 hash");Yg(e);let{config:c,paths:l}=await Zg(t);if(n){let p=await yt(l,i),m=p;if(p?.schema==="comet.native.workspace.v3"){if(p.isolation==="current"){if(s)throw new se("Native current isolation does not accept --finish")}else if(s)m=await Sm(l,i,s);else if(p.finish===null)throw new se("Native branch and worktree isolation require --finish with --dry-run")}else if(s)throw new se("--finish requires a workspace v3 branch or worktree binding");let h=await Lr({paths:l,name:i}),v=await de(l,i);return zu("archive --dry-run",{...h,workspaceFinish:m?.schema==="comet.native.workspace.v3"?m.finish:null,continuation:Wu({state:v,archiveReady:h.ready,archiveConfirmation:h.archiveConfirmation,archivePreflightHash:h.preflightHash})},`Native Archive preview ${h.preflightHash}: ${h.ready?"ready":"blocked"}
180
- `)}if(c.native.archive_confirmation==="required"&&!a)throw new se("archive requires --confirmed when native.archive_confirmation is required");let u=await de(l,i),f=await yt(l,i);if(f?.schema==="comet.native.workspace.v3"&&f.isolation!=="current"&&f.finish===null)throw new se("Native branch and worktree isolation require a persisted --finish preview");let d=await Kg({paths:l,name:i,expectedPreflightHash:r});return zu("archive",{...d,workspaceFinish:f?.schema==="comet.native.workspace.v3"?f.finish:null,continuation:Wu({state:u,done:!0})},`Archived Native change ${i} to ${d.archiveDir}
181
- `)}function eT(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
182
- `}}async function nw(e,t,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{Vr(r,"--json"),s=Wr(r,"--project-root");let u=[...r,...a],f=await Qg(s);c=await t(u,f)}catch(u){c=ew(e,u)}let l=o?eT(c):tw(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
147
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=ls(l,t);else if(i)wd(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let f=ls(l,null);if(f!==null)t=f;else{let u=l.trimStart();if(u.startsWith("<!--")&&!wd(u))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function Vi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function ds(e,t,i,r=[],n="content-hash"){let a=Vi(i),o=t.replaceAll("\\","/").trim(),s=r.map(Vi);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-${ce(Nw,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function fs(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function bw(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Mi(e)){n=s+1;let c=o?us(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function hs(e,t="brief.md",i=qi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=bw(e);if(n===null)return[];let a=null;for(let{line:l,body:d,index:f}of Mi(e)){if(f<n.start||f>=n.end)continue;let u=d?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let p=u[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:d,index:f}of Mi(e)){if(f<n.start||f>=n.end)continue;let u=d?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),fs(o.map(l=>ds("brief-example",t,l.join(`
148
+ `),[],r)),"Brief",r)}function ps(e,t="spec.md",i=qi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(ds("spec-scenario",t,[o.title,...o.body].join(`
149
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of Mi(e)){let d=l?us(c):null,f=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=d.level;)a.pop();let u=Vi(f[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:d.level,title:u,body:[],context:a.map(p=>p.text)}}else if(d){for(o!==null&&d.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=d.level;)a.pop();a.push(d)}else o!==null&&l&&o.body.push(c)}return s(),fs(n,"Specification",r)}function ms(e,t="spec.md",i=qi.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(ds("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(d=>/^(?:non-?goals?|非目标)$/iu.test(d.text.trim()));for(let{line:d,body:f}of Mi(e)){let u=f?us(d):null;if(u){for(c(),o!==null&&u.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u),/^Scenario\s*:/iu.test(u.text)&&(o=u.level);continue}let p=d.trim();if(!f||o!==null||l()){c();continue}if(p.length===0||ls(d,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 v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(d);if(v){c(),s={parts:[v[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(),fs(n,"Specification mandatory requirements",r)}var kw=/^A[1-9]\d*$/u;function Nd(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||yd.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||yd.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Sw(e,t){return e.localeCompare(t,"en")}function Cn(e){let t=Nd(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>Sw(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=hs(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Nd(a.source,`Native spec source for ${a.capability}`);r.push(...ps(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...ms(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Vi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function bd(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!kw.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function kd(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Tn=fr(ji(),1);import{promises as Ew}from"node:fs";var Lt="comet.native.v4",Wi="comet.native.local-execution.v4";function vs(){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 Pw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Rw=/^A[1-9][0-9]*$/u,Cw=new Set(["schema","name","language","phase","status","state_version","brief","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),_n=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Z(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ee(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function z(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function ws(e,t){return e===null?null:z(e,t)}function Ft(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function _(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Aw(e,t){return e===null?null:_(e,t,Number.MIN_SAFE_INTEGER)}function V(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ce(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function In(e,t){return Ce(e,t,(i,r)=>z(i,`${t}[${r}]`))}function pt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Mt(e,t){let i=z(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function ys(e,t,i=!1){let r=z(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function we(e,t){let i=Z(e,t);return ee(i,new Set(["text","truncated"]),t),{text:z(i.text,`${t}.text`,{empty:!0}),truncated:Ft(i.truncated,`${t}.truncated`)}}function _w(e,t){let i=`Native spec_changes[${t}]`,r=Z(e,i);ee(r,new Set(["capability","operation","source"]),i);let n=z(r.capability,`${i}.capability`);if(!xw.test(n))throw new Error(`${i}.capability is invalid`);let a=V(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:ys(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Tw(e){let t="Native workspace",i=Z(e,t);ee(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=V(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=ws(i.change_branch,`${t}.change_branch`),a=ws(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:V(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function Iw(e){let t="Native loop",i=Z(e,t);ee(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=In(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return pt(r,`${t}.previous_unresolved_ids`),{stage:V(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:_(i.goal_cycle,`${t}.goal_cycle`,1),iteration:_(i.iteration,`${t}.iteration`),attempt:_(i.attempt,`${t}.attempt`),retry_epoch:_(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:_(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:_(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:_(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:ws(i.next_action,`${t}.next_action`)}}function jw(e,t){let i=`Native acceptance[${t}]`,r=Z(e,i);ee(r,new Set(["id","source","text","result","reason"]),i);let n=z(r.id,`${i}.id`);if(!Rw.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:ys(r.source,`${i}.source`),text:z(r.text,`${i}.text`),result:V(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:we(r.reason,`${i}.reason`)}}function $w(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Z(e,i);return ee(r,new Set(["name","result","note"]),i),{name:we(r.name,`${i}.name`),result:V(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:we(r.note,`${i}.note`)}}function Ow(e){let t="Native builder_handoff",i=Z(e,t);ee(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=In(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return pt(r,`${t}.addressed_acceptance_ids`),{candidate_id:z(i.candidate_id,`${t}.candidate_id`),identity_provider:z(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:z(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),summary:we(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:Ce(i.checks,`${t}.checks`,$w),checks_truncated:Ft(i.checks_truncated,`${t}.checks_truncated`),known_limits:Ce(i.known_limits,`${t}.known_limits`,(n,a)=>we(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Ft(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Mt(i.submitted_at,`${t}.submitted_at`)}}function Hw(e,t){let i=`Native blockers[${t}]`,r=Z(e,i);ee(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=In(r.acceptance_ids,`${i}.acceptance_ids`);return pt(n,`${i}.acceptance_ids`),{owner:V(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:we(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:V(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function Dw(e,t){let i=`Native verification.checks[${t}]`,r=Z(e,i);return ee(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:z(r.id,`${i}.id`),name:we(r.name,`${i}.name`),argv_display:Ce(r.argv_display,`${i}.argv_display`,(n,a)=>we(n,`${i}.argv_display[${a}]`)),argv_truncated:Ft(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:ys(r.cwd_ref,`${i}.cwd_ref`,!0),status:V(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:Aw(r.exit_code,`${i}.exit_code`),duration_ms:_(r.duration_ms,`${i}.duration_ms`)}}function Bw(e){let t="Native verification",i=Z(e,t);ee(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=Ce(i.checks,`${t}.checks`,Dw);pt(r.map(a=>a.id),`${t}.checks IDs`);let n=z(i.identity_provider,`${t}.identity_provider`);return{candidate_id:z(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:z(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:_(i.iteration,`${t}.iteration`,1),attempt:_(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":V(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:V(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:we(i.summary,`${t}.summary`),risks:Ce(i.risks,`${t}.risks`,(a,o)=>we(a,`${t}.risks[${o}]`)),risks_truncated:Ft(i.risks_truncated,`${t}.risks_truncated`),completed_at:Mt(i.completed_at,`${t}.completed_at`)}}function Sd(e,t){let i=`Native history[${t}]`,r=Z(e,i);ee(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=In(r.unresolved_ids,`${i}.unresolved_ids`);return pt(n,`${i}.unresolved_ids`),{goal_cycle:_(r.goal_cycle,`${i}.goal_cycle`,1),iteration:_(r.iteration,`${i}.iteration`),attempt:_(r.attempt,`${i}.attempt`),outcome:V(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:we(r.summary,`${i}.summary`),completed_at:Mt(r.completed_at,`${i}.completed_at`)}}function Lw(e){let t="Native history_overflow.outcome_counts",i=Z(e,t),r=["pass","fail","blocked","execution-error","recovery"];return ee(i,new Set(r),t),{pass:_(i.pass,`${t}.pass`),fail:_(i.fail,`${t}.fail`),blocked:_(i.blocked,`${t}.blocked`),"execution-error":_(i["execution-error"],`${t}.execution-error`),recovery:_(i.recovery,`${t}.recovery`)}}function Fw(e){let t="Native history_overflow",i=Z(e,t);ee(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=_(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Mt(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Mt(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Lw(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Mw(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(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.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 r=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(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Vw(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 i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);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(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.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 le(e){let t=Z(e,"Native portable state");if(ee(t,Cw,"Native portable state"),t.schema!==Lt)throw new Error(`Native portable state schema must be ${Lt}`);let i=z(t.name,"Native state name");if(!Pw.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=Ce(t.spec_changes,"Native spec_changes",_w);pt(r.map(s=>s.capability),"Native spec change capabilities");let n=Ce(t.acceptance,"Native acceptance",jw);pt(n.map(s=>s.id),"Native acceptance IDs");let a=Ce(t.history,"Native history",Sd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Lt,name:i,language:V(t.language,["en","zh-CN"],"Native state language"),phase:V(t.phase,["shape","build","verify","archive"],"Native state phase"),status:V(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:_(t.state_version,"Native state_version",1),brief:"brief.md",spec_changes:r,workspace:Tw(t.workspace),loop:Iw(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ow(t.builder_handoff),blockers:Ce(t.blockers,"Native blockers",Hw),verification:t.verification===null?null:Bw(t.verification),history:a,history_overflow:Fw(t.history_overflow),verification_result:V(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:V(t.verification_report,["verification.md"],"Native verification_report"),archived:Ft(t.archived,"Native archived"),created_at:Mt(t.created_at,"Native created_at")};return Mw(o),Vw(o),o}function Vt(e,t){let i=le(e),r=Sd(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return le({...i,history:n,history_overflow:a})}function qw(e,t){let i=(0,Tn.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function ue(e){let t=await Ew.readFile(e,"utf8");return le(qw(t,"Native portable state"))}async function jn(e,t,i={}){let r=le(t);await K(e,(0,Tn.stringify)(r),i)}var An=new Map;async function Ww(e,t){let i=An.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);An.set(e,a),await i;try{return await t()}finally{r(),An.get(e)===a&&An.delete(e)}}async function mt(e){return Ww(e.file,async()=>{let t=_(e.expectedStateVersion,"Native expected state version",1),i=le(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await ue(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new _n(t,r.state_version);return await jn(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ue(e.file);if(n.state_version!==t)throw new _n(t,n.state_version)}}),i})}function zw(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function et(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(zw(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Oe="comet.native.v3",Ae="comet.native.v2",_e="comet.native.v1";var $n="comet.native.portable-migration.v1",Gw=new Set(["schema","id","change","fromSchema","status","createdAt"]),Uw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Kw=/^[a-z0-9][a-z0-9-]{7,127}$/u,Yw=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Xw=new Set([_e,Ae,Oe]);function Qw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zw(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function ey(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function ty(e){return e.schema===_e?zi(e):e.schema===Ae?Ji(e):Gi(e)}function iy(e){return Jw.posix.normalize(e.replaceAll("\\","/"))}function ry(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:iy(t.source)})}function ny(e){return e==="shape"?"shape":"build"}function ay(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function oy(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Ed(e){let t=ty(e.state);bd(e.acceptance);let i=ny(t.phase),r=i==="shape"?0:1,n=Zw(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return le({schema:Lt,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:ry(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:ay(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:et(oy(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:vs(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ns(e){let t=Qw(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!Gw.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==$n)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Kw.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Uw.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Xw.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Yw.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:$n,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:ey(t.createdAt,"Native portable migration transaction createdAt")}}function Pd(e){switch(Ns(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var On="comet.native.archive-transaction.v4",xd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",sy=new RegExp(`^portable-archive-(${xd})\\.json$`,"u"),cy=new RegExp(`^portable-migration-(${xd})\\.json$`,"u"),ly=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uy=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dy=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),fy=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),hy=new Set(["capability","operation","source","content"]),Rd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Cd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ad(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function py(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Cd(e,i);if(Ad(r,hy,i),typeof r.capability!="string"||!Rd.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function my(e){let t=Cd(e,"Native portable Archive transaction");if(Ad(t,fy,"Native portable Archive transaction"),t.schema!==On)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!ly.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Rd.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"||!uy.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"||!dy.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 i=t.spec_changes.map(py);if(new Set(i.map(({capability:n})=>n)).size!==i.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)>i.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 r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:On,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:i,created_at:t.created_at}}function Hn(e){let t=sy.exec(e);if(t)return{kind:"archive",change:t[1]};let i=cy.exec(e);return i?{kind:"migration",change:i[1]}:null}function vt(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Hn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return bs.join(e.transactionsDir,i)}async function ks(e,t){let i=Hn(t);if(!i)return null;let r=await B({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=bs.join(e.transactionsDir,t);if(i.kind==="archive"){let s=my(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Ns(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function qt(e,t){let i=vt(e,t);try{return await ks(e,bs.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}function _d(e){return e.kind==="archive"||e.journal.status!=="committed"}import He from"path";import{TextDecoder as Sy}from"util";import{createHash as vy}from"node:crypto";import{constants as Dn,promises as ye}from"node:fs";import Ne from"node:path";function Ln(e,t){let i=Ne.relative(e,t);return i===""||!Ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ne.sep}`)}function gy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function wy(e,t){return A({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Bn(e,t){return A({...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 Ss(e,t){let i=await ye.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ye.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ny(e,t,i){let r=Ne.resolve(e),n=Ne.resolve(t);if(!Ln(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Ss(r,i)],o=r;for(let s of Ne.relative(r,n).split(Ne.sep).filter(Boolean)){await gt(a,i),o=Ne.join(o,s);let c=await Ss(o,i);if(!Ln(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await gt(a,i),a}async function gt(e,t){for(let i of e){let r=await ye.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!wy(i,r)||await ye.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function by(e,t,i){let r=[],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(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Wt(e){let t=gy(e.maxBytes),i=Ne.resolve(e.file),r=await Ny(e.root,Ne.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(d=>Ss(Ne.resolve(d),e.label)));await e.hooks?.afterParentChainCaptured?.(),await gt(r,e.label);let a=await ye.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=yy(a),s=await ye.realpath(i);if(!Ln(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(d=>Ln(d.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Dn.O_RDONLY:Dn.O_RDONLY|Dn.O_NOFOLLOW|Dn.O_NONBLOCK,l=await ye.open(i,c);try{let d=await l.stat();await e.hooks?.afterOpen?.();let[f,u]=await Promise.all([ye.lstat(i),ye.realpath(i)]);if(await gt(r,e.label),await gt(n,e.label),!d.isFile()||!f.isFile()||f.isSymbolicLink()||u!==s||!Bn(o,d)||!Bn(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await by(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),ye.lstat(i),ye.realpath(i)]);if(await gt(r,e.label),await gt(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Bn(o,v)||!Bn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:vy("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Ey=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Py=new Set(["id","type","source","target","staged","backup"]),xy=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Ry=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var jd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Cy=256*1024,SP=1024*1024,EP=16*1024;var PP=64*1024*1024;var Ay=new Sy("utf-8",{fatal:!0});function Mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vn(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function $d(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Es(e,t){if(typeof e!="string"||e.length===0||He.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Fn(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Td(e,t){if(Es(e,t),e.includes("\\")||e!==He.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 _y(e,t){let i=Mn(e,`transaction operations[${t}]`);if(Vn(i,Py,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Es(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Es(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Od(e){let t=Mn(e,"Native Archive transaction journal");if(Vn(t,xy,"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"||!jd.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(!$d(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Fn(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 i=t.operations.map((s,c)=>{let l=Mn(s,`Archive transaction operations[${c}]`);if(Vn(l,Ry,`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`);Td(l.target,`Archive transaction operation ${l.id} target`);for(let d of["source","staged","backup"])l[d]!==void 0&&Td(l[d],`Archive transaction operation ${l.id} ${d}`);if(l.expectedTargetHash!==null&&Fn(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(Fn(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`);Fn(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.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)||i.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 i.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:i}}function Ty(e){let t=Mn(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Od(t);if(Vn(t,Ey,"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"||!jd.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!He.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!He.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(!$d(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 i=t.operations.map(_y),r=i.map(n=>n.id);if(new Set(r).size!==r.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:i}}function Iy(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return He.join(e.transactionsDir,t)}function Hd(e,t){let i=Iy(e,t);return{directory:i,journal:He.join(i,"transaction.json"),events:He.join(i,"events.jsonl"),staged:He.join(i,"staged"),backups:He.join(i,"backups")}}async function xs(e,t){let i=Hd(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}async function Rs(e,t,i={}){let r=await xs(e,t),n=await Wt({root:e.runtimeDir,file:r.journal,maxBytes:Cy,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Ay.decode(n.bytes)),o=Ty(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Oy(e,t,i){let r;try{r=await jy.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Rs(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Hn(n.name))try{let a=await ks(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(_d(a))return!0}catch{return!0}return!1}async function Hy(e,t){let i=Date.now()+5e3,r=$y.join(e.locksDir,"root-move.lock");for(;;)try{return await xn(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await gd(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function J(e,t,i,r){let n=await Hy(e,t);try{if(await Fi(e.projectRoot),await Oy(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Rn(n)}}import{createHash as Dy}from"crypto";function de(e){return Dy("sha256").update(e).digest("hex")}var JP={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var GP=8*1024*1024;var UP=64*1024,KP=64*1024;var YP={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},XP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var QP=(1n<<256n)-1n;var Wy=fr(ji(),1);var px=4*1024*1024;var cR=256*1024;var bR={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import zt from"node:path";var Ui=/^[a-f0-9]{64}$/u,Bd=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Gy=16*1024,DR=process.platform;function Uy(e,t){let i=zt.relative(e,t);return zt.isAbsolute(i)||i===".."||i.startsWith(`..${zt.sep}`)?null:i.replaceAll("\\","/")||"."}function Ld(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Fd(e,t){if(e.length===0||Ld(e)||e.includes("\\")||zt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=zt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Ky(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 Cs(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ld(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Yy(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Cs(e.changeBranch,"Native workspace change branch"),Cs(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 Xy(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Bd.test(t.baseCommit)||typeof t.targetCommit!="string"||!Bd.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Cs(t.targetBranch,"Native workspace Git target branch")}function Qy(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.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"||!Ui.test(String(t.projectRootId))||!Ui.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Ky(t.capturedAt),Fd(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&&!Ui.test(String(t.projectRootPathId))||a&&!Ui.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ui.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Xy(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(Yy(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 Zy(e,t){return zt.join(Pe(e,t),"workspace.json")}function eN(e,t){let i=Zy(e,t),r=xe(e,i),n=Uy(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Fd(n,"Native workspace file ref")}}async function tN(e,t){try{let i=eN(e,t),r=await B({root:i.root,ref:i.ref,maxBytes:Gy});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ki(e,t){let i=await tN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Qy(i),i)}var Vd=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],nN=new Set(Vd),qd=new Set([...Vd,"minimum_runtime_version","revision"]),aN=new Set([...qd,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),oN=new Set(["capability","operation","source","base_hash"]),sN=new Set(["shape","build","verify","archive"]),cN=new Set(["implicit","confirmed"]),lN=new Set(["pending","pass","fail"]),wt="comet-state.yaml",_s=/^[a-f0-9]{64}$/u,Wd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uN=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ts=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Gt=class extends Error{constructor(i,r){super(i!==Oe||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},qn=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Yi=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Wn=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;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"},sC=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
150
+ `);function Qi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function zd(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function js(e){if(!Wd.test(e))throw new Error(`Invalid Native change name: ${e}`)}function dN(e){if(!Wd.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Jd(e,t){if(e.length===0||Jt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function fN(e,t){let i=Qi(e,`spec_changes[${t}]`);if(zd(i,oN,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(dN(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&Jd(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!_s.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!_s.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function hN(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 $s(e,t){if(zd(e,t,wt),typeof e.name!="string")throw new Error("Native change name is required");if(js(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"||!sN.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&&!cN.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 i=e.spec_changes.map(fN),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!lN.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"&&Jd(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!hN(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:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function zi(e){let t=Qi(e,wt);if(t.schema!==_e)throw new Error(`Expected ${_e}`);return{schema:_e,...$s(t,nN)}}function Xi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function As(e,t,i){if(e===null)return null;let r=typeof e=="string"?uN.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function pN(e){if(e==null)return null;if(typeof e!="string"||!_s.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function mN(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Ji(e){let t=Qi(e,wt);if(t.schema!==Ae)throw new Error(`Expected ${Ae}`);if(Xi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ae} minimum_runtime_version must be 2`);return{schema:Ae,minimum_runtime_version:2,revision:Xi(t.revision,"Native v2 revision"),...$s(t,qd)}}function Gi(e){let t=Qi(e,wt);if(t.schema!==Oe){if(t.schema===_e||t.schema===Ae){let o=t.schema===_e?zi(t):Ji(t);throw new Ts(o.name,o.schema)}throw new Gt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Gt(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Xi(t.revision,"Native revision"),n=$s(t,aN),a=pN(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Oe,minimum_runtime_version:3,revision:r,verification_protocol:mN(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:As(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:As(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:As(t.partial_allowance,"Native partial_allowance","allowances")}}function vN(e){let t=Qi(e,wt);if(t.schema===_e){let n=zi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema===Ae){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Oe}`}}if(t.schema!==Oe){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Gt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Gt(t.schema,i).message};let r=Gi(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function re(e,t){js(t);let i=Jt.join(e.changesDir,t);if(!D(e.changesDir,i))throw new Error("Native change path escaped");return i}var gN=256*1024;async function wN(e,t=Jt.dirname(e)){let i=Jt.relative(t,e).split(Jt.sep).join("/"),r=await B({root:t,ref:i,maxBytes:gN}),n=(0,Is.parseDocument)(r.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 zn(e,t){let i=Jt.join(re(e,t),wt);await T(e.nativeRoot,i);let r=vN(await wN(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}import{promises as rr}from"node:fs";import Be from"node:path";var lC=["$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("; ");var Jn="skill-coordinated";function kN(e){return e.state_version+1}function SN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function EN(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:et(e.summary),completed_at:e.completedAt}}function Os(e){let t=le(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Vt(t,EN({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return le({...r,phase:"build",status:"active",state_version:kN(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:SN(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Ud}from"node:fs";import er from"node:path";function Gn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Un(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Te(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Gd(e,t){return e===null?null:Te(e,t)}function Yn(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function PN(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 xN(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Kn(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Hs(e,t){if(e===null)return null;let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Ds(e,t){let i=Te(e,t);if(!er.isAbsolute(i))throw new Error(`${t} must be absolute`);return er.resolve(i)}function RN(e,t){let i=`Native local checks[${t}]`,r=Gn(e,i);if(Un(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,d)=>Te(l,`${i}.argv[${d}]`,!0)),a=Kn(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Hs(r.startedAt,`${i}.startedAt`),s=Hs(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Yn(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Te(r.id,`${i}.id`),name:Te(r.name,`${i}.name`),operationId:Te(r.operationId,`${i}.operationId`),status:a,repeatable:xN(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Yn(r.executionCount,`${i}.executionCount`),argv:n,cwd:Ds(r.cwd,`${i}.cwd`),exitCode:PN(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Te(r.log,`${i}.log`)}}function Bs(e){let t="Native local execution state",i=Gn(e,t);if(Un(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Wi)throw new Error(`Native local execution schema must be ${Wi}`);let r=Gn(i.workspace,"Native local workspace");Un(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Gn(i.execution,"Native local execution");Un(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Hs(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Te(o.operationId,"Native local execution.operationId"),stage:Kn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Kn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Gd(o.executionId,"Native local execution.executionId"),status:Kn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Yn(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(RN);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:Wi,change:Te(i.change,"Native local change"),basedOnStateVersion:Yn(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ds(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ds(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Gd(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function yt(e){return Bs({schema:Wi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:er.resolve(e.projectRoot),worktreeRoot:er.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ls(e){let t;try{t=await Ud.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Bs(i)}async function it(e,t,i={}){let r=Bs(t);await Ud.mkdir(er.dirname(e),{recursive:!0}),await Y(e,r,i)}import{promises as CN}from"node:fs";function rt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
151
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function De(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function AN(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function _N(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===Jn?Jn:"host-attested")}function TN(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${De(o.id)} | ${De(o.result)} | ${De(o.source)} | ${De(o.text)} | ${De(rt(o.reason))} |`).join(`
152
+ `),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(rt).join(" ");return`| ${De(rt(o.name))} | ${De(s||"—")} | ${De(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
153
+ `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${rt(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
154
+ `),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${rt(o)}`).join(`
155
+ `),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${De(rt(o.summary))} | ${o.completed_at} |`)].join(`
156
+ `);return`---
157
+ generated_from_state_version: ${e.state_version}
158
+ ---
159
+
160
+ # Verification
161
+
162
+ ## Current result
163
+
164
+ - Result: **${AN(e)}**
165
+ - Assurance: **${_N(e)}**
166
+ - Goal cycle: ${e.loop.goal_cycle}
167
+ - Iteration: ${e.verification.iteration}
168
+ - Verifier attempt: ${e.verification.attempt}
169
+ - Completed: ${e.verification.completed_at}
170
+ - Summary: ${rt(e.verification.summary)}
171
+
172
+ ## Acceptance
173
+
174
+ | ID | Result | Source | Criterion | Reason |
175
+ | --- | --- | --- | --- | --- |
176
+ ${t}
177
+
178
+ ## Checks
179
+
180
+ ${i}
181
+
182
+ ## Blockers
183
+
184
+ ${r}
185
+
186
+ ## Risks and skipped work
187
+
188
+ ${n}
189
+
190
+ ## Previous iterations
191
+
192
+ ${a}
193
+
194
+ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summary: ${e.history_overflow.dropped_entries}.
195
+
196
+ `:""}## Conclusion
197
+
198
+ ${rt(e.verification.summary)}
199
+ `}function IN(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function tr(e){let t;try{t=await CN.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=IN(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function ir(e){await K(e.file,TN(e.state))}var Kd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jN="comet-state.yaml",$N="state.json";function be(e,t){if(!Kd.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Be.join(e.changesDir,t);if(!D(e.changesDir,i))throw new Error("Native change path escaped");return i}function ne(e,t){return Be.join(be(e,t),jN)}function Ut(e,t){return Be.join(Ee(e,t),$N)}async function nr(e,t){try{let i=await rr.readFile(ne(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function ON(e){return F(e).currentBranch}async function Le(e,t){return ue(ne(e,t))}async function Yd(e){let t=await mt({file:ne(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Be.join(be(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await rr.rm(i,{force:!0})}return t}async function HN(e){let t=be(e.paths,e.state.name),i=Be.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await rr.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Kd.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Be.join(t,...s.split("/")),l=await rr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let d=Be.join(e.paths.specsDir,o.name,"spec.md"),f="create";try{let u=await rr.lstat(d);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:f,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function DN(e){let t=be(e.paths,e.state.name),i=await B({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await B({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Cn({briefMarkdown:i.text,specs:r})}async function Fs(e){let t=await HN(e);if(!(t.length===e.state.spec_changes.length&&t.every((a,o)=>{let s=e.state.spec_changes[o];return s!==void 0&&a.capability===s.capability&&a.source===s.source&&(a.operation===s.operation||e.ignoreSpecOperationFor?.has(a.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let r=await DN({...e,specChanges:t}),n=e.state.acceptance.map(({source:a,text:o})=>({source:a,text:o}));return kd(n,r)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native confirmed acceptance criteria changed"}}async function Xd(e){return J(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Le(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let i={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},r=await Yd({paths:e.paths,previous:t,next:i});return r.verification!==null&&await ir({file:Be.join(be(e.paths,t.name),"verification.md"),state:r}),r})}async function Qd(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Vt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:et(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}},n=await Yd({paths:e.paths,previous:t,next:r});return await it(Ut(e.paths,t.name),yt({portableState:n,projectRoot:e.paths.projectRoot,branch:ON(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Xn(e){if(e.state.verification===null)return"not-applicable";let t=Be.join(be(e.paths,e.state.name),"verification.md");return await tr({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await ir({file:t,state:e.state}),"rebuilt")}import{promises as BN}from"fs";import LN from"path";var Ms="comet.selection.v2",FN=16*1024;function Qn(e){return LN.join(e,".comet","current-change.json")}function MN(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Zd(e){return e===null||typeof e=="string"}function VN(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!MN(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&&!Zd(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ms,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ms)throw new Error(`current change selection schema must be ${Ms}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Zd(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 ef(e){let t;try{let r=Qn(e),{bytes:n}=await ft(r,FN,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...VN(t)}}async function tf(e){await BN.rm(Qn(e),{force:!0})}async function rf(e,t,i){let r=await ef(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await tf(e),!0)}var IA=16*1024;function Vs(e){return Qn(e.projectRoot)}async function Zn(e,t){return await Fi(e.projectRoot),rf(e.projectRoot,"native",t)}var ar=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function qs(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Ws(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=U.join(e.archiveDir,t);if(!D(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ea(e){try{return await q.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function nf(e,t){let i=U.normalize(U.resolve(e)),r=U.normalize(U.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function af(e,t){let i;try{i=await q.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=U.join(e.archiveDir,n.name);try{let o=await ue(U.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function zs(e,t){let i=await qt(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function of(e,t){return await zs(e,t)!==null||await af(e,t)!==null}async function Nt(e,t){await q.mkdir(e.transactionsDir,{recursive:!0}),await Y(vt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function sf(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=St(e.paths.projectRoot);i.some(a=>nf(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Re(a);if(!o)continue;let s=await Bt(a,o.native.artifact_root);r.some(c=>nf(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await q.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await ue(U.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await zn(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function WN(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function zN(e){let t=U.join(e.paths.specsDir,e.change.capability),i=U.join(t,"spec.md");if(!D(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await q.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await q.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([q.realpath(e.paths.specsDir),q.realpath(t)]);if(!D(o,s))throw new Error("Native canonical capability path escaped");try{let c=await q.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await q.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await q.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=U.join(be(e.paths,e.state.name),e.change.source);await K(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await q.mkdir(t,{recursive:!0}),await K(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function Js(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function JN(e,t){let i=be(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await B({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function GN(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(Js(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Gs(e){let t=await Le(e.paths,e.name),i=[];try{Js(t)}catch(o){i.push(o.message)}if(await zs(e.paths,e.name)===null)try{let o=await Fs({paths:e.paths,state:t});o.drifted&&i.push(o.reason??"Native confirmed requirements changed")}catch(o){i.push(o.message)}let n=t.verification===null?"missing":await tr({file:U.join(be(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&i.push(`verification.md is ${n}`);let a=await sf({paths:e.paths,state:t});return a.length>0&&i.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:i.length===0,blockers:i,capabilityPeers:a,archiveDir:Ws(e.paths,qs(t)),stateVersion:t.state_version}}async function cf(e){return J(e.paths,`archive portable change ${e.name}`,async()=>{let t=WN(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await zs(e.paths,e.name),r=be(e.paths,e.name),n=await ea(r),a=n?null:await af(e.paths,e.name),o;if(n)o=await Le(e.paths,e.name);else if(i)o=await ue(U.join(Ws(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await Fs({paths:e.paths,state:o});if(l.drifted){let d=l.reason??"Native confirmed requirements changed";throw await Qd({paths:e.paths,state:o,reason:d}),new Error(`${d}; Native change returned to Shape and requires confirmation`)}}let s=Ws(e.paths,i?.archive_ref??qs(o)),c=await ea(s);if(i&&GN(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Zn(e.paths,o.name),await q.rm(Ee(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)Js(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await sf({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new ar(l);i={schema:On,id:qN(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:qs(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await JN(e.paths,o),created_at:new Date().toISOString()},await Nt(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await Nt(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await zN({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await Nt(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await Nt(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await mt({file:ne(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Nt(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await ea(r)?r:s;if(await ir({file:U.join(l,"verification.md"),state:o}),await tr({file:U.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Nt(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await q.mkdir(e.paths.archiveDir,{recursive:!0}),await ea(s))throw new Error(`Native Archive target already exists: ${s}`);await q.rename(r,s),i={...i,status:"moved"},await Nt(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await Zn(e.paths,o.name),await q.rm(Ee(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await q.rm(vt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function or(e){let t={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},i=r=>({kind:r,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...t,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:i("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...t,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...t,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...t,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...t,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:{...t,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:i("none")};if(e.status==="blocked"){let r=e.blockers.some(({resolution_action:n})=>n==="retry-verifier");return{...t,disposition:"blocked",action:r?"retry-verifier":"none",commandArgs:r?["comet","native","next",e.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:r?["summary"]:["repair-runtime"],inputOptions:r?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:i(r?"retry-verifier":"none")}}if(e.phase==="shape")return{...t,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")};if(e.phase==="build")return{...t,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}],known_limits:[]}}],runnerAction:i("builder-handoff")};if(e.phase==="verify"){let r=e.loop.next_action==="await-verifier-result";return{...t,disposition:"continue",action:r?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[r?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:r?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|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:"<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:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:i(r?"await-verifier":"dispatch-verifier")}}return{...t,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:i("none")}}import{randomUUID as UN}from"node:crypto";import{promises as sr}from"node:fs";import KN from"node:path";var YN=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function XN(e,t){let i=await qt(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function lf(e,t){await sr.mkdir(e.transactionsDir,{recursive:!0}),await Y(vt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function uf(e,t){await Promise.all([sr.rm(Ee(e,t),{recursive:!0,force:!0}),sr.rm(rs(e,t),{recursive:!0,force:!0}),...YN.map(i=>sr.rm(KN.join(re(e,t),i),{force:!0}))])}async function df(e,t){await it(Ut(e,t.name),yt({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ff(e,t){try{let i=await Ki(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function hf(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=F(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function QN(e){let t=re(e.paths,e.state.name),i=await B({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await B({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Cn({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function pf(e,t){let i=await zn(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function mf(e){return J(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await XN(e.paths,e.name),i=await nr(e.paths,e.name)?await ue(ne(e.paths,e.name)):null;if(!t&&i)return await uf(e.paths,e.name),await df(e.paths,i),i;let r=null,n=null;for(t||(r=await pf(e.paths,e.name),n=await ff(e.paths,e.name),hf(e.paths,n),t={schema:$n,id:UN(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await lf(e.paths,t));;){let a=Pd(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await pf(e.paths,e.name),n??=await ff(e.paths,e.name),hf(e.paths,n),i=Ed({state:r,acceptance:await QN({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await jn(ne(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await uf(e.paths,e.name):a.action==="commit-transaction"&&(i??=await ue(ne(e.paths,e.name)),await df(e.paths,i)),t={...t,status:a.nextStatus},await lf(e.paths,t)}return await sr.rm(vt(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??ue(ne(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as vf}from"node:fs";import gf from"node:path";function ZN(e,t){let i=F(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function eb(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function tb(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Vt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:et(t),completed_at:i});return le({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:eb(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function ib(e){try{let t=await Ls(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function wf(e){return J(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Le(e.paths,e.name);if(t.status==="done")return await Xn({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=ZN(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Ut(e.paths,e.name),n=await ib(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await it(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Xn({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=Os({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await mt({file:ne(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await vf.rm(gf.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=yt({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await it(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=c||l;if(d){let u=tb(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await mt({file:ne(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let f=yt({portableState:t,projectRoot:e.paths.projectRoot,branch:F(e.paths.projectRoot).currentBranch});return await vf.mkdir(gf.dirname(Ut(e.paths,t.name)),{recursive:!0}),await it(r,f,{containedRoot:e.paths.runtimeDir}),await Xn({paths:e.paths,state:t}),{state:t,local:f,action:d?"reverify":"resume-stable-boundary",reason:a,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as fb}from"node:fs";import Yt from"node:path";import{execFileSync as rb}from"node:child_process";var nb=6e4,ab=8*1024*1024,Us=class extends Error{constructor(i,r,n,a){super(`${i} ${r.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=i;this.args=r;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr};function Ks(e,t,i={}){let r=i.timeoutMs??nb,n=i.maxBufferBytes??ab;if(!Number.isSafeInteger(r)||r<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");try{return rb(e,[...t],{...i.cwd?{cwd:i.cwd}:{},encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:r,maxBuffer:n,windowsHide:!0,shell:!1})}catch(a){let o=typeof a.stderr=="string"?a.stderr.trim():Buffer.isBuffer(a.stderr)?a.stderr.toString("utf8").trim():"";throw new Us(e,t,o,{cause:a})}}import{execFileSync as ob}from"node:child_process";var sb=3e4,cb=8*1024*1024,Ys=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function yf(e,t){try{return ob("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:sb,maxBuffer:cb,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Ys(e,t,r)}}function L(e,t){return yf(e,t).trim()}function ta(e){return L(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Xs(e){let t=yf(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let i=t.split("\0").filter(Boolean),r=[];for(let n=0;n<i.length;n+=1){let a=i[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(r.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=i[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");r.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(r)].sort()}function Nf(e,t){try{let r=L(e,["config","--get",`branch.${t}.remote`]);if(r&&r!==".")return r}catch{}let i=L(e,["remote"]).split(/\r?\n/u).map(r=>r.trim()).filter(Boolean);if(i.includes("origin"))return"origin";if(i.length===1)return i[0];throw new Error(i.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${i.join(", ")}`)}import ub from"path";var db=["Outcome","Scope","Non-goals","Acceptance examples"],j_=[...db,"Constraints and invariants","Decisions","Open questions","Verification expectations"];function ia(e,t){return ub.join(e.specsDir,t,"spec.md")}var cr=class extends Error{constructor(i){super(i.message??"Native workspace finish is blocked");this.result=i;this.name="NativeWorkspaceFinishError"}result};function hb(e,t){let i=Yt.relative(e,t);return i===""||!Yt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Yt.sep}`)}function bt(e,t){let i=Yt.relative(e,t).replaceAll("\\","/");if(!i||i===".."||i.startsWith("../")||Yt.isAbsolute(i))throw new Error(`Native workspace finish path escaped the project: ${t}`);return i}function bf(e,t){return t.some(i=>e===i||e.startsWith(`${i}/`))}function pb(e){try{if(L(e,["config","--get","user.name"])&&L(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function mb(e,t){for(let i of St(e))if(F(i).currentBranch===t)return i;return null}function vb(e,t){try{Ks(e,t,{timeoutMs:1e4})}catch(i){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:i})}}async function Qs(e){let{paths:t,state:i}=e,r=i.workspace;if(r.isolation==="current")return null;if(!r.finish||!r.change_branch||!r.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(r.change_branch===r.target_branch)throw new Error("Native change and target branches must be different for workspace finish");let n=F(t.projectRoot);if(!n.primaryWorktreeRoot||n.currentBranch!==r.change_branch)throw new Error(`Native workspace finish requires branch ${r.change_branch} in the current registered worktree`);pb(t.projectRoot);let a=[bt(t.projectRoot,Vs(t))];e.archiveDir&&a.push(bt(t.projectRoot,re(t,i.name)),bt(t.projectRoot,e.archiveDir));let o=Xs(t.projectRoot).filter(l=>!bf(l,a));if(o.length>0)throw new Error(`Native workspace finish is blocked until change-owned implementation and artifacts are committed; remaining paths: ${o.slice(0,20).join(", ")}${o.length>20?", ...":""}`);let s=r.isolation==="branch"?t.projectRoot:mb(n.primaryWorktreeRoot,r.target_branch);if(r.finish==="merge"&&r.isolation==="worktree"){if(!s)throw new Error(`Native merge finish requires a registered worktree on target branch ${r.target_branch}`);if(!ta(s))throw new Error(`Native merge target worktree is not clean: ${s}`)}let c=r.finish==="push"||r.finish==="pull-request"?Nf(t.projectRoot,r.change_branch):null;return r.finish==="pull-request"&&vb("gh",["--version"]),{finish:r.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:r.change_branch,targetBranch:r.target_branch,targetRoot:s,remote:c,isolation:r.isolation}}function gb(e,t){try{return Ks("gh",t,{cwd:e,timeoutMs:6e4}).trim()}catch(i){throw new Error(`gh ${t.join(" ")} failed: ${i.message}`,{cause:i})}}async function wb(e){try{return await fb.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function yb(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},message:null,recoveryArgs:null}}async function kf(e){let t=yb(e.plan),i=null;try{let r=[bt(e.paths.projectRoot,re(e.paths,e.name)),bt(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(c=>bt(e.paths.projectRoot,ia(e.paths,c.capability))),bt(e.paths.projectRoot,Vs(e.paths))],n=Xs(e.plan.changeRoot).filter(c=>!bf(c,r));if(n.length>0)throw new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.slice(0,20).join(", ")}${n.length>20?", ...":""}`);let a=[];for(let c of r){let l=Yt.resolve(e.paths.projectRoot,...c.split("/")),d=L(e.plan.changeRoot,["ls-files","--",c])!=="";(await wb(l)||d)&&a.push(c)}if(a.length>0&&L(e.plan.changeRoot,["add","-A","--",...a]),L(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&L(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=L(e.plan.changeRoot,["rev-parse","HEAD"]),!ta(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){if(L(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequestUrl=gb(e.plan.changeRoot,["pr","create","--base",e.plan.targetBranch,"--head",e.plan.changeBranch,"--fill"]).split(/\r?\n/u).find(l=>/^https?:\/\//u.test(l.trim()))??null,!t.pullRequestUrl))throw new Error("GitHub CLI did not return a pull request URL");let c=hb(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!c?(L(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let s=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(L(s,["switch",e.plan.targetBranch]),i=s),L(s,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=s,t.cleanup={performed:!1,reason:"post-merge-validation-required-before-cleanup"},t}catch(r){if(i!==null){let n;try{L(i,["merge","--abort"])}catch{}try{F(i).currentBranch===e.plan.targetBranch&&L(i,["switch",e.plan.changeBranch]),n=F(i).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=i)}throw t.status="blocked",t.message=r.message,t.recoveryArgs=e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new cr(t)}}import tc from"path";var Nb=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});var Sf=1024*1024;var Pf="scoped-text-safety",bb=1,kb=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Sb="comet.native.checker-policy.v1";var pT=ce(Sb,{policy:Pf,version:bb,limits:kb,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Eb=["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"],mT=new Set(Eb);var Rb=Sf,IT=3*Rb;var xf={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:[]},Ab=de("comet-native-runtime:v3:scope-reopen"),aI=[{skillVersion:"3",skillHash:de("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:de("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:de("comet-native-runtime:v1")}];var Cf=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],LI=new Set(Cf),Hb=new Set([...Cf,"minimum_runtime_version","revision"]),FI=new Set([...Hb,"operation"]),MI=512*1024,Db=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),VI=new Set([...Db,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var JI={maxAcceptanceCriteria:qi.maxCriteria};var XI={maxSpecs:64,maxFileBytes:pr,maxTotalBytes:4*1024*1024};import{execFile as Jb}from"node:child_process";import{promisify as Gb}from"node:util";var sj={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var Cj=512*1024;var lr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Xj=64*1024;var Qj=3600*1e3;var Zj=Gb(Jb);var ra=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};var B$={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var U$=16*1024*1024,K$=256*1024,Y$=16*1024;var tO=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var WO=16*1024*1024,na=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},aa=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var oa=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Tf=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],ec=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",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 remove Record a complete capability removal intent.","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:Tf,output:"Human-readable text by default; use --json for a structured command envelope.",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] [--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.","--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, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","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 remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],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."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries or inspect the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction.",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> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
200
+ comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, 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 Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," 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."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. 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','comet native next session-timeout --summary "Implementation changed" --return-to-build','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]
201
+ 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 Inspect readiness without rerunning verification.","--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 plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Zs(e,t){return`${e}:
202
+ ${t.map(i=>` ${i}`).join(`
203
+ `)}`}function Qb(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return ec[i]||t.length>1&&ec[t[0]]?.subcommands?i:t[0]}function Zb(e=[]){let t=Qb(e),i=ec[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Zs("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Tf];return n&&n.length>0&&r.push("",Zs("Options",n)),r.push("",`Output:
204
+ ${i.output}`),i.examples&&r.push("",Zs("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
205
+ `)}
206
+ `}}var ek=Zb().usage;var c0=10*1024*1024,j=class extends Error{};function ur(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new j(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Xt(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new j(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new j(`${t} requires a value`);return e.splice(r,2),n}function ic(e){if(e.length>0)throw new j(`Unexpected argument: ${e[0]}`)}function jf(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new j(`${t} is required`);return i}function If(e,t){let i=tc.normalize(e),r=tc.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function tk(e){let t=tc.resolve(e),i=F(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=F(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!If(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||If(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function $f(e){return e?tk(e):Sn(process.cwd())}async function Of(e){let t=await ad({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Qt(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
207
+ `}}function Hf(e,t){if(t instanceof j)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof na)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 aa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof qn)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 Yi)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 oa)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Wn)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 ra)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof lr)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Df(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
208
+ `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Bf(e,t){let i=jf(e,"change name"),r=ur(e,"--dry-run"),n=Xt(e,"--expect-preflight"),a=ur(e,"--confirmed"),o=Xt(e,"--finish"),s=Xt(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new j("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new j("--finish must be merge, push, pull-request, or keep");let l=await Of(t),d=await nr(l.paths,i),f=d?await qt(l.paths,{kind:"archive",change:i}):null,u=d?!1:await of(l.paths,i);if(d||u){if(n)throw new j("Portable Native Archive does not use preflight hashes");if(r&&a)throw new j("--confirmed is only valid when executing Archive");if(r&&s)throw new j("--serial-first is only valid when executing Archive");if(!r&&c)throw new j("--finish is only valid with --dry-run");ic(e);let v=d&&!r&&f?.kind!=="archive"?await wf({paths:l.paths,name:i}):null,h=v?.state??(d?await Le(l.paths,i):null);if(v?.action==="reverify"||v?.action==="await-user")return Qt(r?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:or(v.state)},`${v.message}
209
+ `);if(r){if(!h)return Qt("archive --dry-run",{change:i,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",i,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${i}
210
+ `);if(c)h=await Xd({paths:l.paths,name:i,finish:c});else if(h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new j("Native branch and worktree isolation require --finish with --dry-run");let w=await Gs({paths:l.paths,name:i}),k=or(h),S=w.capabilityPeers.length>0?{...k,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],runnerAction:{...k.runnerAction,kind:"none"}}:k;return Qt("archive --dry-run",{...w,workspaceFinish:h.workspace.finish,continuation:S},`Native Archive preview: ${w.ready?"ready":"blocked"}
211
+ `)}if(l.config.native.archive_confirmation==="required"&&!a)throw new j("archive requires --confirmed when native.archive_confirmation is required");if(h&&h.workspace.isolation!=="current"&&h.workspace.finish===null)throw new j("Native branch and worktree isolation require a persisted --finish preview");let m=h?await Qs({paths:l.paths,state:h}):null,g;try{g=await cf({paths:l.paths,name:i,...s?{serialFirstChange:s}:{}})}catch(w){if(!(w instanceof ar)||!h)throw w;let k=await Gs({paths:l.paths,name:i}),S=w.peers.length>0?["comet","native","archive",i,"--confirmed","--serial-first",i]:["comet","native","archive",i,"--confirmed"];return{command:"archive",exitCode:73,data:{...k,workspaceFinish:h.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:w.message,commandArgs:S,inputOptions:w.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}h=g.state,!m&&h.workspace.isolation!=="current"&&(m=await Qs({paths:l.paths,state:h,archiveDir:g.archiveDir}));let N=null;if(m)try{N=await kf({paths:l.paths,state:g.state,name:i,archiveDir:g.archiveDir,transactionId:g.transactionId,plan:m})}catch(w){if(!(w instanceof cr))throw w;return{command:"archive",exitCode:73,data:{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:w.result,continuation:{disposition:"blocked",reason:w.message,commandArgs:w.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:w.message}}}return Qt("archive",{...g,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:N,continuation:or(g.state)},`Archived Native change ${i} to ${g.archiveDir}
212
+ `)}if(s)throw new j("--serial-first is only valid for portable Native changes");if(!r&&c)throw new j("--finish is only valid with --dry-run");if(ic(e),r)return{command:"archive --dry-run",exitCode:65,data:{change:i,migrationRequired:!0,repairCommand:`comet native doctor ${i} --repair`},error:{code:"invalid-data",message:`Native active change ${i} must migrate before Archive preview`}};let p=await mf({paths:l.paths,name:i});return Qt("archive",{migration:{from:"legacy",to:p.schema,completed:!0},state:p,continuation:or(p)},`Migrated Native change ${i}; follow the returned portable continuation before Archive
213
+ `)}function ik(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
214
+ `}}async function Lf(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{ur(n,"--json"),s=Xt(n,"--project-root");let d=[...n,...a],f=await $f(s);c=await t(d,f)}catch(d){c=Hf(e,d)}let l=o?ik(c):Df(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
183
215
  `)?"":`
184
- `)),l.exitCode}process.exitCode=await nw("archive",iw);
216
+ `)),l.exitCode}process.exitCode=await Lf("archive",Bf);