@rpamis/comet 0.4.0-beta.15 → 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 (587) hide show
  1. package/README.md +37 -33
  2. package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.html +8 -0
  3. package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.json +286 -0
  4. package/assets/manifest.json +25 -17
  5. package/assets/skills/comet/SKILL.md +1 -1
  6. package/assets/skills/comet/agents/openai.yaml +3 -0
  7. package/assets/skills/comet/rules/comet-phase-guard.en.md +1 -1
  8. package/assets/skills/comet/rules/comet-phase-guard.md +1 -1
  9. package/assets/skills/comet/rules/comet-workflow-guard.en.md +2 -2
  10. package/assets/skills/comet/rules/comet-workflow-guard.md +2 -2
  11. package/assets/skills/comet/scripts/comet-archive.mjs +75 -75
  12. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +47 -47
  13. package/assets/skills/comet/scripts/comet-guard.mjs +119 -119
  14. package/assets/skills/comet/scripts/comet-handoff.mjs +80 -80
  15. package/assets/skills/comet/scripts/comet-hook-guard.mjs +78 -78
  16. package/assets/skills/comet/scripts/comet-hook-router.mjs +142 -140
  17. package/assets/skills/comet/scripts/comet-resume-probe.mjs +89 -89
  18. package/assets/skills/comet/scripts/comet-runtime.mjs +148 -148
  19. package/assets/skills/comet/scripts/comet-state.mjs +72 -72
  20. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +94 -94
  21. package/assets/skills/comet-any/SKILL.md +2 -1
  22. package/assets/skills/comet-any/agents/openai.yaml +5 -0
  23. package/assets/skills/comet-archive/SKILL.md +7 -6
  24. package/assets/skills/comet-archive/agents/openai.yaml +5 -0
  25. package/assets/skills/comet-build/SKILL.md +14 -13
  26. package/assets/skills/comet-build/agents/openai.yaml +5 -0
  27. package/assets/skills/comet-classic/SKILL.md +14 -14
  28. package/assets/skills/comet-classic/agents/openai.yaml +3 -0
  29. package/assets/skills/{comet → comet-classic}/reference/auto-transition.md +1 -1
  30. package/assets/skills/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
  31. package/assets/skills/{comet → comet-classic}/reference/context-recovery.md +5 -5
  32. package/assets/skills/{comet → comet-classic}/reference/debug-gate.md +2 -2
  33. package/assets/skills/{comet → comet-classic}/reference/decision-point.md +1 -1
  34. package/assets/skills/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
  35. package/assets/skills/{comet → comet-classic}/reference/file-structure.md +1 -1
  36. package/assets/skills/{comet → comet-classic}/reference/intent-frame.md +1 -1
  37. package/assets/skills/{comet → comet-classic}/reference/scripts.md +1 -1
  38. package/assets/skills/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  39. package/assets/skills/comet-design/SKILL.md +7 -6
  40. package/assets/skills/comet-design/agents/openai.yaml +5 -0
  41. package/assets/skills/comet-hotfix/SKILL.md +10 -9
  42. package/assets/skills/comet-hotfix/agents/openai.yaml +5 -0
  43. package/assets/skills/comet-native/SKILL.md +54 -168
  44. package/assets/skills/comet-native/agents/openai.yaml +3 -0
  45. package/assets/skills/comet-native/reference/artifacts.md +23 -89
  46. package/assets/skills/comet-native/reference/clarification.md +54 -29
  47. package/assets/skills/comet-native/reference/commands.md +30 -173
  48. package/assets/skills/comet-native/reference/recovery.md +38 -88
  49. package/assets/skills/comet-native/reference/workspace.md +23 -0
  50. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +184 -152
  51. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +219 -163
  52. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +125 -116
  53. package/assets/skills/comet-native/scripts/comet-native-init.mjs +134 -124
  54. package/assets/skills/comet-native/scripts/comet-native-new.mjs +170 -163
  55. package/assets/skills/comet-native/scripts/comet-native-next.mjs +179 -148
  56. package/assets/skills/comet-native/scripts/comet-native-root.mjs +152 -147
  57. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +247 -202
  58. package/assets/skills/comet-native/scripts/comet-native-select.mjs +153 -146
  59. package/assets/skills/comet-native/scripts/comet-native-show.mjs +117 -110
  60. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +133 -151
  61. package/assets/skills/comet-native/scripts/comet-native-status.mjs +146 -139
  62. package/assets/skills/comet-open/SKILL.md +7 -6
  63. package/assets/skills/comet-open/agents/openai.yaml +5 -0
  64. package/assets/skills/comet-tweak/SKILL.md +11 -10
  65. package/assets/skills/comet-tweak/agents/openai.yaml +5 -0
  66. package/assets/skills/comet-verify/SKILL.md +9 -8
  67. package/assets/skills/comet-verify/agents/openai.yaml +5 -0
  68. package/assets/skills-zh/comet/SKILL.md +1 -1
  69. package/assets/skills-zh/comet/agents/openai.yaml +3 -0
  70. package/assets/skills-zh/comet-any/SKILL.md +2 -1
  71. package/assets/skills-zh/comet-any/agents/openai.yaml +5 -0
  72. package/assets/skills-zh/comet-archive/SKILL.md +7 -6
  73. package/assets/skills-zh/comet-archive/agents/openai.yaml +5 -0
  74. package/assets/skills-zh/comet-build/SKILL.md +14 -13
  75. package/assets/skills-zh/comet-build/agents/openai.yaml +5 -0
  76. package/assets/skills-zh/comet-classic/SKILL.md +15 -15
  77. package/assets/skills-zh/comet-classic/agents/openai.yaml +3 -0
  78. package/assets/skills-zh/{comet → comet-classic}/reference/auto-transition.md +1 -1
  79. package/assets/skills-zh/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
  80. package/assets/skills-zh/{comet → comet-classic}/reference/context-recovery.md +5 -5
  81. package/assets/skills-zh/{comet → comet-classic}/reference/debug-gate.md +2 -2
  82. package/assets/skills-zh/{comet → comet-classic}/reference/decision-point.md +1 -1
  83. package/assets/skills-zh/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
  84. package/assets/skills-zh/{comet → comet-classic}/reference/file-structure.md +1 -1
  85. package/assets/skills-zh/{comet → comet-classic}/reference/intent-frame.md +1 -1
  86. package/assets/skills-zh/{comet → comet-classic}/reference/scripts.md +1 -1
  87. package/assets/skills-zh/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  88. package/assets/skills-zh/comet-design/SKILL.md +7 -6
  89. package/assets/skills-zh/comet-design/agents/openai.yaml +5 -0
  90. package/assets/skills-zh/comet-hotfix/SKILL.md +10 -9
  91. package/assets/skills-zh/comet-hotfix/agents/openai.yaml +5 -0
  92. package/assets/skills-zh/comet-native/SKILL.md +54 -168
  93. package/assets/skills-zh/comet-native/agents/openai.yaml +3 -0
  94. package/assets/skills-zh/comet-native/reference/artifacts.md +23 -89
  95. package/assets/skills-zh/comet-native/reference/clarification.md +40 -15
  96. package/assets/skills-zh/comet-native/reference/commands.md +30 -173
  97. package/assets/skills-zh/comet-native/reference/recovery.md +36 -86
  98. package/assets/skills-zh/comet-native/reference/workspace.md +23 -0
  99. package/assets/skills-zh/comet-open/SKILL.md +7 -6
  100. package/assets/skills-zh/comet-open/agents/openai.yaml +5 -0
  101. package/assets/skills-zh/comet-tweak/SKILL.md +11 -10
  102. package/assets/skills-zh/comet-tweak/agents/openai.yaml +5 -0
  103. package/assets/skills-zh/comet-verify/SKILL.md +9 -8
  104. package/assets/skills-zh/comet-verify/agents/openai.yaml +5 -0
  105. package/bin/fast-runtime-router.js +0 -4
  106. package/dist/app/commands/doctor.d.ts.map +1 -1
  107. package/dist/app/commands/doctor.js +16 -2
  108. package/dist/app/commands/doctor.js.map +1 -1
  109. package/dist/app/commands/init.d.ts.map +1 -1
  110. package/dist/app/commands/init.js +9 -1
  111. package/dist/app/commands/init.js.map +1 -1
  112. package/dist/app/commands/update.d.ts.map +1 -1
  113. package/dist/app/commands/update.js +9 -2
  114. package/dist/app/commands/update.js.map +1 -1
  115. package/dist/config/repository-layout.json +0 -8
  116. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  117. package/dist/domains/bundle/bundle-platform.js +8 -0
  118. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  119. package/dist/domains/bundle/types.d.ts +1 -1
  120. package/dist/domains/bundle/types.d.ts.map +1 -1
  121. package/dist/domains/comet-classic/classic-evidence.d.ts.map +1 -1
  122. package/dist/domains/comet-classic/classic-evidence.js +45 -9
  123. package/dist/domains/comet-classic/classic-evidence.js.map +1 -1
  124. package/dist/domains/comet-classic/classic-layout-initialization.d.ts +4 -3
  125. package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
  126. package/dist/domains/comet-classic/classic-layout-initialization.js +13 -9
  127. package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
  128. package/dist/domains/comet-classic/classic-layout.d.ts +2 -11
  129. package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
  130. package/dist/domains/comet-classic/classic-layout.js +22 -28
  131. package/dist/domains/comet-classic/classic-layout.js.map +1 -1
  132. package/dist/domains/comet-classic/classic-root-command.d.ts.map +1 -1
  133. package/dist/domains/comet-classic/classic-root-command.js +6 -1
  134. package/dist/domains/comet-classic/classic-root-command.js.map +1 -1
  135. package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
  136. package/dist/domains/comet-entry/hook-adapter.js +6 -0
  137. package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
  138. package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
  139. package/dist/domains/comet-entry/hook-router-entry.js +11 -2
  140. package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
  141. package/dist/domains/comet-entry/project-activation.d.ts.map +1 -1
  142. package/dist/domains/comet-entry/project-activation.js +2 -1
  143. package/dist/domains/comet-entry/project-activation.js.map +1 -1
  144. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  145. package/dist/domains/comet-entry/resume-probe.js +48 -4
  146. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  147. package/dist/domains/comet-native/native-acceptance.d.ts +4 -3
  148. package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
  149. package/dist/domains/comet-native/native-acceptance.js +23 -18
  150. package/dist/domains/comet-native/native-acceptance.js.map +1 -1
  151. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  152. package/dist/domains/comet-native/native-archive-command.js +204 -61
  153. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  154. package/dist/domains/comet-native/native-archive-transaction.d.ts.map +1 -1
  155. package/dist/domains/comet-native/native-archive-transaction.js +28 -23
  156. package/dist/domains/comet-native/native-archive-transaction.js.map +1 -1
  157. package/dist/domains/comet-native/native-archive.d.ts +1 -0
  158. package/dist/domains/comet-native/native-archive.d.ts.map +1 -1
  159. package/dist/domains/comet-native/native-archive.js +56 -12
  160. package/dist/domains/comet-native/native-archive.js.map +1 -1
  161. package/dist/domains/comet-native/native-bounded-file.d.ts +32 -2
  162. package/dist/domains/comet-native/native-bounded-file.d.ts.map +1 -1
  163. package/dist/domains/comet-native/native-bounded-file.js +87 -6
  164. package/dist/domains/comet-native/native-bounded-file.js.map +1 -1
  165. package/dist/domains/comet-native/native-build-evidence.d.ts.map +1 -1
  166. package/dist/domains/comet-native/native-build-evidence.js +23 -1
  167. package/dist/domains/comet-native/native-build-evidence.js.map +1 -1
  168. package/dist/domains/comet-native/native-change.d.ts +1 -0
  169. package/dist/domains/comet-native/native-change.d.ts.map +1 -1
  170. package/dist/domains/comet-native/native-change.js +96 -8
  171. package/dist/domains/comet-native/native-change.js.map +1 -1
  172. package/dist/domains/comet-native/native-check-executor.d.ts +36 -0
  173. package/dist/domains/comet-native/native-check-executor.d.ts.map +1 -0
  174. package/dist/domains/comet-native/native-check-executor.js +132 -0
  175. package/dist/domains/comet-native/native-check-executor.js.map +1 -0
  176. package/dist/domains/comet-native/native-check-receipt-model.d.ts +9 -0
  177. package/dist/domains/comet-native/native-check-receipt-model.d.ts.map +1 -1
  178. package/dist/domains/comet-native/native-check-receipt-model.js +70 -8
  179. package/dist/domains/comet-native/native-check-receipt-model.js.map +1 -1
  180. package/dist/domains/comet-native/native-check-receipt-storage.d.ts.map +1 -1
  181. package/dist/domains/comet-native/native-check-receipt-storage.js +9 -8
  182. package/dist/domains/comet-native/native-check-receipt-storage.js.map +1 -1
  183. package/dist/domains/comet-native/native-check-receipt.d.ts.map +1 -1
  184. package/dist/domains/comet-native/native-check-receipt.js +123 -60
  185. package/dist/domains/comet-native/native-check-receipt.js.map +1 -1
  186. package/dist/domains/comet-native/native-checkpoint-command.d.ts.map +1 -1
  187. package/dist/domains/comet-native/native-checkpoint-command.js +0 -6
  188. package/dist/domains/comet-native/native-checkpoint-command.js.map +1 -1
  189. package/dist/domains/comet-native/native-checkpoint-storage.d.ts.map +1 -1
  190. package/dist/domains/comet-native/native-checkpoint-storage.js +27 -19
  191. package/dist/domains/comet-native/native-checkpoint-storage.js.map +1 -1
  192. package/dist/domains/comet-native/native-cli-help.d.ts +6 -0
  193. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -0
  194. package/dist/domains/comet-native/native-cli-help.js +192 -0
  195. package/dist/domains/comet-native/native-cli-help.js.map +1 -0
  196. package/dist/domains/comet-native/native-cli-shared.d.ts +2 -2
  197. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  198. package/dist/domains/comet-native/native-cli-shared.js +46 -24
  199. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  200. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  201. package/dist/domains/comet-native/native-cli.js +18 -11
  202. package/dist/domains/comet-native/native-cli.js.map +1 -1
  203. package/dist/domains/comet-native/native-config.d.ts +2 -1
  204. package/dist/domains/comet-native/native-config.d.ts.map +1 -1
  205. package/dist/domains/comet-native/native-config.js +2 -1
  206. package/dist/domains/comet-native/native-config.js.map +1 -1
  207. package/dist/domains/comet-native/native-continuation.d.ts.map +1 -1
  208. package/dist/domains/comet-native/native-continuation.js +175 -147
  209. package/dist/domains/comet-native/native-continuation.js.map +1 -1
  210. package/dist/domains/comet-native/native-diagnostics.d.ts.map +1 -1
  211. package/dist/domains/comet-native/native-diagnostics.js +96 -13
  212. package/dist/domains/comet-native/native-diagnostics.js.map +1 -1
  213. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  214. package/dist/domains/comet-native/native-doctor-command.js +327 -0
  215. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  216. package/dist/domains/comet-native/native-doctor.d.ts +1 -0
  217. package/dist/domains/comet-native/native-doctor.d.ts.map +1 -1
  218. package/dist/domains/comet-native/native-doctor.js +116 -22
  219. package/dist/domains/comet-native/native-doctor.js.map +1 -1
  220. package/dist/domains/comet-native/native-evidence-projection.d.ts +50 -0
  221. package/dist/domains/comet-native/native-evidence-projection.d.ts.map +1 -0
  222. package/dist/domains/comet-native/native-evidence-projection.js +284 -0
  223. package/dist/domains/comet-native/native-evidence-projection.js.map +1 -0
  224. package/dist/domains/comet-native/native-evidence-retention.d.ts.map +1 -1
  225. package/dist/domains/comet-native/native-evidence-retention.js +14 -12
  226. package/dist/domains/comet-native/native-evidence-retention.js.map +1 -1
  227. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  228. package/dist/domains/comet-native/native-evidence-storage.js +14 -11
  229. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  230. package/dist/domains/comet-native/native-findings.d.ts.map +1 -1
  231. package/dist/domains/comet-native/native-findings.js +18 -0
  232. package/dist/domains/comet-native/native-findings.js.map +1 -1
  233. package/dist/domains/comet-native/native-git-provenance.d.ts +16 -0
  234. package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -0
  235. package/dist/domains/comet-native/native-git-provenance.js +171 -0
  236. package/dist/domains/comet-native/native-git-provenance.js.map +1 -0
  237. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  238. package/dist/domains/comet-native/native-hook-guard.js +159 -18
  239. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  240. package/dist/domains/comet-native/native-init-command.d.ts.map +1 -1
  241. package/dist/domains/comet-native/native-init-command.js +14 -2
  242. package/dist/domains/comet-native/native-init-command.js.map +1 -1
  243. package/dist/domains/comet-native/native-local-execution.d.ts +25 -0
  244. package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -0
  245. package/dist/domains/comet-native/native-local-execution.js +241 -0
  246. package/dist/domains/comet-native/native-local-execution.js.map +1 -0
  247. package/dist/domains/comet-native/native-lock.d.ts +1 -1
  248. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  249. package/dist/domains/comet-native/native-lock.js +9 -9
  250. package/dist/domains/comet-native/native-lock.js.map +1 -1
  251. package/dist/domains/comet-native/native-loop-runtime.d.ts +63 -0
  252. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -0
  253. package/dist/domains/comet-native/native-loop-runtime.js +580 -0
  254. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -0
  255. package/dist/domains/comet-native/native-mutation-lock.d.ts +2 -0
  256. package/dist/domains/comet-native/native-mutation-lock.d.ts.map +1 -1
  257. package/dist/domains/comet-native/native-mutation-lock.js +23 -2
  258. package/dist/domains/comet-native/native-mutation-lock.js.map +1 -1
  259. package/dist/domains/comet-native/native-new-command.d.ts.map +1 -1
  260. package/dist/domains/comet-native/native-new-command.js +27 -20
  261. package/dist/domains/comet-native/native-new-command.js.map +1 -1
  262. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  263. package/dist/domains/comet-native/native-next-command.js +114 -63
  264. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  265. package/dist/domains/comet-native/native-paths.d.ts +18 -0
  266. package/dist/domains/comet-native/native-paths.d.ts.map +1 -1
  267. package/dist/domains/comet-native/native-paths.js +125 -13
  268. package/dist/domains/comet-native/native-paths.js.map +1 -1
  269. package/dist/domains/comet-native/native-portable-acceptance.d.ts +28 -0
  270. package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -0
  271. package/dist/domains/comet-native/native-portable-acceptance.js +73 -0
  272. package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -0
  273. package/dist/domains/comet-native/native-portable-archive.d.ts +37 -0
  274. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -0
  275. package/dist/domains/comet-native/native-portable-archive.js +492 -0
  276. package/dist/domains/comet-native/native-portable-archive.js.map +1 -0
  277. package/dist/domains/comet-native/native-portable-continuation.d.ts +29 -0
  278. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -0
  279. package/dist/domains/comet-native/native-portable-continuation.js +341 -0
  280. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -0
  281. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts +9 -0
  282. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -0
  283. package/dist/domains/comet-native/native-portable-migration-runtime.js +213 -0
  284. package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -0
  285. package/dist/domains/comet-native/native-portable-migration.d.ts +42 -0
  286. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -0
  287. package/dist/domains/comet-native/native-portable-migration.js +212 -0
  288. package/dist/domains/comet-native/native-portable-migration.js.map +1 -0
  289. package/dist/domains/comet-native/native-portable-recovery.d.ts +15 -0
  290. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -0
  291. package/dist/domains/comet-native/native-portable-recovery.js +203 -0
  292. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -0
  293. package/dist/domains/comet-native/native-portable-runtime.d.ts +150 -0
  294. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -0
  295. package/dist/domains/comet-native/native-portable-runtime.js +1444 -0
  296. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -0
  297. package/dist/domains/comet-native/native-portable-state.d.ts +30 -0
  298. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -0
  299. package/dist/domains/comet-native/native-portable-state.js +688 -0
  300. package/dist/domains/comet-native/native-portable-state.js.map +1 -0
  301. package/dist/domains/comet-native/native-portable-status.d.ts +62 -0
  302. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -0
  303. package/dist/domains/comet-native/native-portable-status.js +125 -0
  304. package/dist/domains/comet-native/native-portable-status.js.map +1 -0
  305. package/dist/domains/comet-native/native-portable-text.d.ts +8 -0
  306. package/dist/domains/comet-native/native-portable-text.d.ts.map +1 -0
  307. package/dist/domains/comet-native/native-portable-text.js +28 -0
  308. package/dist/domains/comet-native/native-portable-text.js.map +1 -0
  309. package/dist/domains/comet-native/native-portable-transactions.d.ts +41 -0
  310. package/dist/domains/comet-native/native-portable-transactions.d.ts.map +1 -0
  311. package/dist/domains/comet-native/native-portable-transactions.js +204 -0
  312. package/dist/domains/comet-native/native-portable-transactions.js.map +1 -0
  313. package/dist/domains/comet-native/native-portable-types.d.ts +165 -0
  314. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -0
  315. package/dist/domains/comet-native/native-portable-types.js +18 -0
  316. package/dist/domains/comet-native/native-portable-types.js.map +1 -0
  317. package/dist/domains/comet-native/native-repair-integration.js +5 -5
  318. package/dist/domains/comet-native/native-repair-integration.js.map +1 -1
  319. package/dist/domains/comet-native/native-resume-view.d.ts.map +1 -1
  320. package/dist/domains/comet-native/native-resume-view.js +1 -5
  321. package/dist/domains/comet-native/native-resume-view.js.map +1 -1
  322. package/dist/domains/comet-native/native-root-move.d.ts.map +1 -1
  323. package/dist/domains/comet-native/native-root-move.js +4 -20
  324. package/dist/domains/comet-native/native-root-move.js.map +1 -1
  325. package/dist/domains/comet-native/native-run-consistency.d.ts.map +1 -1
  326. package/dist/domains/comet-native/native-run-consistency.js +8 -12
  327. package/dist/domains/comet-native/native-run-consistency.js.map +1 -1
  328. package/dist/domains/comet-native/native-run-store.js +4 -4
  329. package/dist/domains/comet-native/native-run-store.js.map +1 -1
  330. package/dist/domains/comet-native/native-runner-input.d.ts +160 -0
  331. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -0
  332. package/dist/domains/comet-native/native-runner-input.js +347 -0
  333. package/dist/domains/comet-native/native-runner-input.js.map +1 -0
  334. package/dist/domains/comet-native/native-runner-protocol.d.ts +40 -0
  335. package/dist/domains/comet-native/native-runner-protocol.d.ts.map +1 -0
  336. package/dist/domains/comet-native/native-runner-protocol.js +55 -0
  337. package/dist/domains/comet-native/native-runner-protocol.js.map +1 -0
  338. package/dist/domains/comet-native/native-runtime-package.d.ts +3 -0
  339. package/dist/domains/comet-native/native-runtime-package.d.ts.map +1 -1
  340. package/dist/domains/comet-native/native-runtime-package.js +5 -1
  341. package/dist/domains/comet-native/native-runtime-package.js.map +1 -1
  342. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  343. package/dist/domains/comet-native/native-schema-migration.js +30 -27
  344. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  345. package/dist/domains/comet-native/native-select-command.d.ts.map +1 -1
  346. package/dist/domains/comet-native/native-select-command.js +8 -4
  347. package/dist/domains/comet-native/native-select-command.js.map +1 -1
  348. package/dist/domains/comet-native/native-selection.d.ts.map +1 -1
  349. package/dist/domains/comet-native/native-selection.js +11 -2
  350. package/dist/domains/comet-native/native-selection.js.map +1 -1
  351. package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
  352. package/dist/domains/comet-native/native-show-command.js +36 -0
  353. package/dist/domains/comet-native/native-show-command.js.map +1 -1
  354. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  355. package/dist/domains/comet-native/native-snapshot.js +13 -10
  356. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  357. package/dist/domains/comet-native/native-spec-command.d.ts.map +1 -1
  358. package/dist/domains/comet-native/native-spec-command.js +14 -28
  359. package/dist/domains/comet-native/native-spec-command.js.map +1 -1
  360. package/dist/domains/comet-native/native-specs.js +3 -3
  361. package/dist/domains/comet-native/native-specs.js.map +1 -1
  362. package/dist/domains/comet-native/native-status-command.d.ts.map +1 -1
  363. package/dist/domains/comet-native/native-status-command.js +7 -17
  364. package/dist/domains/comet-native/native-status-command.js.map +1 -1
  365. package/dist/domains/comet-native/native-status-discovery.d.ts +51 -0
  366. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -0
  367. package/dist/domains/comet-native/native-status-discovery.js +299 -0
  368. package/dist/domains/comet-native/native-status-discovery.js.map +1 -0
  369. package/dist/domains/comet-native/native-trajectory-recovery.d.ts.map +1 -1
  370. package/dist/domains/comet-native/native-trajectory-recovery.js +6 -9
  371. package/dist/domains/comet-native/native-trajectory-recovery.js.map +1 -1
  372. package/dist/domains/comet-native/native-transaction.d.ts.map +1 -1
  373. package/dist/domains/comet-native/native-transaction.js +31 -20
  374. package/dist/domains/comet-native/native-transaction.js.map +1 -1
  375. package/dist/domains/comet-native/native-transition-evidence.d.ts.map +1 -1
  376. package/dist/domains/comet-native/native-transition-evidence.js +1 -0
  377. package/dist/domains/comet-native/native-transition-evidence.js.map +1 -1
  378. package/dist/domains/comet-native/native-transition-journal.d.ts.map +1 -1
  379. package/dist/domains/comet-native/native-transition-journal.js +71 -22
  380. package/dist/domains/comet-native/native-transition-journal.js.map +1 -1
  381. package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
  382. package/dist/domains/comet-native/native-transitions.js +167 -15
  383. package/dist/domains/comet-native/native-transitions.js.map +1 -1
  384. package/dist/domains/comet-native/native-types.d.ts +36 -1
  385. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  386. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  387. package/dist/domains/comet-native/native-verification-receipt-runtime.js +18 -100
  388. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  389. package/dist/domains/comet-native/native-verification-report-v2.d.ts +12 -0
  390. package/dist/domains/comet-native/native-verification-report-v2.d.ts.map +1 -0
  391. package/dist/domains/comet-native/native-verification-report-v2.js +141 -0
  392. package/dist/domains/comet-native/native-verification-report-v2.js.map +1 -0
  393. package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
  394. package/dist/domains/comet-native/native-verification-runtime.js +7 -2
  395. package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
  396. package/dist/domains/comet-native/native-verification-scope.d.ts +23 -0
  397. package/dist/domains/comet-native/native-verification-scope.d.ts.map +1 -1
  398. package/dist/domains/comet-native/native-verification-scope.js +106 -19
  399. package/dist/domains/comet-native/native-verification-scope.js.map +1 -1
  400. package/dist/domains/comet-native/native-verifier-protocol.d.ts +49 -0
  401. package/dist/domains/comet-native/native-verifier-protocol.d.ts.map +1 -0
  402. package/dist/domains/comet-native/native-verifier-protocol.js +157 -0
  403. package/dist/domains/comet-native/native-verifier-protocol.js.map +1 -0
  404. package/dist/domains/comet-native/native-workspace-finish.d.ts +61 -0
  405. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -0
  406. package/dist/domains/comet-native/native-workspace-finish.js +332 -0
  407. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -0
  408. package/dist/domains/comet-native/native-workspace-preparation.d.ts +32 -0
  409. package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -0
  410. package/dist/domains/comet-native/native-workspace-preparation.js +265 -0
  411. package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -0
  412. package/dist/domains/comet-native/native-workspace.d.ts +9 -1
  413. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  414. package/dist/domains/comet-native/native-workspace.js +109 -11
  415. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  416. package/dist/domains/dashboard/native-adapter.d.ts +136 -127
  417. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  418. package/dist/domains/dashboard/native-adapter.js +157 -271
  419. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  420. package/dist/domains/dashboard/native-collector.d.ts +4 -4
  421. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  422. package/dist/domains/dashboard/native-collector.js +230 -412
  423. package/dist/domains/dashboard/native-collector.js.map +1 -1
  424. package/dist/domains/dashboard/native-legacy-adapter.d.ts +30 -0
  425. package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -0
  426. package/dist/domains/dashboard/native-legacy-adapter.js +115 -0
  427. package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -0
  428. package/dist/domains/dashboard/web/assets/{arc-ClrSujVb.js → arc-CkuYweSh.js} +1 -1
  429. package/dist/domains/dashboard/web/assets/{architectureDiagram-3BPJPVTR-B4A_t84A.js → architectureDiagram-3BPJPVTR--tTGrKam.js} +1 -1
  430. package/dist/domains/dashboard/web/assets/{blockDiagram-GPEHLZMM-D72u2953.js → blockDiagram-GPEHLZMM-DLKYOixs.js} +1 -1
  431. package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-Ca5zba3N.js → c4Diagram-AAUBKEIU-BL17BIb8.js} +1 -1
  432. package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +1 -0
  433. package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-CCVPBm0J.js → chunk-2J33WTMH-B_DDS2IK.js} +1 -1
  434. package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-JYluRsP-.js → chunk-4BX2VUAB-vQyyh3eG.js} +1 -1
  435. package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-DfYm7pN7.js → chunk-55IACEB6-Cug8J1Qa.js} +1 -1
  436. package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-CwghIMO9.js → chunk-727SXJPM-pMreYMW7.js} +1 -1
  437. package/dist/domains/dashboard/web/assets/{chunk-AQP2D5EJ-BA_zgMXZ.js → chunk-AQP2D5EJ-BUkV_rb7.js} +1 -1
  438. package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-BAJLB5V6.js → chunk-FMBD7UC4-CQXqBSqQ.js} +1 -1
  439. package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-Bj6HWRwi.js → chunk-ND2GUHAM-XWLMOyd4.js} +1 -1
  440. package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-B1kXfg5N.js → chunk-QZHKN3VN-4drjXzHQ.js} +1 -1
  441. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +1 -0
  442. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +1 -0
  443. package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-BBrkuiAU.js → cose-bilkent-S5V4N54A-IQKP-hgj.js} +1 -1
  444. package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-DlFhgQHt.js → cynefin-VYW2F7L2-CvvRO4J2.js} +1 -1
  445. package/dist/domains/dashboard/web/assets/{dagre-BM42HDAG-B0Bk5oiP.js → dagre-BM42HDAG-DeOQo7bP.js} +1 -1
  446. package/dist/domains/dashboard/web/assets/demo-CeIDHUFJ.js +24 -0
  447. package/dist/domains/dashboard/web/assets/{diagram-2AECGRRQ-tvTUiBA2.js → diagram-2AECGRRQ-IQd_jQwB.js} +1 -1
  448. package/dist/domains/dashboard/web/assets/{diagram-5GNKFQAL-BZfcK29q.js → diagram-5GNKFQAL-Dllkdt0m.js} +1 -1
  449. package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-BQahyP-C.js → diagram-KO2AKTUF-CN_LYqvT.js} +1 -1
  450. package/dist/domains/dashboard/web/assets/{diagram-LMA3HP47-D5bJnW2C.js → diagram-LMA3HP47-DK36WkNN.js} +1 -1
  451. package/dist/domains/dashboard/web/assets/{diagram-OG6HWLK6-DTwWdzWJ.js → diagram-OG6HWLK6-iqUnMYEh.js} +1 -1
  452. package/dist/domains/dashboard/web/assets/{erDiagram-TEJ5UH35-BbvrdCp9.js → erDiagram-TEJ5UH35-Bc64lzy8.js} +1 -1
  453. package/dist/domains/dashboard/web/assets/{flowDiagram-I6XJVG4X-DgbR7Tcc.js → flowDiagram-I6XJVG4X-UfOqef9j.js} +1 -1
  454. package/dist/domains/dashboard/web/assets/{ganttDiagram-6RSMTGT7-wWMOA7F4.js → ganttDiagram-6RSMTGT7-D-u6Aauc.js} +1 -1
  455. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-DCxvMAUJ.js → gitGraphDiagram-PVQCEYII-CaWEk3PM.js} +1 -1
  456. package/dist/domains/dashboard/web/assets/index-BFwKBVTJ.css +1 -0
  457. package/dist/domains/dashboard/web/assets/{index-Blit0P5Z.js → index-BNyOfAhu.js} +1 -1
  458. package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +257 -0
  459. package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-9qXEkzDe.js → infoDiagram-5YYISTIA-BK07mNG0.js} +1 -1
  460. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-Dkf5othW.js → ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js} +1 -1
  461. package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-C2_IkO4s.js → journeyDiagram-JHISSGLW-BPy-P7xx.js} +1 -1
  462. package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-BxWgu4DL.js → kanban-definition-UN3LZRKU-3Jq9c_lo.js} +1 -1
  463. package/dist/domains/dashboard/web/assets/{linear-Dkr6p-Ro.js → linear-kQyEW-4G.js} +1 -1
  464. package/dist/domains/dashboard/web/assets/{mermaid.core-DZUcsoG4.js → mermaid.core-COBBjtVH.js} +4 -4
  465. package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-C9xyxGfa.js → mindmap-definition-RKZ34NQL-CyyurUpv.js} +1 -1
  466. package/dist/domains/dashboard/web/assets/{pieDiagram-4H26LBE5-Dn67tdOF.js → pieDiagram-4H26LBE5-CJro_XKk.js} +1 -1
  467. package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-Cy6iOcxc.js → quadrantDiagram-W4KKPZXB-CpayUMjH.js} +1 -1
  468. package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-B_gZONhx.js → requirementDiagram-4Y6WPE33-Bi8YpfnA.js} +1 -1
  469. package/dist/domains/dashboard/web/assets/{sankeyDiagram-5OEKKPKP-C3u-4dOk.js → sankeyDiagram-5OEKKPKP-Wx60WwHe.js} +1 -1
  470. package/dist/domains/dashboard/web/assets/{sequenceDiagram-3UESZ5HK-Xd3ByTVF.js → sequenceDiagram-3UESZ5HK-BiMsRFbc.js} +1 -1
  471. package/dist/domains/dashboard/web/assets/{stateDiagram-AJRCARHV-CJGHL7Up.js → stateDiagram-AJRCARHV-BrURMY0R.js} +1 -1
  472. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +1 -0
  473. package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-DvONX2YQ.js → timeline-definition-PNZ67QCA-aHrrtV-b.js} +1 -1
  474. package/dist/domains/dashboard/web/assets/{vennDiagram-CIIHVFJN-B-L4qWy4.js → vennDiagram-CIIHVFJN-DGB16bvR.js} +1 -1
  475. package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-cf39WX2o.js → wardleyDiagram-YWT4CUSO-RVQbcySh.js} +1 -1
  476. package/dist/domains/dashboard/web/assets/{xychartDiagram-2RQKCTM6-Dk1vcm3u.js → xychartDiagram-2RQKCTM6-DMzzwDVX.js} +1 -1
  477. package/dist/domains/dashboard/web/index.html +2 -2
  478. package/dist/domains/factory/package.d.ts.map +1 -1
  479. package/dist/domains/factory/package.js +7 -22
  480. package/dist/domains/factory/package.js.map +1 -1
  481. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  482. package/dist/domains/skill/platform-inspect.js +11 -3
  483. package/dist/domains/skill/platform-inspect.js.map +1 -1
  484. package/dist/domains/skill/platform-install.d.ts +7 -1
  485. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  486. package/dist/domains/skill/platform-install.js +114 -33
  487. package/dist/domains/skill/platform-install.js.map +1 -1
  488. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  489. package/dist/domains/skill/uninstall.js +69 -15
  490. package/dist/domains/skill/uninstall.js.map +1 -1
  491. package/dist/domains/workflow-contract/index.d.ts +1 -0
  492. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  493. package/dist/domains/workflow-contract/index.js +1 -0
  494. package/dist/domains/workflow-contract/index.js.map +1 -1
  495. package/dist/domains/workflow-contract/project-config.d.ts +2 -0
  496. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  497. package/dist/domains/workflow-contract/project-config.js +77 -17
  498. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  499. package/dist/domains/workflow-contract/project-gitignore.d.ts +9 -0
  500. package/dist/domains/workflow-contract/project-gitignore.d.ts.map +1 -0
  501. package/dist/domains/workflow-contract/project-gitignore.js +108 -0
  502. package/dist/domains/workflow-contract/project-gitignore.js.map +1 -0
  503. package/dist/platform/install/platforms.d.ts +3 -1
  504. package/dist/platform/install/platforms.d.ts.map +1 -1
  505. package/dist/platform/install/platforms.js +9 -0
  506. package/dist/platform/install/platforms.js.map +1 -1
  507. package/dist/platform/paths/git-worktree.d.ts +2 -1
  508. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  509. package/dist/platform/paths/git-worktree.js +14 -1
  510. package/dist/platform/paths/git-worktree.js.map +1 -1
  511. package/dist/platform/process/external-command.d.ts +13 -0
  512. package/dist/platform/process/external-command.d.ts.map +1 -0
  513. package/dist/platform/process/external-command.js +45 -0
  514. package/dist/platform/process/external-command.js.map +1 -0
  515. package/dist/platform/process/git.d.ts +12 -0
  516. package/dist/platform/process/git.d.ts.map +1 -0
  517. package/dist/platform/process/git.js +86 -0
  518. package/dist/platform/process/git.js.map +1 -0
  519. package/dist/platform/process/spawn-command.d.ts +8 -0
  520. package/dist/platform/process/spawn-command.d.ts.map +1 -0
  521. package/dist/platform/process/spawn-command.js +113 -0
  522. package/dist/platform/process/spawn-command.js.map +1 -0
  523. package/eval/local/tasks/comet-native-clarification/validation/test_native_clarification.py +9 -21
  524. package/eval/local/tasks/comet-native-clarification-depth/validation/test_native_clarification_depth.py +4 -7
  525. package/eval/local/tasks/comet-native-clarification-modes/validation/test_native_clarification_modes.py +4 -10
  526. package/eval/local/tasks/comet-native-interrupted-transition/instruction.md +1 -1
  527. package/eval/local/tasks/comet-native-interrupted-transition/validation/test_native_interrupted_transition.py +15 -16
  528. package/eval/local/tasks/comet-native-repository-fact/instruction.md +2 -2
  529. package/eval/local/tasks/comet-native-repository-fact/validation/test_native_repository_fact.py +8 -2
  530. package/eval/local/tasks/comet-native-wave-b-decision-resume/instruction.md +8 -4
  531. package/eval/local/tasks/comet-native-wave-b-decision-resume/task.toml +6 -6
  532. package/eval/local/tasks/comet-native-wave-b-decision-resume/validation/test_native_wave_b_decision_resume.py +126 -135
  533. package/eval/local/tasks/comet-native-wave-c-verification-integrity/instruction.md +6 -6
  534. package/eval/local/tasks/comet-native-wave-c-verification-integrity/task.toml +8 -8
  535. package/eval/local/tasks/comet-native-wave-c-verification-integrity/validation/test_native_wave_c_verification_integrity.py +97 -317
  536. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +7 -7
  537. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +4 -4
  538. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +130 -199
  539. package/eval/local/tasks/comet-native-wave-e-parallel-safety/instruction.md +5 -5
  540. package/eval/local/tasks/comet-native-wave-e-parallel-safety/task.toml +8 -8
  541. package/eval/local/tasks/comet-native-wave-e-parallel-safety/validation/test_native_wave_e_parallel_safety.py +135 -239
  542. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/instruction.md +3 -3
  543. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/task.toml +6 -6
  544. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/validation/test_native_wave_f_dashboard_readonly.py +81 -439
  545. package/eval/local/tasks/comet-native-workflow/instruction.md +5 -4
  546. package/eval/local/tasks/comet-native-workflow/validation/test_native_workflow.py +145 -502
  547. package/eval/local/tasks/index.yaml +5 -5
  548. package/eval/local/tests/scaffold/test_native_aligned_eval.py +146 -35
  549. package/eval/local/tests/scaffold/test_native_wave_evaluations.py +75 -2054
  550. package/eval/local/tests/scaffold/test_tasks.py +38 -52
  551. package/eval/local/tests/tasks/test_tasks.py +3 -3
  552. package/eval/local/treatments/comet/comet_native_phase1.yaml +7 -4
  553. package/eval/scaffold/python/native_eval.py +10 -5
  554. package/eval/scaffold/python/validation/native_v4.py +249 -0
  555. package/eval/scaffold/python/validation/native_wave.py +4 -5
  556. package/eval/scaffold/python/validation/native_workflow.py +193 -97
  557. package/eval/scaffold/python/validation/rubric.py +114 -1
  558. package/package.json +8 -5
  559. package/assets/skills/comet-native/scripts/comet-native-check.mjs +0 -179
  560. package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +0 -179
  561. package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +0 -151
  562. package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +0 -187
  563. package/dist/domains/comet-native/native-check-entry.d.ts +0 -2
  564. package/dist/domains/comet-native/native-check-entry.d.ts.map +0 -1
  565. package/dist/domains/comet-native/native-check-entry.js +0 -4
  566. package/dist/domains/comet-native/native-check-entry.js.map +0 -1
  567. package/dist/domains/comet-native/native-checkpoint-entry.d.ts +0 -2
  568. package/dist/domains/comet-native/native-checkpoint-entry.d.ts.map +0 -1
  569. package/dist/domains/comet-native/native-checkpoint-entry.js +0 -4
  570. package/dist/domains/comet-native/native-checkpoint-entry.js.map +0 -1
  571. package/dist/domains/comet-native/native-evidence-entry.d.ts +0 -2
  572. package/dist/domains/comet-native/native-evidence-entry.d.ts.map +0 -1
  573. package/dist/domains/comet-native/native-evidence-entry.js +0 -4
  574. package/dist/domains/comet-native/native-evidence-entry.js.map +0 -1
  575. package/dist/domains/comet-native/native-receipt-entry.d.ts +0 -2
  576. package/dist/domains/comet-native/native-receipt-entry.d.ts.map +0 -1
  577. package/dist/domains/comet-native/native-receipt-entry.js +0 -4
  578. package/dist/domains/comet-native/native-receipt-entry.js.map +0 -1
  579. package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +0 -1
  580. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-BpA7BPgX.js +0 -1
  581. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-BpA7BPgX.js +0 -1
  582. package/dist/domains/dashboard/web/assets/demo-DZYPLZpF.js +0 -25
  583. package/dist/domains/dashboard/web/assets/index-Bk1o-4VO.css +0 -1
  584. package/dist/domains/dashboard/web/assets/index-g8vyW0R_.js +0 -257
  585. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +0 -1
  586. /package/assets/skills/{comet → comet-classic}/reference/classic-layout.md +0 -0
  587. /package/assets/skills-zh/{comet → comet-classic}/reference/classic-layout.md +0 -0
@@ -1,175 +1,182 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var dv=Object.create;var Bl=Object.defineProperty;var fv=Object.getOwnPropertyDescriptor;var hv=Object.getOwnPropertyNames;var pv=Object.getPrototypeOf,mv=Object.prototype.hasOwnProperty;var nr=(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 vv=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of hv(t))!mv.call(e,r)&&r!==i&&Bl(e,r,{get:()=>t[r],enumerable:!(n=fv(t,r))||n.enumerable});return e};var vo=(e,t,i)=>(i=e!=null?dv(pv(e)):{},vv(t||!e||!e.__esModule?Bl(i,"default",{value:e,enumerable:!0}):i,e));var D=R(ae=>{"use strict";var go=Symbol.for("yaml.alias"),ql=Symbol.for("yaml.document"),rr=Symbol.for("yaml.map"),Vl=Symbol.for("yaml.pair"),wo=Symbol.for("yaml.scalar"),ar=Symbol.for("yaml.seq"),Ue=Symbol.for("yaml.node.type"),gv=e=>!!e&&typeof e=="object"&&e[Ue]===go,wv=e=>!!e&&typeof e=="object"&&e[Ue]===ql,yv=e=>!!e&&typeof e=="object"&&e[Ue]===rr,Nv=e=>!!e&&typeof e=="object"&&e[Ue]===Vl,Wl=e=>!!e&&typeof e=="object"&&e[Ue]===wo,bv=e=>!!e&&typeof e=="object"&&e[Ue]===ar;function zl(e){if(e&&typeof e=="object")switch(e[Ue]){case rr:case ar:return!0}return!1}function kv(e){if(e&&typeof e=="object")switch(e[Ue]){case go:case rr:case wo:case ar:return!0}return!1}var Sv=e=>(Wl(e)||zl(e))&&!!e.anchor;ae.ALIAS=go;ae.DOC=ql;ae.MAP=rr;ae.NODE_TYPE=Ue;ae.PAIR=Vl;ae.SCALAR=wo;ae.SEQ=ar;ae.hasAnchor=Sv;ae.isAlias=gv;ae.isCollection=zl;ae.isDocument=wv;ae.isMap=yv;ae.isNode=kv;ae.isPair=Nv;ae.isScalar=Wl;ae.isSeq=bv});var Bi=R(yo=>{"use strict";var re=D(),ue=Symbol("break visit"),Jl=Symbol("skip children"),Be=Symbol("remove node");function or(e,t){let i=Gl(t);re.isDocument(e)?ri(null,e.contents,i,Object.freeze([e]))===Be&&(e.contents=null):ri(null,e,i,Object.freeze([]))}or.BREAK=ue;or.SKIP=Jl;or.REMOVE=Be;function ri(e,t,i,n){let r=Ul(e,t,i,n);if(re.isNode(r)||re.isPair(r))return Kl(e,n,r),ri(e,r,i,n);if(typeof r!="symbol"){if(re.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=ri(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===ue)return ue;o===Be&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){n=Object.freeze(n.concat(t));let a=ri("key",t.key,i,n);if(a===ue)return ue;a===Be&&(t.key=null);let o=ri("value",t.value,i,n);if(o===ue)return ue;o===Be&&(t.value=null)}}return r}async function sr(e,t){let i=Gl(t);re.isDocument(e)?await ai(null,e.contents,i,Object.freeze([e]))===Be&&(e.contents=null):await ai(null,e,i,Object.freeze([]))}sr.BREAK=ue;sr.SKIP=Jl;sr.REMOVE=Be;async function ai(e,t,i,n){let r=await Ul(e,t,i,n);if(re.isNode(r)||re.isPair(r))return Kl(e,n,r),ai(e,r,i,n);if(typeof r!="symbol"){if(re.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await ai(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===ue)return ue;o===Be&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){n=Object.freeze(n.concat(t));let a=await ai("key",t.key,i,n);if(a===ue)return ue;a===Be&&(t.key=null);let o=await ai("value",t.value,i,n);if(o===ue)return ue;o===Be&&(t.value=null)}}return r}function Gl(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 Ul(e,t,i,n){if(typeof i=="function")return i(e,t,n);if(re.isMap(t))return i.Map?.(e,t,n);if(re.isSeq(t))return i.Seq?.(e,t,n);if(re.isPair(t))return i.Pair?.(e,t,n);if(re.isScalar(t))return i.Scalar?.(e,t,n);if(re.isAlias(t))return i.Alias?.(e,t,n)}function Kl(e,t,i){let n=t[t.length-1];if(re.isCollection(n))n.items[e]=i;else if(re.isPair(n))e==="key"?n.key=i:n.value=i;else if(re.isDocument(n))n.contents=i;else{let r=re.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}yo.visit=or;yo.visitAsync=sr});var No=R(Xl=>{"use strict";var Yl=D(),Ev=Bi(),Cv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rv=e=>e.replace(/[!,[\]{}]/g,t=>Cv[t]),qi=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+Rv(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&&Yl.isNode(t.contents)){let a={};Ev.visit(t.contents,(o,s)=>{Yl.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
- `)}};qi.defaultYaml={explicit:!1,version:"1.2"};qi.defaultTags={"!!":"tag:yaml.org,2002:"};Xl.Directives=qi});var cr=R(Vi=>{"use strict";var Ql=D(),Pv=Bi();function Av(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 Zl(e){let t=new Set;return Pv.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function eu(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function xv(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=Zl(e));let o=eu(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Ql.isScalar(o.node)||Ql.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}}Vi.anchorIsValid=Av;Vi.anchorNames=Zl;Vi.createNodeAnchors=xv;Vi.findNewAnchor=eu});var bo=R(tu=>{"use strict";function Wi(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=Wi(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=Wi(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=Wi(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=Wi(e,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return e.call(t,i,n)}tu.applyReviver=Wi});var at=R(nu=>{"use strict";var Tv=D();function iu(e,t,i){if(Array.isArray(e))return e.map((n,r)=>iu(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!Tv.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}nu.toJS=iu});var lr=R(au=>{"use strict";var Iv=bo(),ru=D(),_v=at(),ko=class{constructor(t){Object.defineProperty(this,ru.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(!ru.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=_v.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?Iv.applyReviver(a,{"":s},"",s):s}};au.NodeBase=ko});var zi=R(ou=>{"use strict";var jv=cr(),Ov=Bi(),oi=D(),$v=lr(),Hv=at(),So=class extends $v.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=[],Ov.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||(Hv.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=ur(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(jv.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 ur(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=ur(e,r,i);a>n&&(n=a)}return n}else if(oi.isPair(t)){let n=ur(e,t.key,i),r=ur(e,t.value,i);return Math.max(n,r)}return 1}ou.Alias=So});var te=R(Eo=>{"use strict";var Fv=D(),Dv=lr(),Mv=at(),Lv=e=>!e||typeof e!="function"&&typeof e!="object",ot=class extends Dv.NodeBase{constructor(t){super(Fv.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Mv.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";Eo.Scalar=ot;Eo.isScalarValue=Lv});var Ji=R(cu=>{"use strict";var Bv=zi(),Tt=D(),su=te(),qv="tag:yaml.org,2002:";function Vv(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 Wv(e,t,i){if(Tt.isDocument(e)&&(e=e.contents),Tt.isNode(e))return e;if(Tt.isPair(e)){let d=i.schema[Tt.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor: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 Bv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=qv+t.slice(2));let l=Vv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new su.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Tt.MAP]:Symbol.iterator in Object(e)?o[Tt.SEQ]:o[Tt.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 su.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}cu.createNode=Wv});var fr=R(dr=>{"use strict";var zv=Ji(),qe=D(),Jv=lr();function Co(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 zv.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 lu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ro=class extends Jv.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=>qe.isNode(n)||qe.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(lu(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(qe.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Co(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(qe.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&&qe.isScalar(a)?a.value:a:qe.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!qe.isPair(i))return!1;let n=i.value;return n==null||t&&qe.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 qe.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(qe.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Co(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};dr.Collection=Ro;dr.collectionFromPath=Co;dr.isEmptyPath=lu});var Gi=R(hr=>{"use strict";var Gv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Po(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Uv=(e,t,i)=>e.endsWith(`
6
- `)?Po(i,t):i.includes(`
4
+ var jg=Object.create;var Fu=Object.defineProperty;var $g=Object.getOwnPropertyDescriptor;var Og=Object.getOwnPropertyNames;var Hg=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty;var On=(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 C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Bg=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Og(t))!Dg.call(e,n)&&n!==i&&Fu(e,n,{get:()=>t[n],enumerable:!(r=$g(t,n))||r.enumerable});return e};var Hn=(e,t,i)=>(i=e!=null?jg(Hg(e)):{},Bg(t||!e||!e.__esModule?Fu(i,"default",{value:e,enumerable:!0}):i,e));var L=C(se=>{"use strict";var Xo=Symbol.for("yaml.alias"),Lu=Symbol.for("yaml.document"),Bn=Symbol.for("yaml.map"),Mu=Symbol.for("yaml.pair"),Qo=Symbol.for("yaml.scalar"),Fn=Symbol.for("yaml.seq"),pt=Symbol.for("yaml.node.type"),Wg=e=>!!e&&typeof e=="object"&&e[pt]===Xo,zg=e=>!!e&&typeof e=="object"&&e[pt]===Lu,Jg=e=>!!e&&typeof e=="object"&&e[pt]===Bn,Gg=e=>!!e&&typeof e=="object"&&e[pt]===Mu,qu=e=>!!e&&typeof e=="object"&&e[pt]===Qo,Ug=e=>!!e&&typeof e=="object"&&e[pt]===Fn;function Vu(e){if(e&&typeof e=="object")switch(e[pt]){case Bn:case Fn:return!0}return!1}function Kg(e){if(e&&typeof e=="object")switch(e[pt]){case Xo:case Bn:case Qo:case Fn:return!0}return!1}var Yg=e=>(qu(e)||Vu(e))&&!!e.anchor;se.ALIAS=Xo;se.DOC=Lu;se.MAP=Bn;se.NODE_TYPE=pt;se.PAIR=Mu;se.SCALAR=Qo;se.SEQ=Fn;se.hasAnchor=Yg;se.isAlias=Wg;se.isCollection=Vu;se.isDocument=zg;se.isMap=Jg;se.isNode=Kg;se.isPair=Gg;se.isScalar=qu;se.isSeq=Ug});var wr=C(Zo=>{"use strict";var ae=L(),ge=Symbol("break visit"),Wu=Symbol("skip children"),it=Symbol("remove node");function Ln(e,t){let i=zu(t);ae.isDocument(e)?Si(null,e.contents,i,Object.freeze([e]))===it&&(e.contents=null):Si(null,e,i,Object.freeze([]))}Ln.BREAK=ge;Ln.SKIP=Wu;Ln.REMOVE=it;function Si(e,t,i,r){let n=Ju(e,t,i,r);if(ae.isNode(n)||ae.isPair(n))return Gu(e,r,n),Si(e,n,i,r);if(typeof n!="symbol"){if(ae.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Si(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===it&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){r=Object.freeze(r.concat(t));let a=Si("key",t.key,i,r);if(a===ge)return ge;a===it&&(t.key=null);let o=Si("value",t.value,i,r);if(o===ge)return ge;o===it&&(t.value=null)}}return n}async function Mn(e,t){let i=zu(t);ae.isDocument(e)?await Ei(null,e.contents,i,Object.freeze([e]))===it&&(e.contents=null):await Ei(null,e,i,Object.freeze([]))}Mn.BREAK=ge;Mn.SKIP=Wu;Mn.REMOVE=it;async function Ei(e,t,i,r){let n=await Ju(e,t,i,r);if(ae.isNode(n)||ae.isPair(n))return Gu(e,r,n),Ei(e,n,i,r);if(typeof n!="symbol"){if(ae.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Ei(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===it&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){r=Object.freeze(r.concat(t));let a=await Ei("key",t.key,i,r);if(a===ge)return ge;a===it&&(t.key=null);let o=await Ei("value",t.value,i,r);if(o===ge)return ge;o===it&&(t.value=null)}}return n}function zu(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 Ju(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(ae.isMap(t))return i.Map?.(e,t,r);if(ae.isSeq(t))return i.Seq?.(e,t,r);if(ae.isPair(t))return i.Pair?.(e,t,r);if(ae.isScalar(t))return i.Scalar?.(e,t,r);if(ae.isAlias(t))return i.Alias?.(e,t,r)}function Gu(e,t,i){let r=t[t.length-1];if(ae.isCollection(r))r.items[e]=i;else if(ae.isPair(r))e==="key"?r.key=i:r.value=i;else if(ae.isDocument(r))r.contents=i;else{let n=ae.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Zo.visit=Ln;Zo.visitAsync=Mn});var es=C(Ku=>{"use strict";var Uu=L(),Xg=wr(),Qg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Zg=e=>e.replace(/[!,[\]{}]/g,t=>Qg[t]),yr=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+Zg(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&&Uu.isNode(t.contents)){let a={};Xg.visit(t.contents,(o,s)=>{Uu.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
+ `)}};yr.defaultYaml={explicit:!1,version:"1.2"};yr.defaultTags={"!!":"tag:yaml.org,2002:"};Ku.Directives=yr});var qn=C(Nr=>{"use strict";var Yu=L(),ew=wr();function tw(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 Xu(e){let t=new Set;return ew.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Qu(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function iw(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Xu(e));let o=Qu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Yu.isScalar(o.node)||Yu.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}}Nr.anchorIsValid=tw;Nr.anchorNames=Xu;Nr.createNodeAnchors=iw;Nr.findNewAnchor=Qu});var ts=C(Zu=>{"use strict";function br(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=br(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=br(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=br(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=br(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Zu.applyReviver=br});var Ct=C(td=>{"use strict";var rw=L();function ed(e,t,i){if(Array.isArray(e))return e.map((r,n)=>ed(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!rw.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}td.toJS=ed});var Vn=C(rd=>{"use strict";var nw=ts(),id=L(),aw=Ct(),is=class{constructor(t){Object.defineProperty(this,id.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(!id.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=aw.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?nw.applyReviver(a,{"":s},"",s):s}};rd.NodeBase=is});var kr=C(nd=>{"use strict";var ow=qn(),sw=wr(),Pi=L(),cw=Vn(),lw=Ct(),rs=class extends cw.NodeBase{constructor(t){super(Pi.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=[],sw.visit(t,{Node:(a,o)=>{(Pi.isAlias(o)||Pi.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||(lw.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=Wn(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(ow.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 Wn(e,t,i){if(Pi.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Pi.isCollection(t)){let r=0;for(let n of t.items){let a=Wn(e,n,i);a>r&&(r=a)}return r}else if(Pi.isPair(t)){let r=Wn(e,t.key,i),n=Wn(e,t.value,i);return Math.max(r,n)}return 1}nd.Alias=rs});var ie=C(ns=>{"use strict";var uw=L(),dw=Vn(),fw=Ct(),pw=e=>!e||typeof e!="function"&&typeof e!="object",Rt=class extends dw.NodeBase{constructor(t){super(uw.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:fw.toJS(this.value,t,i)}toString(){return String(this.value)}};Rt.BLOCK_FOLDED="BLOCK_FOLDED";Rt.BLOCK_LITERAL="BLOCK_LITERAL";Rt.PLAIN="PLAIN";Rt.QUOTE_DOUBLE="QUOTE_DOUBLE";Rt.QUOTE_SINGLE="QUOTE_SINGLE";ns.Scalar=Rt;ns.isScalarValue=pw});var Sr=C(od=>{"use strict";var hw=kr(),oi=L(),ad=ie(),mw="tag:yaml.org,2002:";function vw(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 gw(e,t,i){if(oi.isDocument(e)&&(e=e.contents),oi.isNode(e))return e;if(oi.isPair(e)){let d=i.schema[oi.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects: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 hw.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=mw+t.slice(2));let l=vw(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new ad.Scalar(e);return c&&(c.node=d),d}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 ad.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}od.createNode=gw});var Jn=C(zn=>{"use strict";var ww=Sr(),rt=L(),yw=Vn();function as(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 ww.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 sd=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,os=class extends yw.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=>rt.isNode(r)||rt.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(sd(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(rt.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,as(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(rt.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&&rt.isScalar(a)?a.value:a:rt.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!rt.isPair(i))return!1;let r=i.value;return r==null||t&&rt.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 rt.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(rt.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,as(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};zn.Collection=os;zn.collectionFromPath=as;zn.isEmptyPath=sd});var Er=C(Gn=>{"use strict";var Nw=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ss(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var bw=(e,t,i)=>e.endsWith(`
6
+ `)?ss(i,t):i.includes(`
7
7
  `)?`
8
- `+Po(i,t):(e.endsWith(" ")?"":" ")+i;hr.indentComment=Po;hr.lineComment=Uv;hr.stringifyComment=Gv});var du=R(Ui=>{"use strict";var Kv="flow",Ao="block",pr="quoted";function Yv(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={},d=r-t.length;typeof n=="number"&&(n>r-Math.max(2,a)?l.push(0):d=r-n);let f,p,m=!1,h=-1,g=-1,S=-1;i===Ao&&(h=uu(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(i===pr&&k==="\\"){switch(g=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(k===`
9
- `)i===Ao&&(h=uu(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
10
- `&&p!==" "){let b=e[h+1];b&&b!==" "&&b!==`
11
- `&&b!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===pr){for(;p===" "||p===" ";)p=k,k=e[h+=1],m=!0;let b=h>S+1?h-2:g-1;if(u[b])return e;l.push(b),u[b]=!0,d=b+c,f=void 0}else m=!0}p=k}if(m&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let b=l[k],C=l[k+1]||e.length;b===0?N=`
12
- ${t}${e.slice(0,C)}`:(i===pr&&u[b]&&(N+=`${e[b]}\\`),N+=`
13
- ${t}${e.slice(b+1,C)}`)}return N}function uu(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}Ui.FOLD_BLOCK=Ao;Ui.FOLD_FLOW=Kv;Ui.FOLD_QUOTED=pr;Ui.foldFlowLines=Yv});var Yi=R(fu=>{"use strict";var Ae=te(),st=du(),vr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),gr=e=>/^(%|---|\.\.\.)/m.test(e);function Xv(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 Ki(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(gr(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
+ `+ss(i,t):(e.endsWith(" ")?"":" ")+i;Gn.indentComment=ss;Gn.lineComment=bw;Gn.stringifyComment=Nw});var ld=C(Pr=>{"use strict";var kw="flow",cs="block",Un="quoted";function Sw(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=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,v=!1,p=-1,m=-1,b=-1;i===cs&&(p=cd(e,p,t.length),p!==-1&&(d=p+c));for(let P;P=e[p+=1];){if(i===Un&&P==="\\"){switch(m=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}b=p}if(P===`
9
+ `)i===cs&&(p=cd(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(P===" "&&h&&h!==" "&&h!==`
10
+ `&&h!==" "){let k=e[p+1];k&&k!==" "&&k!==`
11
+ `&&k!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Un){for(;h===" "||h===" ";)h=P,P=e[p+=1],v=!0;let k=p>b+1?p-2:m-1;if(u[k])return e;l.push(k),u[k]=!0,d=k+c,f=void 0}else v=!0}h=P}if(v&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let P=0;P<l.length;++P){let k=l[P],E=l[P+1]||e.length;k===0?N=`
12
+ ${t}${e.slice(0,E)}`:(i===Un&&u[k]&&(N+=`${e[k]}\\`),N+=`
13
+ ${t}${e.slice(k+1,E)}`)}return N}function cd(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}Pr.FOLD_BLOCK=cs;Pr.FOLD_FLOW=kw;Pr.FOLD_QUOTED=Un;Pr.foldFlowLines=Sw});var Cr=C(ud=>{"use strict";var Me=ie(),At=ld(),Yn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Xn=e=>/^(%|---|\.\.\.)/m.test(e);function Ew(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 xr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Xn(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(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:st.foldFlowLines(o,a,st.FOLD_QUOTED,vr(t,!1))}function xo(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Ki(e,t);let i=t.indent||(gr(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?n:st.foldFlowLines(n,i,st.FOLD_FLOW,vr(t,!1))}function si(e,t){let{singleQuote:i}=t.options,n;if(i===!1)n=Ki;else{let r=e.includes('"'),a=e.includes("'");r&&!a?n=xo:a&&!r?n=Ki:n=i?xo:Ki}return n(e,t)}var To;try{To=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:At.foldFlowLines(o,a,At.FOLD_QUOTED,Yn(t,!1))}function ls(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return xr(e,t);let i=t.indent||(Xn(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?r:At.foldFlowLines(r,i,At.FOLD_FLOW,Yn(t,!1))}function xi(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=xr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=ls:a&&!n?r=xr:r=i?ls:xr}return r(e,t)}var us;try{us=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{To=/\n+(?!\n|$)/g}function mr({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 si(i,n);let l=n.indent||(n.forceBlockIndent||gr(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ae.Scalar.BLOCK_FOLDED?!1:t===Ae.Scalar.BLOCK_LITERAL?!0:!Xv(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{us=/\n+(?!\n|$)/g}function Kn({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 xi(i,r);let l=r.indent||(r.forceBlockIndent||Xn(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Me.Scalar.BLOCK_FOLDED?!1:t===Me.Scalar.BLOCK_LITERAL?!0:!Ew(i,c,l.length);if(!i)return u?`|
24
24
  `:`>
25
- `;let d,f;for(f=i.length;f>0;--f){let C=i[f-1];if(C!==`
26
- `&&C!==" "&&C!==" ")break}let p=i.substring(f),m=p.indexOf(`
27
- `);m===-1?d="-":i===p||m!==p.length-1?(d="+",a&&a()):d="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
28
- `&&(p=p.slice(0,-1)),p=p.replace(To,`$&${l}`));let h=!1,g,S=-1;for(g=0;g<i.length;++g){let C=i[g];if(C===" ")h=!0;else if(C===`
29
- `)S=g;else break}let N=i.substring(0,S<g?S+1:g);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+d;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let C=i.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),y=!1,w=vr(n,!0);o!=="folded"&&t!==Ae.Scalar.BLOCK_FOLDED&&(w.onOverflow=()=>{y=!0});let v=st.foldFlowLines(`${N}${C}${p}`,l,st.FOLD_BLOCK,w);if(!y)return`>${b}
31
- ${l}${v}`}return i=i.replace(/\n+/g,`$&${l}`),`|${b}
32
- ${l}${N}${i}${p}`}function Qv(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 si(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?si(a,t):mr(e,t,i,n);if(!s&&!u&&r!==Ae.Scalar.PLAIN&&a.includes(`
35
- `))return mr(e,t,i,n);if(gr(a)){if(c==="")return t.forceBlockIndent=!0,mr(e,t,i,n);if(s&&c===l)return si(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(f)||p?.some(f))return si(a,t)}return s?d:st.foldFlowLines(d,c,st.FOLD_FLOW,vr(t,!1))}function Zv(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!==Ae.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ae.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ae.Scalar.BLOCK_FOLDED:case Ae.Scalar.BLOCK_LITERAL:return r||a?si(o.value,t):mr(o,t,i,n);case Ae.Scalar.QUOTE_DOUBLE:return Ki(o.value,t);case Ae.Scalar.QUOTE_SINGLE:return xo(o.value,t);case Ae.Scalar.PLAIN:return Qv(o,t,i,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=r&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}fu.stringifyString=Zv});var Xi=R(Io=>{"use strict";var eg=cr(),ct=D(),tg=Gi(),ig=Yi();function ng(e,t){let i=Object.assign({blockQuote:!0,commentString:tg.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 rg(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(ct.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 ag(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(ct.isScalar(e)||ct.isCollection(e))&&e.anchor;a&&eg.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 og(e,t,i,n){if(ct.isPair(e))return e.toString(t,i,n);if(ct.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=ct.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=rg(t.doc.schema.tags,a));let o=ag(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):ct.isScalar(a)?ig.stringifyString(a,t,i,n):a.toString(t,i,n);return o?ct.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Io.createStringifyContext=ng;Io.stringify=og});var vu=R(mu=>{"use strict";var Ke=D(),hu=te(),pu=Xi(),Qi=Gi();function sg({key:e,value:t},i,n,r){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=Ke.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ke.isCollection(e)||!Ke.isNode(e)&&typeof e=="object"){let w="With simple keys, collection cannot be used as a key value";throw new Error(w)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||Ke.isCollection(e)||(Ke.isScalar(e)?e.type===hu.Scalar.BLOCK_FOLDED||e.type===hu.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=pu.stringify(e,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&g.length>1024){if(d)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(),g===""?"?":p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=Qi.lineComment(g,i.indent,l(f)):h&&r&&r(),g;m&&(f=null),p?(f&&(g+=Qi.lineComment(g,i.indent,l(f))),g=`? ${g}
38
- ${s}:`):(g=`${g}:`,f&&(g+=Qi.lineComment(g,i.indent,l(f))));let S,N,k;Ke.isNode(t)?(S=!!t.spaceBefore,N=t.commentBefore,k=t.comment):(S=!1,N=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&Ke.isScalar(t)&&(i.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&Ke.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let b=!1,C=pu.stringify(t,i,()=>b=!0,()=>h=!0),y=" ";if(f||S||N){if(y=S?`
39
- `:"",N){let w=l(N);y+=`
40
- ${Qi.indentComment(w,i.indent)}`}C===""&&!i.inFlow?y===`
41
- `&&k&&(y=`
25
+ `;let d,f;for(f=i.length;f>0;--f){let E=i[f-1];if(E!==`
26
+ `&&E!==" "&&E!==" ")break}let h=i.substring(f),v=h.indexOf(`
27
+ `);v===-1?d="-":i===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(i=i.slice(0,-h.length),h[h.length-1]===`
28
+ `&&(h=h.slice(0,-1)),h=h.replace(us,`$&${l}`));let p=!1,m,b=-1;for(m=0;m<i.length;++m){let E=i[m];if(E===" ")p=!0;else if(E===`
29
+ `)b=m;else break}let N=i.substring(0,b<m?b+1:m);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let k=(p?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=i.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),y=!1,x=Yn(r,!0);o!=="folded"&&t!==Me.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{y=!0});let w=At.foldFlowLines(`${N}${E}${h}`,l,At.FOLD_BLOCK,x);if(!y)return`>${k}
31
+ ${l}${w}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
32
+ ${l}${N}${i}${h}`}function Pw(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return xi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?xi(a,t):Kn(e,t,i,r);if(!s&&!u&&n!==Me.Scalar.PLAIN&&a.includes(`
35
+ `))return Kn(e,t,i,r);if(Xn(a)){if(c==="")return t.forceBlockIndent=!0,Kn(e,t,i,r);if(s&&c===l)return xi(a,t)}let d=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return xi(a,t)}return s?d:At.foldFlowLines(d,c,At.FOLD_FLOW,Yn(t,!1))}function xw(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!==Me.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Me.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Me.Scalar.BLOCK_FOLDED:case Me.Scalar.BLOCK_LITERAL:return n||a?xi(o.value,t):Kn(o,t,i,r);case Me.Scalar.QUOTE_DOUBLE:return xr(o.value,t);case Me.Scalar.QUOTE_SINGLE:return ls(o.value,t);case Me.Scalar.PLAIN:return Pw(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}ud.stringifyString=xw});var Rr=C(ds=>{"use strict";var Cw=qn(),_t=L(),Rw=Er(),Aw=Cr();function _w(e,t){let i=Object.assign({blockQuote:!0,commentString:Rw.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 Tw(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(_t.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 Iw(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(_t.isScalar(e)||_t.isCollection(e))&&e.anchor;a&&Cw.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 jw(e,t,i,r){if(_t.isPair(e))return e.toString(t,i,r);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 n,a=_t.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Tw(t.doc.schema.tags,a));let o=Iw(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):_t.isScalar(a)?Aw.stringifyString(a,t,i,r):a.toString(t,i,r);return o?_t.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}ds.createStringifyContext=_w;ds.stringify=jw});var hd=C(pd=>{"use strict";var ht=L(),dd=ie(),fd=Rr(),Ar=Er();function $w({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=ht.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ht.isCollection(e)||!ht.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||ht.isCollection(e)||(ht.isScalar(e)?e.type===dd.Scalar.BLOCK_FOLDED||e.type===dd.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,p=!1,m=fd.stringify(e,i,()=>v=!0,()=>p=!0);if(!h&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":h?`? ${m}`:m}else if(a&&!d||t==null&&h)return m=`? ${m}`,f&&!v?m+=Ar.lineComment(m,i.indent,l(f)):p&&n&&n(),m;v&&(f=null),h?(f&&(m+=Ar.lineComment(m,i.indent,l(f))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,f&&(m+=Ar.lineComment(m,i.indent,l(f))));let b,N,P;ht.isNode(t)?(b=!!t.spaceBefore,N=t.commentBefore,P=t.comment):(b=!1,N=null,P=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&ht.isScalar(t)&&(i.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&ht.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,E=fd.stringify(t,i,()=>k=!0,()=>p=!0),y=" ";if(f||b||N){if(y=b?`
39
+ `:"",N){let x=l(N);y+=`
40
+ ${Ar.indentComment(x,i.indent)}`}E===""&&!i.inFlow?y===`
41
+ `&&P&&(y=`
42
42
 
43
43
  `):y+=`
44
- ${i.indent}`}else if(!p&&Ke.isCollection(t)){let w=C[0],v=C.indexOf(`
45
- `),E=v!==-1,I=i.inFlow??t.flow??t.items.length===0;if(E||!I){let J=!1;if(E&&(w==="&"||w==="!")){let L=C.indexOf(" ");w==="&"&&L!==-1&&L<v&&C[L+1]==="!"&&(L=C.indexOf(" ",L+1)),(L===-1||v<L)&&(J=!0)}J||(y=`
46
- ${i.indent}`)}}else(C===""||C[0]===`
47
- `)&&(y="");return g+=y+C,i.inFlow?b&&n&&n():k&&!b?g+=Qi.lineComment(g,i.indent,l(k)):h&&r&&r(),g}mu.stringifyPair=sg});var jo=R(_o=>{"use strict";var gu=nr("process");function cg(e,...t){e==="debug"&&console.log(...t)}function lg(e,t){(e==="debug"||e==="warn")&&(typeof gu.emitWarning=="function"?gu.emitWarning(t):console.warn(t))}_o.debug=cg;_o.warn=lg});var kr=R(br=>{"use strict";var Nr=D(),wu=te(),wr="<<",yr={identify:e=>e===wr||typeof e=="symbol"&&e.description===wr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wu.Scalar(Symbol(wr)),{addToJSMap:yu}),stringify:()=>wr},ug=(e,t)=>(yr.identify(t)||Nr.isScalar(t)&&(!t.type||t.type===wu.Scalar.PLAIN)&&yr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===yr.tag&&i.default);function yu(e,t,i){let n=Nu(e,i);if(Nr.isSeq(n))for(let r of n.items)Oo(e,t,r);else if(Array.isArray(n))for(let r of n)Oo(e,t,r);else Oo(e,t,n)}function Oo(e,t,i){let n=Nu(e,i);if(!Nr.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 Nu(e,t){return e&&Nr.isAlias(t)?t.resolve(e.doc,e):t}br.addMergeToJSMap=yu;br.isMergeKey=ug;br.merge=yr});var Ho=R(Su=>{"use strict";var dg=jo(),bu=kr(),fg=Xi(),ku=D(),$o=at();function hg(e,t,{key:i,value:n}){if(ku.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(bu.isMergeKey(e,i))bu.addMergeToJSMap(e,t,n);else{let r=$o.toJS(i,"",e);if(t instanceof Map)t.set(r,$o.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=pg(i,r,e),o=$o.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 pg(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(ku.isNode(e)&&i?.doc){let n=fg.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)+'..."'),dg.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)}Su.addPairToJSMap=hg});var lt=R(Fo=>{"use strict";var Eu=Ji(),mg=vu(),vg=Ho(),Sr=D();function gg(e,t,i){let n=Eu.createNode(e,void 0,i),r=Eu.createNode(t,void 0,i);return new Er(n,r)}var Er=class e{constructor(t,i=null){Object.defineProperty(this,Sr.NODE_TYPE,{value:Sr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return Sr.isNode(i)&&(i=i.clone(t)),Sr.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return vg.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?mg.stringifyPair(this,t,i,n):JSON.stringify(this)}};Fo.Pair=Er;Fo.createPair=gg});var Do=R(Ru=>{"use strict";var It=D(),Cu=Xi(),Cr=Gi();function wg(e,t,i){return(t.inFlow??e.flow?Ng:yg)(e,t,i)}function yg({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}),d=!1,f=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(It.isNode(h))!d&&h.spaceBefore&&f.push(""),Rr(i,f,h.commentBefore,d),h.comment&&(g=h.comment);else if(It.isPair(h)){let N=It.isNode(h.key)?h.key:null;N&&(!d&&N.spaceBefore&&f.push(""),Rr(i,f,N.commentBefore,d))}d=!1;let S=Cu.stringify(h,u,()=>g=null,()=>d=!0);g&&(S+=Cr.lineComment(S,a,l(g))),d&&g&&(d=!1),f.push(n+S)}let p;if(f.length===0)p=r.start+r.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
48
- ${c}${h}`:`
49
- `}}return e?(p+=`
50
- `+Cr.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Ng({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,d=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(It.isNode(h))h.spaceBefore&&d.push(""),Rr(t,d,h.commentBefore,!1),h.comment&&(g=h.comment);else if(It.isPair(h)){let N=It.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&d.push(""),Rr(t,d,N.commentBefore,!1),N.comment&&(l=!0));let k=It.isNode(h.value)?h.value:null;k?(k.comment&&(g=k.comment),k.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(g=N.comment)}g&&(l=!0);let S=Cu.stringify(h,c,()=>g=null);l||(l=d.length>u||S.includes(`
51
- `)),m<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((N,k)=>N+k.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),g&&(S+=Cr.lineComment(S,n,s(g))),d.push(S),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,g)=>h+g.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?`
52
- ${a}${r}${h}`:`
53
- `;return`${m}
54
- ${r}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Rr({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=Cr.indentComment(t(n),e);i.push(a.trimStart())}}Ru.stringifyCollection=wg});var dt=R(Lo=>{"use strict";var bg=Do(),kg=Ho(),Sg=fr(),ut=D(),Pr=lt(),Eg=te();function Zi(e,t){let i=ut.isScalar(t)?t.value:t;for(let n of e)if(ut.isPair(n)&&(n.key===t||n.key===i||ut.isScalar(n.key)&&n.key.value===i))return n}var Mo=class extends Sg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ut.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(Pr.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;ut.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Pr.Pair(t,t?.value):n=new Pr.Pair(t.key,t.value);let r=Zi(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);ut.isScalar(r.value)&&Eg.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=Zi(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=Zi(this.items,t)?.value;return(!i&&ut.isScalar(r)?r.value:r)??void 0}has(t){return!!Zi(this.items,t)}set(t,i){this.add(new Pr.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)kg.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!ut.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})),bg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};Lo.YAMLMap=Mo;Lo.findPair=Zi});var ci=R(Au=>{"use strict";var Cg=D(),Pu=dt(),Rg={collection:"map",default:!0,nodeClass:Pu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Cg.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Pu.YAMLMap.from(e,t,i)};Au.map=Rg});var ft=R(xu=>{"use strict";var Pg=Ji(),Ag=Do(),xg=fr(),xr=D(),Tg=te(),Ig=at(),Bo=class extends xg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(xr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ar(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=Ar(t);if(typeof n!="number")return;let r=this.items[n];return!i&&xr.isScalar(r)?r.value:r}has(t){let i=Ar(t);return typeof i=="number"&&i<this.items.length}set(t,i){let n=Ar(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[n];xr.isScalar(r)&&Tg.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(Ig.toJS(a,String(r++),i));return n}toString(t,i,n){return t?Ag.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(Pg.createNode(s,void 0,n))}}return a}};function Ar(e){let t=xr.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}xu.YAMLSeq=Bo});var li=R(Iu=>{"use strict";var _g=D(),Tu=ft(),jg={collection:"seq",default:!0,nodeClass:Tu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return _g.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Tu.YAMLSeq.from(e,t,i)};Iu.seq=jg});var en=R(_u=>{"use strict";var Og=Yi(),$g={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),Og.stringifyString(e,t,i,n)}};_u.string=$g});var Tr=R($u=>{"use strict";var ju=te(),Ou={identify:e=>e==null,createNode:()=>new ju.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ju.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Ou.test.test(e)?e:t.options.nullStr};$u.nullTag=Ou});var qo=R(Fu=>{"use strict";var Hg=te(),Hu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Hg.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Hu.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};Fu.boolTag=Hu});var ui=R(Du=>{"use strict";function Fg({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}Du.stringifyNumber=Fg});var Wo=R(Ir=>{"use strict";var Dg=te(),Vo=ui(),Mg={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:Vo.stringifyNumber},Lg={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():Vo.stringifyNumber(e)}},Bg={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 Dg.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Vo.stringifyNumber};Ir.float=Bg;Ir.floatExp=Lg;Ir.floatNaN=Mg});var Jo=R(jr=>{"use strict";var Mu=ui(),_r=e=>typeof e=="bigint"||Number.isInteger(e),zo=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function Lu(e,t,i){let{value:n}=e;return _r(n)&&n>=0?i+n.toString(t):Mu.stringifyNumber(e)}var qg={identify:e=>_r(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>zo(e,2,8,i),stringify:e=>Lu(e,8,"0o")},Vg={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>zo(e,0,10,i),stringify:Mu.stringifyNumber},Wg={identify:e=>_r(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>zo(e,2,16,i),stringify:e=>Lu(e,16,"0x")};jr.int=Vg;jr.intHex=Wg;jr.intOct=qg});var qu=R(Bu=>{"use strict";var zg=ci(),Jg=Tr(),Gg=li(),Ug=en(),Kg=qo(),Go=Wo(),Uo=Jo(),Yg=[zg.map,Gg.seq,Ug.string,Jg.nullTag,Kg.boolTag,Uo.intOct,Uo.int,Uo.intHex,Go.floatNaN,Go.floatExp,Go.float];Bu.schema=Yg});var zu=R(Wu=>{"use strict";var Xg=te(),Qg=ci(),Zg=li();function Vu(e){return typeof e=="bigint"||Number.isInteger(e)}var Or=({value:e})=>JSON.stringify(e),ew=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Or},{identify:e=>e==null,createNode:()=>new Xg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Or},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Or},{identify:Vu,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})=>Vu(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:Or}],tw={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},iw=[Qg.map,Zg.seq].concat(ew,tw);Wu.schema=iw});var Yo=R(Ju=>{"use strict";var tn=nr("buffer"),Ko=te(),nw=Yi(),rw={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof tn.Buffer=="function")return tn.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 tn.Buffer=="function")s=o instanceof tn.Buffer?o.toString("base64"):tn.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=Ko.Scalar.BLOCK_LITERAL),t!==Ko.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Ko.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return nw.stringifyString({comment:e,type:t,value:s},n,r,a)}};Ju.binary=rw});var Fr=R(Hr=>{"use strict";var $r=D(),Xo=lt(),aw=te(),ow=ft();function Gu(e,t){if($r.isSeq(e))for(let i=0;i<e.items.length;++i){let n=e.items[i];if(!$r.isPair(n)){if($r.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new Xo.Pair(new aw.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]=$r.isPair(n)?n:new Xo.Pair(n)}}else t("Expected a sequence for this tag");return e}function Uu(e,t,i){let{replacer:n}=i,r=new ow.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(Xo.createPair(s,c,i))}return r}var sw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gu,createNode:Uu};Hr.createPairs=Uu;Hr.pairs=sw;Hr.resolvePairs=Gu});var es=R(Zo=>{"use strict";var Ku=D(),Qo=at(),nn=dt(),cw=ft(),Yu=Fr(),_t=class e extends cw.YAMLSeq{constructor(){super(),this.add=nn.YAMLMap.prototype.add.bind(this),this.delete=nn.YAMLMap.prototype.delete.bind(this),this.get=nn.YAMLMap.prototype.get.bind(this),this.has=nn.YAMLMap.prototype.has.bind(this),this.set=nn.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(Ku.isPair(r)?(a=Qo.toJS(r.key,"",i),o=Qo.toJS(r.value,a,i)):a=Qo.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=Yu.createPairs(t,i,n),a=new this;return a.items=r.items,a}};_t.tag="tag:yaml.org,2002:omap";var lw={collection:"seq",identify:e=>e instanceof Map,nodeClass:_t,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Yu.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Ku.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new _t,i)},createNode:(e,t,i)=>_t.from(e,t,i)};Zo.YAMLOMap=_t;Zo.omap=lw});var td=R(ts=>{"use strict";var Xu=te();function Qu({value:e,source:t},i){return t&&(e?Zu:ed).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Zu={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 Xu.Scalar(!0),stringify:Qu},ed={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 Xu.Scalar(!1),stringify:Qu};ts.falseTag=ed;ts.trueTag=Zu});var id=R(Dr=>{"use strict";var uw=te(),is=ui(),dw={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:is.stringifyNumber},fw={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():is.stringifyNumber(e)}},hw={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 uw.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:is.stringifyNumber};Dr.float=hw;Dr.floatExp=fw;Dr.floatNaN=dw});var rd=R(an=>{"use strict";var nd=ui(),rn=e=>typeof e=="bigint"||Number.isInteger(e);function Mr(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 ns(e,t,i){let{value:n}=e;if(rn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return nd.stringifyNumber(e)}var pw={identify:rn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Mr(e,2,2,i),stringify:e=>ns(e,2,"0b")},mw={identify:rn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Mr(e,1,8,i),stringify:e=>ns(e,8,"0")},vw={identify:rn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Mr(e,0,10,i),stringify:nd.stringifyNumber},gw={identify:rn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Mr(e,2,16,i),stringify:e=>ns(e,16,"0x")};an.int=vw;an.intBin=pw;an.intHex=gw;an.intOct=mw});var as=R(rs=>{"use strict";var qr=D(),Lr=lt(),Br=dt(),jt=class e extends Br.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;qr.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Lr.Pair(t.key,null):i=new Lr.Pair(t,null),Br.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=Br.findPair(this.items,t);return!i&&qr.isPair(n)?qr.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=Br.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Lr.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(Lr.createPair(o,null,n));return a}};jt.tag="tag:yaml.org,2002:set";var ww={collection:"map",identify:e=>e instanceof Set,nodeClass:jt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>jt.from(e,t,i),resolve(e,t){if(qr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new jt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};rs.YAMLSet=jt;rs.set=ww});var ss=R(Vr=>{"use strict";var yw=ui();function os(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 ad(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return yw.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 Nw={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})=>os(e,i),stringify:ad},bw={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=>os(e,!1),stringify:ad},od={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(od.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 d=os(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Vr.floatTime=bw;Vr.intTime=Nw;Vr.timestamp=od});var ld=R(cd=>{"use strict";var kw=ci(),Sw=Tr(),Ew=li(),Cw=en(),Rw=Yo(),sd=td(),cs=id(),Wr=rd(),Pw=kr(),Aw=es(),xw=Fr(),Tw=as(),ls=ss(),Iw=[kw.map,Ew.seq,Cw.string,Sw.nullTag,sd.trueTag,sd.falseTag,Wr.intBin,Wr.intOct,Wr.int,Wr.intHex,cs.floatNaN,cs.floatExp,cs.float,Rw.binary,Pw.merge,Aw.omap,xw.pairs,Tw.set,ls.intTime,ls.floatTime,ls.timestamp];cd.schema=Iw});var yd=R(fs=>{"use strict";var hd=ci(),_w=Tr(),pd=li(),jw=en(),Ow=qo(),us=Wo(),ds=Jo(),$w=qu(),Hw=zu(),md=Yo(),on=kr(),vd=es(),gd=Fr(),ud=ld(),wd=as(),zr=ss(),dd=new Map([["core",$w.schema],["failsafe",[hd.map,pd.seq,jw.string]],["json",Hw.schema],["yaml11",ud.schema],["yaml-1.1",ud.schema]]),fd={binary:md.binary,bool:Ow.boolTag,float:us.float,floatExp:us.floatExp,floatNaN:us.floatNaN,floatTime:zr.floatTime,int:ds.int,intHex:ds.intHex,intOct:ds.intOct,intTime:zr.intTime,map:hd.map,merge:on.merge,null:_w.nullTag,omap:vd.omap,pairs:gd.pairs,seq:pd.seq,set:wd.set,timestamp:zr.timestamp},Fw={"tag:yaml.org,2002:binary":md.binary,"tag:yaml.org,2002:merge":on.merge,"tag:yaml.org,2002:omap":vd.omap,"tag:yaml.org,2002:pairs":gd.pairs,"tag:yaml.org,2002:set":wd.set,"tag:yaml.org,2002:timestamp":zr.timestamp};function Dw(e,t,i){let n=dd.get(t);if(n&&!e)return i&&!n.includes(on.merge)?n.concat(on.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(dd.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(on.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?fd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(fd).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},[])}fs.coreKnownTags=Fw;fs.getTags=Dw});var ms=R(Nd=>{"use strict";var hs=D(),Mw=ci(),Lw=li(),Bw=en(),Jr=yd(),qw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ps=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Jr.getTags(t,"compat"):t?Jr.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Jr.coreKnownTags:{},this.tags=Jr.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,hs.MAP,{value:Mw.map}),Object.defineProperty(this,hs.SCALAR,{value:Bw.string}),Object.defineProperty(this,hs.SEQ,{value:Lw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?qw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Nd.Schema=ps});var kd=R(bd=>{"use strict";var Vw=D(),vs=Xi(),sn=Gi();function Ww(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=vs.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(sn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Vw.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(sn.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=vs.stringify(e.contents,r,()=>s=null,c);s&&(l+=sn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(vs.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(sn.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(sn.indentComment(a(c),"")))}return i.join(`
44
+ ${i.indent}`}else if(!h&&ht.isCollection(t)){let x=E[0],w=E.indexOf(`
45
+ `),g=w!==-1,S=i.inFlow??t.flow??t.items.length===0;if(g||!S){let D=!1;if(g&&(x==="&"||x==="!")){let I=E.indexOf(" ");x==="&"&&I!==-1&&I<w&&E[I+1]==="!"&&(I=E.indexOf(" ",I+1)),(I===-1||w<I)&&(D=!0)}D||(y=`
46
+ ${i.indent}`)}}else(E===""||E[0]===`
47
+ `)&&(y="");return m+=y+E,i.inFlow?k&&r&&r():P&&!k?m+=Ar.lineComment(m,i.indent,l(P)):p&&n&&n(),m}pd.stringifyPair=$w});var ps=C(fs=>{"use strict";var md=On("process");function Ow(e,...t){e==="debug"&&console.log(...t)}function Hw(e,t){(e==="debug"||e==="warn")&&(typeof md.emitWarning=="function"?md.emitWarning(t):console.warn(t))}fs.debug=Ow;fs.warn=Hw});var ia=C(ta=>{"use strict";var ea=L(),vd=ie(),Qn="<<",Zn={identify:e=>e===Qn||typeof e=="symbol"&&e.description===Qn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new vd.Scalar(Symbol(Qn)),{addToJSMap:gd}),stringify:()=>Qn},Dw=(e,t)=>(Zn.identify(t)||ea.isScalar(t)&&(!t.type||t.type===vd.Scalar.PLAIN)&&Zn.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Zn.tag&&i.default);function gd(e,t,i){let r=wd(e,i);if(ea.isSeq(r))for(let n of r.items)hs(e,t,n);else if(Array.isArray(r))for(let n of r)hs(e,t,n);else hs(e,t,r)}function hs(e,t,i){let r=wd(e,i);if(!ea.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 wd(e,t){return e&&ea.isAlias(t)?t.resolve(e.doc,e):t}ta.addMergeToJSMap=gd;ta.isMergeKey=Dw;ta.merge=Zn});var vs=C(bd=>{"use strict";var Bw=ps(),yd=ia(),Fw=Rr(),Nd=L(),ms=Ct();function Lw(e,t,{key:i,value:r}){if(Nd.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(yd.isMergeKey(e,i))yd.addMergeToJSMap(e,t,r);else{let n=ms.toJS(i,"",e);if(t instanceof Map)t.set(n,ms.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=Mw(i,n,e),o=ms.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 Mw(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Nd.isNode(e)&&i?.doc){let r=Fw.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)+'..."'),Bw.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)}bd.addPairToJSMap=Lw});var Tt=C(gs=>{"use strict";var kd=Sr(),qw=hd(),Vw=vs(),ra=L();function Ww(e,t,i){let r=kd.createNode(e,void 0,i),n=kd.createNode(t,void 0,i);return new na(r,n)}var na=class e{constructor(t,i=null){Object.defineProperty(this,ra.NODE_TYPE,{value:ra.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return ra.isNode(i)&&(i=i.clone(t)),ra.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return Vw.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?qw.stringifyPair(this,t,i,r):JSON.stringify(this)}};gs.Pair=na;gs.createPair=Ww});var ws=C(Ed=>{"use strict";var si=L(),Sd=Rr(),aa=Er();function zw(e,t,i){return(t.inFlow??e.flow?Gw:Jw)(e,t,i)}function Jw({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if(si.isNode(p))!d&&p.spaceBefore&&f.push(""),oa(i,f,p.commentBefore,d),p.comment&&(m=p.comment);else if(si.isPair(p)){let N=si.isNode(p.key)?p.key:null;N&&(!d&&N.spaceBefore&&f.push(""),oa(i,f,N.commentBefore,d))}d=!1;let b=Sd.stringify(p,u,()=>m=null,()=>d=!0);m&&(b+=aa.lineComment(b,a,l(m))),d&&m&&(d=!1),f.push(r+b)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let p=f[v];h+=p?`
48
+ ${c}${p}`:`
49
+ `}}return e?(h+=`
50
+ `+aa.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function Gw({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,u=0,d=[];for(let v=0;v<e.length;++v){let p=e[v],m=null;if(si.isNode(p))p.spaceBefore&&d.push(""),oa(t,d,p.commentBefore,!1),p.comment&&(m=p.comment);else if(si.isPair(p)){let N=si.isNode(p.key)?p.key:null;N&&(N.spaceBefore&&d.push(""),oa(t,d,N.commentBefore,!1),N.comment&&(l=!0));let P=si.isNode(p.value)?p.value:null;P?(P.comment&&(m=P.comment),P.commentBefore&&(l=!0)):p.value==null&&N?.comment&&(m=N.comment)}m&&(l=!0);let b=Sd.stringify(p,c,()=>m=null);l||(l=d.length>u||b.includes(`
51
+ `)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((N,P)=>N+P.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),m&&(b+=aa.lineComment(b,r,s(m))),d.push(b),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let v=d.reduce((p,m)=>p+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let p of d)v+=p?`
52
+ ${a}${n}${p}`:`
53
+ `;return`${v}
54
+ ${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function oa({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=aa.indentComment(t(r),e);i.push(a.trimStart())}}Ed.stringifyCollection=zw});var jt=C(Ns=>{"use strict";var Uw=ws(),Kw=vs(),Yw=Jn(),It=L(),sa=Tt(),Xw=ie();function _r(e,t){let i=It.isScalar(t)?t.value:t;for(let r of e)if(It.isPair(r)&&(r.key===t||r.key===i||It.isScalar(r.key)&&r.key.value===i))return r}var ys=class extends Yw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(It.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(sa.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;It.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new sa.Pair(t,t?.value):r=new sa.Pair(t.key,t.value);let n=_r(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);It.isScalar(n.value)&&Xw.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=_r(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=_r(this.items,t)?.value;return(!i&&It.isScalar(n)?n.value:n)??void 0}has(t){return!!_r(this.items,t)}set(t,i){this.add(new sa.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)Kw.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!It.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})),Uw.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Ns.YAMLMap=ys;Ns.findPair=_r});var Ci=C(xd=>{"use strict";var Qw=L(),Pd=jt(),Zw={collection:"map",default:!0,nodeClass:Pd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Qw.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Pd.YAMLMap.from(e,t,i)};xd.map=Zw});var $t=C(Cd=>{"use strict";var ey=Sr(),ty=ws(),iy=Jn(),la=L(),ry=ie(),ny=Ct(),bs=class extends iy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(la.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=ca(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=ca(t);if(typeof r!="number")return;let n=this.items[r];return!i&&la.isScalar(n)?n.value:n}has(t){let i=ca(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=ca(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];la.isScalar(n)&&ry.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(ny.toJS(a,String(n++),i));return r}toString(t,i,r){return t?ty.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(ey.createNode(s,void 0,r))}}return a}};function ca(e){let t=la.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Cd.YAMLSeq=bs});var Ri=C(Ad=>{"use strict";var ay=L(),Rd=$t(),oy={collection:"seq",default:!0,nodeClass:Rd.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ay.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Rd.YAMLSeq.from(e,t,i)};Ad.seq=oy});var Tr=C(_d=>{"use strict";var sy=Cr(),cy={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),sy.stringifyString(e,t,i,r)}};_d.string=cy});var ua=C(jd=>{"use strict";var Td=ie(),Id={identify:e=>e==null,createNode:()=>new Td.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Td.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Id.test.test(e)?e:t.options.nullStr};jd.nullTag=Id});var ks=C(Od=>{"use strict";var ly=ie(),$d={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new ly.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&$d.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Od.boolTag=$d});var Ai=C(Hd=>{"use strict";function uy({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}Hd.stringifyNumber=uy});var Es=C(da=>{"use strict";var dy=ie(),Ss=Ai(),fy={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:Ss.stringifyNumber},py={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():Ss.stringifyNumber(e)}},hy={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 dy.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ss.stringifyNumber};da.float=hy;da.floatExp=py;da.floatNaN=fy});var xs=C(pa=>{"use strict";var Dd=Ai(),fa=e=>typeof e=="bigint"||Number.isInteger(e),Ps=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Bd(e,t,i){let{value:r}=e;return fa(r)&&r>=0?i+r.toString(t):Dd.stringifyNumber(e)}var my={identify:e=>fa(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Ps(e,2,8,i),stringify:e=>Bd(e,8,"0o")},vy={identify:fa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Ps(e,0,10,i),stringify:Dd.stringifyNumber},gy={identify:e=>fa(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Ps(e,2,16,i),stringify:e=>Bd(e,16,"0x")};pa.int=vy;pa.intHex=gy;pa.intOct=my});var Ld=C(Fd=>{"use strict";var wy=Ci(),yy=ua(),Ny=Ri(),by=Tr(),ky=ks(),Cs=Es(),Rs=xs(),Sy=[wy.map,Ny.seq,by.string,yy.nullTag,ky.boolTag,Rs.intOct,Rs.int,Rs.intHex,Cs.floatNaN,Cs.floatExp,Cs.float];Fd.schema=Sy});var Vd=C(qd=>{"use strict";var Ey=ie(),Py=Ci(),xy=Ri();function Md(e){return typeof e=="bigint"||Number.isInteger(e)}var ha=({value:e})=>JSON.stringify(e),Cy=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ha},{identify:e=>e==null,createNode:()=>new Ey.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ha},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ha},{identify:Md,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})=>Md(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ha}],Ry={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Ay=[Py.map,xy.seq].concat(Cy,Ry);qd.schema=Ay});var _s=C(Wd=>{"use strict";var Ir=On("buffer"),As=ie(),_y=Cr(),Ty={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ir.Buffer=="function")return Ir.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 Ir.Buffer=="function")s=o instanceof Ir.Buffer?o.toString("base64"):Ir.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=As.Scalar.BLOCK_LITERAL),t!==As.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===As.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return _y.stringifyString({comment:e,type:t,value:s},r,n,a)}};Wd.binary=Ty});var ga=C(va=>{"use strict";var ma=L(),Ts=Tt(),Iy=ie(),jy=$t();function zd(e,t){if(ma.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!ma.isPair(r)){if(ma.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Ts.Pair(new Iy.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]=ma.isPair(r)?r:new Ts.Pair(r)}}else t("Expected a sequence for this tag");return e}function Jd(e,t,i){let{replacer:r}=i,n=new jy.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(Ts.createPair(s,c,i))}return n}var $y={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:zd,createNode:Jd};va.createPairs=Jd;va.pairs=$y;va.resolvePairs=zd});var $s=C(js=>{"use strict";var Gd=L(),Is=Ct(),jr=jt(),Oy=$t(),Ud=ga(),ci=class e extends Oy.YAMLSeq{constructor(){super(),this.add=jr.YAMLMap.prototype.add.bind(this),this.delete=jr.YAMLMap.prototype.delete.bind(this),this.get=jr.YAMLMap.prototype.get.bind(this),this.has=jr.YAMLMap.prototype.has.bind(this),this.set=jr.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(Gd.isPair(n)?(a=Is.toJS(n.key,"",i),o=Is.toJS(n.value,a,i)):a=Is.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=Ud.createPairs(t,i,r),a=new this;return a.items=n.items,a}};ci.tag="tag:yaml.org,2002:omap";var Hy={collection:"seq",identify:e=>e instanceof Map,nodeClass:ci,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Ud.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Gd.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new ci,i)},createNode:(e,t,i)=>ci.from(e,t,i)};js.YAMLOMap=ci;js.omap=Hy});var Zd=C(Os=>{"use strict";var Kd=ie();function Yd({value:e,source:t},i){return t&&(e?Xd:Qd).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Xd={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 Kd.Scalar(!0),stringify:Yd},Qd={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 Kd.Scalar(!1),stringify:Yd};Os.falseTag=Qd;Os.trueTag=Xd});var ef=C(wa=>{"use strict";var Dy=ie(),Hs=Ai(),By={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:Hs.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.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Hs.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 Dy.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:Hs.stringifyNumber};wa.float=Ly;wa.floatExp=Fy;wa.floatNaN=By});var rf=C(Or=>{"use strict";var tf=Ai(),$r=e=>typeof e=="bigint"||Number.isInteger(e);function ya(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 Ds(e,t,i){let{value:r}=e;if($r(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return tf.stringifyNumber(e)}var My={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>ya(e,2,2,i),stringify:e=>Ds(e,2,"0b")},qy={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>ya(e,1,8,i),stringify:e=>Ds(e,8,"0")},Vy={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>ya(e,0,10,i),stringify:tf.stringifyNumber},Wy={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>ya(e,2,16,i),stringify:e=>Ds(e,16,"0x")};Or.int=Vy;Or.intBin=My;Or.intHex=Wy;Or.intOct=qy});var Fs=C(Bs=>{"use strict";var ka=L(),Na=Tt(),ba=jt(),li=class e extends ba.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;ka.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Na.Pair(t.key,null):i=new Na.Pair(t,null),ba.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=ba.findPair(this.items,t);return!i&&ka.isPair(r)?ka.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=ba.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Na.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(Na.createPair(o,null,r));return a}};li.tag="tag:yaml.org,2002:set";var zy={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(ka.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}};Bs.YAMLSet=li;Bs.set=zy});var Ms=C(Sa=>{"use strict";var Jy=Ai();function Ls(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 nf(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Jy.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 Gy={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})=>Ls(e,i),stringify:nf},Uy={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=>Ls(e,!1),stringify:nf},af={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(af.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),u=t[8];if(u&&u!=="Z"){let d=Ls(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Sa.floatTime=Uy;Sa.intTime=Gy;Sa.timestamp=af});var cf=C(sf=>{"use strict";var Ky=Ci(),Yy=ua(),Xy=Ri(),Qy=Tr(),Zy=_s(),of=Zd(),qs=ef(),Ea=rf(),eN=ia(),tN=$s(),iN=ga(),rN=Fs(),Vs=Ms(),nN=[Ky.map,Xy.seq,Qy.string,Yy.nullTag,of.trueTag,of.falseTag,Ea.intBin,Ea.intOct,Ea.int,Ea.intHex,qs.floatNaN,qs.floatExp,qs.float,Zy.binary,eN.merge,tN.omap,iN.pairs,rN.set,Vs.intTime,Vs.floatTime,Vs.timestamp];sf.schema=nN});var wf=C(Js=>{"use strict";var ff=Ci(),aN=ua(),pf=Ri(),oN=Tr(),sN=ks(),Ws=Es(),zs=xs(),cN=Ld(),lN=Vd(),hf=_s(),Hr=ia(),mf=$s(),vf=ga(),lf=cf(),gf=Fs(),Pa=Ms(),uf=new Map([["core",cN.schema],["failsafe",[ff.map,pf.seq,oN.string]],["json",lN.schema],["yaml11",lf.schema],["yaml-1.1",lf.schema]]),df={binary:hf.binary,bool:sN.boolTag,float:Ws.float,floatExp:Ws.floatExp,floatNaN:Ws.floatNaN,floatTime:Pa.floatTime,int:zs.int,intHex:zs.intHex,intOct:zs.intOct,intTime:Pa.intTime,map:ff.map,merge:Hr.merge,null:aN.nullTag,omap:mf.omap,pairs:vf.pairs,seq:pf.seq,set:gf.set,timestamp:Pa.timestamp},uN={"tag:yaml.org,2002:binary":hf.binary,"tag:yaml.org,2002:merge":Hr.merge,"tag:yaml.org,2002:omap":mf.omap,"tag:yaml.org,2002:pairs":vf.pairs,"tag:yaml.org,2002:set":gf.set,"tag:yaml.org,2002:timestamp":Pa.timestamp};function dN(e,t,i){let r=uf.get(t);if(r&&!e)return i&&!r.includes(Hr.merge)?r.concat(Hr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(uf.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(Hr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?df[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(df).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},[])}Js.coreKnownTags=uN;Js.getTags=dN});var Ks=C(yf=>{"use strict";var Gs=L(),fN=Ci(),pN=Ri(),hN=Tr(),xa=wf(),mN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Us=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?xa.getTags(t,"compat"):t?xa.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?xa.coreKnownTags:{},this.tags=xa.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Gs.MAP,{value:fN.map}),Object.defineProperty(this,Gs.SCALAR,{value:hN.string}),Object.defineProperty(this,Gs.SEQ,{value:pN.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}};yf.Schema=Us});var bf=C(Nf=>{"use strict";var vN=L(),Ys=Rr(),Dr=Er();function gN(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=Ys.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Dr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(vN.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Dr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ys.stringify(e.contents,n,()=>s=null,c);s&&(l+=Dr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ys.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(Dr.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(Dr.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}bd.stringifyDocument=Ww});var cn=R(Sd=>{"use strict";var zw=zi(),di=fr(),be=D(),Jw=lt(),Gw=at(),Uw=ms(),Kw=kd(),gs=cr(),Yw=bo(),Xw=Ji(),ws=No(),ys=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,be.NODE_TYPE,{value:be.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 ws.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,{[be.NODE_TYPE]:{value:be.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=be.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){fi(this.contents)&&this.contents.add(t)}addIn(t,i){fi(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=gs.anchorNames(this);t.anchor=!i||n.has(i)?gs.findNewAnchor(i||"a",n):i}return new zw.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 g=N=>typeof N=="number"||N instanceof String||N instanceof Number,S=i.filter(g).map(String);S.length>0&&(i=i.concat(S)),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:d,setAnchors:f,sourceObjects:p}=gs.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=Xw.createNode(t,u,m);return s&&be.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,n={}){let r=this.createNode(t,null,n),a=this.createNode(i,null,n);return new Jw.Pair(r,a)}delete(t){return fi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return di.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):fi(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return be.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return di.isEmptyPath(t)?!i&&be.isScalar(this.contents)?this.contents.value:this.contents:be.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return be.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return di.isEmptyPath(t)?this.contents!==void 0:be.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=di.collectionFromPath(this.schema,[t],i):fi(this.contents)&&this.contents.set(t,i)}setIn(t,i){di.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=di.collectionFromPath(this.schema,Array.from(t),i):fi(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 ws.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 ws.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 Uw.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=Gw.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"?Yw.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 Kw.stringifyDocument(this,t)}};function fi(e){if(be.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Sd.Document=ys});var dn=R(un=>{"use strict";var ln=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},Ns=class extends ln{constructor(t,i,n){super("YAMLParseError",t,i,n)}},bs=class extends ln{constructor(t,i,n){super("YAMLWarning",t,i,n)}},Qw=(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
+ `}Nf.stringifyDocument=gN});var Br=C(kf=>{"use strict";var wN=kr(),_i=Jn(),_e=L(),yN=Tt(),NN=Ct(),bN=Ks(),kN=bf(),Xs=qn(),SN=ts(),EN=Sr(),Qs=es(),Zs=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,_e.NODE_TYPE,{value:_e.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 Qs.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,{[_e.NODE_TYPE]:{value:_e.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=_e.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ti(this.contents)&&this.contents.add(t)}addIn(t,i){Ti(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Xs.anchorNames(this);t.anchor=!i||r.has(i)?Xs.findNewAnchor(i||"a",r):i}return new wN.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,b=i.filter(m).map(String);b.length>0&&(i=i.concat(b)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=Xs.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=EN.createNode(t,u,v);return s&&_e.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new yN.Pair(n,a)}delete(t){return Ti(this.contents)?this.contents.delete(t):!1}deleteIn(t){return _i.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ti(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return _e.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return _i.isEmptyPath(t)?!i&&_e.isScalar(this.contents)?this.contents.value:this.contents:_e.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return _e.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return _i.isEmptyPath(t)?this.contents!==void 0:_e.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=_i.collectionFromPath(this.schema,[t],i):Ti(this.contents)&&this.contents.set(t,i)}setIn(t,i){_i.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=_i.collectionFromPath(this.schema,Array.from(t),i):Ti(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 Qs.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 Qs.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 bN.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=NN.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"?SN.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 kN.stringifyDocument(this,t)}};function Ti(e){if(_e.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}kf.Document=Zs});var Mr=C(Lr=>{"use strict";var Fr=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},ec=class extends Fr{constructor(t,i,r){super("YAMLParseError",t,i,r)}},tc=class extends Fr{constructor(t,i,r){super("YAMLWarning",t,i,r)}},PN=(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
- `}};un.YAMLError=ln;un.YAMLParseError=Ns;un.YAMLWarning=bs;un.prettifyError=Qw});var fn=R(Ed=>{"use strict";function Zw(e,{flow:t,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,m=!1,h=null,g=null,S=null,N=null,k=null,b=null,C=null;for(let v of e)switch(m&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&a(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&v.type!=="comment"&&v.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),v.type){case"space":!t&&(i!=="doc-start"||n?.type!=="flow-collection")&&v.source.includes(" ")&&(h=v),u=!0;break;case"comment":{u||a(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=v.source.substring(1)||" ";d?d+=f+E:d=E,f="",l=!1;break}case"newline":l?d?d+=v.source:(!b||i!=="seq-item-ind")&&(c=!0):f+=v.source,l=!0,p=!0,(g||S)&&(N=v),u=!0;break;case"anchor":g&&a(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&a(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=v,C??(C=v.offset),l=!1,u=!1,m=!0;break;case"tag":{S&&a(v,"MULTIPLE_TAGS","A node can have at most one tag"),S=v,C??(C=v.offset),l=!1,u=!1,m=!0;break}case i:(g||S)&&a(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),b&&a(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${t??"collection"}`),b=v,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(v,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=v,l=!1,u=!1;break}default:a(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),l=!1,u=!1}let y=e[e.length-1],w=y?y.offset+y.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:k,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:S,newlineAfterProp:N,end:w,start:C??w}}Ed.resolveProps=Zw});var Gr=R(Cd=>{"use strict";function ks(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(ks(t.key)||ks(t.value))return!0}return!1;default:return!0}}Cd.containsNewline=ks});var Ss=R(Rd=>{"use strict";var ey=Gr();function ty(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&ey.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Rd.flowIndentCheck=ty});var Es=R(Ad=>{"use strict";var Pd=D();function iy(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||Pd.isScalar(a)&&Pd.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Ad.mapIncludes=iy});var Od=R(jd=>{"use strict";var xd=lt(),ny=dt(),Td=fn(),ry=Gr(),Id=Ss(),ay=Es(),_d="All mapping items must start at the same column";function oy({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??ny.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:d,key:f,sep:p,value:m}=u,h=Td.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),g=!h.found;if(g){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&r(c,"BAD_INDENT",_d)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||ry.containsNewline(f))&&r(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&r(c,"BAD_INDENT",_d);i.atKey=!0;let S=h.end,N=f?e(i,f,h,r):t(i,S,d,null,h,r);i.schema.compat&&Id.flowIndentCheck(n.indent,f,r),i.atKey=!1,ay.mapIncludes(i,s.items,N)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let k=Td.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:N.range[2],onError:r,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){g&&(m?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<k.found.offset-1024&&r(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=m?e(i,m,k,r):t(i,c,p,null,k,r);i.schema.compat&&Id.flowIndentCheck(n.indent,m,r),c=b.range[2];let C=new xd.Pair(N,b);i.options.keepSourceTokens&&(C.srcToken=u),s.items.push(C)}else{g&&r(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(N.comment?N.comment+=`
68
- `+k.comment:N.comment=k.comment);let b=new xd.Pair(N);i.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}jd.resolveBlockMap=oy});var Hd=R($d=>{"use strict";var sy=ft(),cy=fn(),ly=Ss();function uy({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??sy.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:d}of n.items){let f=cy.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,r):t(i,f.end,u,null,f,r);i.schema.compat&&ly.flowIndentCheck(n.indent,d,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}$d.resolveBlockSeq=uy});var hi=R(Fd=>{"use strict";function dy(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}}Fd.resolveEnd=dy});var Bd=R(Ld=>{"use strict";var fy=D(),hy=lt(),Dd=dt(),py=ft(),my=hi(),Md=fn(),vy=Gr(),gy=Es(),Cs="Block collections are not allowed within flow collections",Rs=e=>e&&(e.type==="block-map"||e.type==="block-seq");function wy({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Dd.YAMLMap:py.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let S=n.items[g],{start:N,key:k,sep:b,value:C}=S,y=Md.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:k??b?.[0],offset:d,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!y.found){if(!y.anchor&&!y.tag&&!b&&!C){g===0&&y.comma?r(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<n.items.length-1&&r(y.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),y.comment&&(l.comment?l.comment+=`
69
- `+y.comment:l.comment=y.comment),d=y.end;continue}!o&&i.options.strict&&vy.containsNewline(k)&&r(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)y.comma&&r(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(y.comma||r(y.start,"MISSING_CHAR",`Missing , between ${s} items`),y.comment){let w="";e:for(let v of N)switch(v.type){case"comma":case"space":break;case"comment":w=v.source.substring(1);break e;default:break e}if(w){let v=l.items[l.items.length-1];fy.isPair(v)&&(v=v.value??v.key),v.comment?v.comment+=`
70
- `+w:v.comment=w,y.comment=y.comment.substring(w.length+1)}}if(!o&&!b&&!y.found){let w=C?e(i,C,y,r):t(i,y.end,b,null,y,r);l.items.push(w),d=w.range[2],Rs(C)&&r(w.range,"BLOCK_IN_FLOW",Cs)}else{i.atKey=!0;let w=y.end,v=k?e(i,k,y,r):t(i,w,N,null,y,r);Rs(k)&&r(v.range,"BLOCK_IN_FLOW",Cs),i.atKey=!1;let E=Md.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:C,offset:v.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(E.found){if(!o&&!y.found&&i.options.strict){if(b)for(let L of b){if(L===E.found)break;if(L.type==="newline"){r(L,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}y.start<E.found.offset-1024&&r(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?r(C,"MISSING_CHAR",`Missing space after : in ${s}`):r(E.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let I=C?e(i,C,E,r):E.found?t(i,E.end,b,null,E,r):null;I?Rs(C)&&r(I.range,"BLOCK_IN_FLOW",Cs):E.comment&&(v.comment?v.comment+=`
71
- `+E.comment:v.comment=E.comment);let J=new hy.Pair(v,I);if(i.options.keepSourceTokens&&(J.srcToken=S),o){let L=l;gy.mapIncludes(i,L.items,v)&&r(w,"DUPLICATE_KEY","Map keys must be unique"),L.items.push(J)}else{let L=new Dd.YAMLMap(i.schema);L.flow=!0,L.items.push(J);let W=(I??v).range;L.range=[v.range[0],W[1],W[2]],l.items.push(L)}d=I?I.range[2]:E.end}}let f=o?"}":"]",[p,...m]=n.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let g=s[0].toUpperCase()+s.substring(1),S=u?`${g} must end with a ${f}`:`${g} in block collection must be sufficiently indented and end with a ${f}`;r(d,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let g=my.resolveEnd(m,h,i.options.strict,r);g.comment&&(l.comment?l.comment+=`
72
- `+g.comment:l.comment=g.comment),l.range=[n.offset,h,g.offset]}else l.range=[n.offset,h,h];return l}Ld.resolveFlowCollection=wy});var Vd=R(qd=>{"use strict";var yy=D(),Ny=te(),by=dt(),ky=ft(),Sy=Od(),Ey=Hd(),Cy=Bd();function Ps(e,t,i,n,r,a){let o=i.type==="block-map"?Sy.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?Ey.resolveBlockSeq(e,t,i,n,a):Cy.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 Ry(e,t,i,n,r){let a=n.tag,o=a?t.directives.tagName(a.source,f=>r(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!p||p.offset<m.offset)&&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===by.YAMLMap.tagName&&s==="map"||o===ky.YAMLSeq.tagName&&s==="seq")return Ps(e,t,i,r,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?r(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):r(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ps(e,t,i,r,o)}let l=Ps(e,t,i,r,o,c),u=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=yy.isNode(u)?u:new Ny.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}qd.composeCollection=Ry});var xs=R(Wd=>{"use strict";var As=te();function Py(e,t,i){let n=t.offset,r=Ay(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?As.Scalar.BLOCK_FOLDED:As.Scalar.BLOCK_LITERAL,o=t.source?xy(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let g=o[h][1];if(g===""||g==="\r")s=h;else break}if(s===0){let h=r.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",g=n+r.length;return t.source&&(g+=t.source.length),{value:h,type:a,comment:r.comment,range:[n,g,g]}}let c=t.indent+r.indent,l=t.offset+r.length,u=0;for(let h=0;h<s;++h){let[g,S]=o[h];if(S===""||S==="\r")r.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&i(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=g.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+S.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
74
- `;for(let h=u;h<s;++h){let[g,S]=o[h];l+=g.length+S.length+1;let N=S[S.length-1]==="\r";if(N&&(S=S.slice(0,-1)),S&&g.length<c){let b=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(N?2:1),"BAD_INDENT",b),g=""}a===As.Scalar.BLOCK_LITERAL?(d+=f+g.slice(c)+S,f=`
75
- `):g.length>c||S[0]===" "?(f===" "?f=`
76
- `:!p&&f===`
65
+ `}};Lr.YAMLError=Fr;Lr.YAMLParseError=ec;Lr.YAMLWarning=tc;Lr.prettifyError=PN});var qr=C(Sf=>{"use strict";function xN(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,v=!1,p=null,m=null,b=null,N=null,P=null,k=null,E=null;for(let w of e)switch(v&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&a(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),p&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(p=w),u=!0;break;case"comment":{u||a(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let g=w.source.substring(1)||" ";d?d+=f+g:d=g,f="",l=!1;break}case"newline":l?d?d+=w.source:(!k||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,h=!0,(m||b)&&(N=w),u=!0;break;case"anchor":m&&a(w,"MULTIPLE_ANCHORS","A node can have at most one anchor"),w.source.endsWith(":")&&a(w.offset+w.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=w,E??(E=w.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),b=w,E??(E=w.offset),l=!1,u=!1,v=!0;break}case i:(m||b)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),k&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),k=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){P&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),P=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let y=e[e.length-1],x=y?y.offset+y.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"),p&&(l&&p.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:P,found:k,spaceBefore:c,comment:d,hasNewline:h,anchor:m,tag:b,newlineAfterProp:N,end:x,start:E??x}}Sf.resolveProps=xN});var Ca=C(Ef=>{"use strict";function ic(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(ic(t.key)||ic(t.value))return!0}return!1;default:return!0}}Ef.containsNewline=ic});var rc=C(Pf=>{"use strict";var CN=Ca();function RN(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&CN.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Pf.flowIndentCheck=RN});var nc=C(Cf=>{"use strict";var xf=L();function AN(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||xf.isScalar(a)&&xf.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Cf.mapIncludes=AN});var jf=C(If=>{"use strict";var Rf=Tt(),_N=jt(),Af=qr(),TN=Ca(),_f=rc(),IN=nc(),Tf="All mapping items must start at the same column";function jN({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??_N.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:h,value:v}=u,p=Af.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Tf)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
67
+ `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||TN.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==r.indent&&n(c,"BAD_INDENT",Tf);i.atKey=!0;let b=p.end,N=f?e(i,f,p,n):t(i,b,d,null,p,n);i.schema.compat&&_f.flowIndentCheck(r.indent,f,n),i.atKey=!1,IN.mapIncludes(i,s.items,N)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let P=Af.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=P.end,P.found){m&&(v?.type==="block-map"&&!P.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&p.start<P.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,P,n):t(i,c,h,null,P,n);i.schema.compat&&_f.flowIndentCheck(r.indent,v,n),c=k.range[2];let E=new Rf.Pair(N,k);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),P.comment&&(N.comment?N.comment+=`
68
+ `+P.comment:N.comment=P.comment);let k=new Rf.Pair(N);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}If.resolveBlockMap=jN});var Of=C($f=>{"use strict";var $N=$t(),ON=qr(),HN=rc();function DN({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??$N.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:u,value:d}of r.items){let f=ON.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&HN.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}$f.resolveBlockSeq=DN});var Ii=C(Hf=>{"use strict";function BN(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 u=c.substring(1)||" ";n?n+=o+u:n=u,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}}Hf.resolveEnd=BN});var Lf=C(Ff=>{"use strict";var FN=L(),LN=Tt(),Df=jt(),MN=$t(),qN=Ii(),Bf=qr(),VN=Ca(),WN=nc(),ac="Block collections are not allowed within flow collections",oc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function zN({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Df.YAMLMap:MN.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let b=r.items[m],{start:N,key:P,sep:k,value:E}=b,y=Bf.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:P??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!y.found){if(!y.anchor&&!y.tag&&!k&&!E){m===0&&y.comma?n(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(y.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),y.comment&&(l.comment?l.comment+=`
69
+ `+y.comment:l.comment=y.comment),d=y.end;continue}!o&&i.options.strict&&VN.containsNewline(P)&&n(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)y.comma&&n(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(y.comma||n(y.start,"MISSING_CHAR",`Missing , between ${s} items`),y.comment){let x="";e:for(let w of N)switch(w.type){case"comma":case"space":break;case"comment":x=w.source.substring(1);break e;default:break e}if(x){let w=l.items[l.items.length-1];FN.isPair(w)&&(w=w.value??w.key),w.comment?w.comment+=`
70
+ `+x:w.comment=x,y.comment=y.comment.substring(x.length+1)}}if(!o&&!k&&!y.found){let x=E?e(i,E,y,n):t(i,y.end,k,null,y,n);l.items.push(x),d=x.range[2],oc(E)&&n(x.range,"BLOCK_IN_FLOW",ac)}else{i.atKey=!0;let x=y.end,w=P?e(i,P,y,n):t(i,x,N,null,y,n);oc(P)&&n(w.range,"BLOCK_IN_FLOW",ac),i.atKey=!1;let g=Bf.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:E,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(g.found){if(!o&&!y.found&&i.options.strict){if(k)for(let I of k){if(I===g.found)break;if(I.type==="newline"){n(I,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}y.start<g.found.offset-1024&&n(g.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(g.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let S=E?e(i,E,g,n):g.found?t(i,g.end,k,null,g,n):null;S?oc(E)&&n(S.range,"BLOCK_IN_FLOW",ac):g.comment&&(w.comment?w.comment+=`
71
+ `+g.comment:w.comment=g.comment);let D=new LN.Pair(w,S);if(i.options.keepSourceTokens&&(D.srcToken=b),o){let I=l;WN.mapIncludes(i,I.items,w)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),I.items.push(D)}else{let I=new Df.YAMLMap(i.schema);I.flow=!0,I.items.push(D);let de=(S??w).range;I.range=[w.range[0],de[1],de[2]],l.items.push(I)}d=S?S.range[2]:g.end}}let f=o?"}":"]",[h,...v]=r.end,p=d;if(h?.source===f)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),b=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",b),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=qN.resolveEnd(v,p,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
+ `+m.comment:l.comment=m.comment),l.range=[r.offset,p,m.offset]}else l.range=[r.offset,p,p];return l}Ff.resolveFlowCollection=zN});var qf=C(Mf=>{"use strict";var JN=L(),GN=ie(),UN=jt(),KN=$t(),YN=jf(),XN=Of(),QN=Lf();function sc(e,t,i,r,n,a){let o=i.type==="block-map"?YN.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?XN.resolveBlockSeq(e,t,i,r,a):QN.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 ZN(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.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===UN.YAMLMap.tagName&&s==="map"||o===KN.YAMLSeq.tagName&&s==="seq")return sc(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),sc(e,t,i,n,o)}let l=sc(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=JN.isNode(u)?u:new GN.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Mf.composeCollection=ZN});var lc=C(Vf=>{"use strict";var cc=ie();function eb(e,t,i){let r=t.offset,n=tb(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?cc.Scalar.BLOCK_FOLDED:cc.Scalar.BLOCK_LITERAL,o=t.source?ib(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:p,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let p=0;p<s;++p){let[m,b]=o[p];if(b===""||b==="\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),u=p,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+b.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let d="",f="",h=!1;for(let p=0;p<u;++p)d+=o[p][0].slice(c)+`
74
+ `;for(let p=u;p<s;++p){let[m,b]=o[p];l+=m.length+b.length+1;let N=b[b.length-1]==="\r";if(N&&(b=b.slice(0,-1)),b&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(N?2:1),"BAD_INDENT",k),m=""}a===cc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+b,f=`
75
+ `):m.length>c||b[0]===" "?(f===" "?f=`
76
+ `:!h&&f===`
77
77
  `&&(f=`
78
78
 
79
- `),d+=f+g.slice(c)+S,f=`
80
- `,p=!0):S===""?f===`
79
+ `),d+=f+m.slice(c)+b,f=`
80
+ `,h=!0):b===""?f===`
81
81
  `?d+=`
82
82
  `:f=`
83
- `:(d+=f+S,f=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
84
- `+o[h][0].slice(c);d[d.length-1]!==`
83
+ `:(d+=f+b,f=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let p=s;p<o.length;++p)d+=`
84
+ `+o[p][0].slice(c);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let m=n+r.length+t.source.length;return{value:d,type:a,comment:r.comment,range:[n,m,m]}}function Ay({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 f=1;f<r.length;++f){let p=r[f];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=e+f)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,u="",d=r.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function xy(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}Wd.resolveBlockScalar=Py});var Is=R(Jd=>{"use strict";var Ts=te(),Ty=hi();function Iy(e,t,i){let{offset:n,type:r,source:a,end:o}=e,s,c,l=(f,p,m)=>i(n+f,p,m);switch(r){case"scalar":s=Ts.Scalar.PLAIN,c=_y(a,l);break;case"single-quoted-scalar":s=Ts.Scalar.QUOTE_SINGLE,c=jy(a,l);break;case"double-quoted-scalar":s=Ts.Scalar.QUOTE_DOUBLE,c=Oy(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,d=Ty.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function _y(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}`),zd(e)}function jy(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),zd(e.slice(1,-1)).replace(/''/g,"'")}function zd(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function tb({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 f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function ib(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}Vf.resolveBlockScalar=eb});var dc=C(zf=>{"use strict";var uc=ie(),rb=Ii();function nb(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=uc.Scalar.PLAIN,c=ab(a,l);break;case"single-quoted-scalar":s=uc.Scalar.QUOTE_SINGLE,c=ob(a,l);break;case"double-quoted-scalar":s=uc.Scalar.QUOTE_DOUBLE,c=sb(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 u=r+a.length,d=rb.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function ab(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}`),Wf(e)}function ob(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Wf(e.slice(1,-1)).replace(/''/g,"'")}function Wf(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 Oy(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}=$y(e,n);i+=a,n=o}else if(r==="\\"){let a=e[++n],o=Hy[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+=Fy(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 $y(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 sb(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}=cb(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=lb[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+=ub(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 cb(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 Hy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Fy(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}}Jd.resolveFlowScalar=Iy});var Kd=R(Ud=>{"use strict";var Ot=D(),Gd=te(),Dy=xs(),My=Is();function Ly(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?Dy.resolveBlockScalar(e,t,n):My.resolveFlowScalar(t,e.options.strict,n),c=i?e.directives.tagName(i.source,d=>n(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Ot.SCALAR]:c?l=By(e.schema,r,c,i,n):t.type==="scalar"?l=qy(e,r,t,n):l=e.schema[Ot.SCALAR];let u;try{let d=l.resolve(r,f=>n(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Ot.isScalar(d)?d:new Gd.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(i??t,"TAG_RESOLVE_FAILED",f),u=new Gd.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 By(e,t,i,n,r){if(i==="!")return e[Ot.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[Ot.SCALAR])}function qy({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[Ot.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[Ot.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}Ud.composeScalar=Ly});var Xd=R(Yd=>{"use strict";function Vy(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}Yd.emptyScalarPosition=Vy});var ef=R(js=>{"use strict";var Wy=zi(),zy=D(),Jy=Vd(),Qd=Kd(),Gy=hi(),Uy=Xd(),Ky={composeNode:Zd,composeEmptyNode:_s};function Zd(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=Yy(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=Qd.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Jy.composeCollection(Ky,e,t,i,n),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=_s(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&&(!zy.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 _s(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Uy.emptyScalarPosition(t,i,n),indent:-1,source:""},d=Qd.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Yy({options:e},{offset:t,source:i,end:n},r){let a=new Wy.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=Gy.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}js.composeEmptyNode=_s;js.composeNode=Zd});var rf=R(nf=>{"use strict";var Xy=cn(),tf=ef(),Qy=hi(),Zy=fn();function eN(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new Xy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Zy.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?tf.composeNode(l,r,u,o):tf.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Qy.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}nf.composeDoc=eN});var $s=R(sf=>{"use strict";var tN=nr("process"),iN=No(),nN=cn(),hn=dn(),af=D(),rN=rf(),aN=hi();function pn(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 of(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 lb={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ub(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}}zf.resolveFlowScalar=nb});var Uf=C(Gf=>{"use strict";var ui=L(),Jf=ie(),db=lc(),fb=dc();function pb(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?db.resolveBlockScalar(e,t,r):fb.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ui.SCALAR]:c?l=hb(e.schema,n,c,i,r):t.type==="scalar"?l=mb(e,n,t,r):l=e.schema[ui.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=ui.isScalar(d)?d:new Jf.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Jf.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function hb(e,t,i,r,n){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):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[ui.SCALAR])}function mb({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[ui.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??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(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Gf.composeScalar=pb});var Yf=C(Kf=>{"use strict";function vb(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}Kf.emptyScalarPosition=vb});var Zf=C(pc=>{"use strict";var gb=kr(),wb=L(),yb=qf(),Xf=Uf(),Nb=Ii(),bb=Yf(),kb={composeNode:Qf,composeEmptyNode:fc};function Qf(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=Sb(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=Xf.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=yb.composeCollection(kb,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=fc(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&&(!wb.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&&u&&(l.srcToken=t),l}function fc(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:bb.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Xf.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Sb({options:e},{offset:t,source:i,end:r},n){let a=new gb.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=Nb.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}pc.composeEmptyNode=fc;pc.composeNode=Qf});var ip=C(tp=>{"use strict";var Eb=Br(),ep=Zf(),Pb=Ii(),xb=qr();function Cb(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Eb.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=xb.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?ep.composeNode(l,n,u,o):ep.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Pb.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}tp.composeDoc=Cb});var mc=C(ap=>{"use strict";var Rb=On("process"),Ab=es(),_b=Br(),Vr=Mr(),rp=L(),Tb=ip(),Ib=Ii();function Wr(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 np(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 Os=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=pn(i);a?this.warnings.push(new hn.YAMLWarning(o,n,r)):this.errors.push(new hn.YAMLParseError(o,n,r))},this.directives=new iN.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=of(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(af.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];af.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:of(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(tN.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,n,r)=>{let a=pn(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=rN.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 hn.YAMLParseError(pn(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 hn.YAMLParseError(pn(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=aN.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 hn.YAMLParseError(pn(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 nN.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}}};sf.Composer=Os});var uf=R(Ur=>{"use strict";var oN=xs(),sN=Is(),cN=dn(),cf=Yi();function lN(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 cN.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return sN.resolveFlowScalar(e,t,n);case"block-scalar":return oN.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function uN(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=cf.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 hc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Wr(i);a?this.warnings.push(new Vr.YAMLWarning(o,r,n)):this.errors.push(new Vr.YAMLParseError(o,r,n))},this.directives=new Ab.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=np(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(rp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];rp.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:np(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(Rb.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Wr(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=Tb.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 Vr.YAMLParseError(Wr(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 Vr.YAMLParseError(Wr(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Ib.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 Vr.YAMLParseError(Wr(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 _b.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}}};ap.Composer=hc});var cp=C(Ra=>{"use strict";var jb=lc(),$b=dc(),Ob=Mr(),op=Cr();function Hb(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 Ob.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return $b.resolveFlowScalar(e,t,r);case"block-scalar":return jb.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Db(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=op.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
111
  `),u=s.substring(0,l),d=s.substring(l+1)+`
112
- `,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return lf(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
113
- `}),{type:"block-scalar",offset:a,indent:n,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function dN(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=cf.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">":fN(e,c);break;case'"':Hs(e,c,"double-quoted-scalar");break;case"'":Hs(e,c,"single-quoted-scalar");break;default:Hs(e,c,"scalar")}}function fN(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}];lf(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 lf(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 Hs(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})}}}Ur.createScalarToken=uN;Ur.resolveAsScalar=lN;Ur.setScalarValue=dN});var ff=R(df=>{"use strict";var hN=e=>"type"in e?Yr(e):Kr(e);function Yr(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Yr(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Kr(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Kr(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Kr(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 Kr({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=Yr(t)),i)for(let a of i)r+=a.source;return n&&(r+=Yr(n)),r}df.stringify=hN});var vf=R(mf=>{"use strict";var Fs=Symbol("break visit"),pN=Symbol("skip children"),hf=Symbol("remove item");function $t(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),pf(Object.freeze([]),e,t)}$t.BREAK=Fs;$t.SKIP=pN;$t.REMOVE=hf;$t.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};$t.parentCollection=(e,t)=>{let i=$t.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 pf(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=pf(Object.freeze(e.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Fs)return Fs;s===hf&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}mf.visit=$t});var Xr=R(de=>{"use strict";var Ds=uf(),mN=ff(),vN=vf(),Ms="\uFEFF",Ls="",Bs="",qs="",gN=e=>!!e&&"items"in e,wN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function yN(e){switch(e){case Ms:return"<BOM>";case Ls:return"<DOC>";case Bs:return"<FLOW_END>";case qs:return"<SCALAR>";default:return JSON.stringify(e)}}function NN(e){switch(e){case Ms:return"byte-order-mark";case Ls:return"doc-mode";case Bs:return"flow-error-end";case qs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return sp(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}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 Bb(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=op.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">":Fb(e,c);break;case'"':vc(e,c,"double-quoted-scalar");break;case"'":vc(e,c,"single-quoted-scalar");break;default:vc(e,c,"scalar")}}function Fb(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}];sp(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 sp(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 vc(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})}}}Ra.createScalarToken=Db;Ra.resolveAsScalar=Hb;Ra.setScalarValue=Bb});var up=C(lp=>{"use strict";var Lb=e=>"type"in e?_a(e):Aa(e);function _a(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=_a(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Aa(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Aa(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Aa(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 Aa({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=_a(t)),i)for(let a of i)n+=a.source;return r&&(n+=_a(r)),n}lp.stringify=Lb});var hp=C(pp=>{"use strict";var gc=Symbol("break visit"),Mb=Symbol("skip children"),dp=Symbol("remove item");function di(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),fp(Object.freeze([]),e,t)}di.BREAK=gc;di.SKIP=Mb;di.REMOVE=dp;di.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};di.parentCollection=(e,t)=>{let i=di.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 fp(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=fp(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===gc)return gc;s===dp&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}pp.visit=di});var Ta=C(we=>{"use strict";var wc=cp(),qb=up(),Vb=hp(),yc="\uFEFF",Nc="",bc="",kc="",Wb=e=>!!e&&"items"in e,zb=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Jb(e){switch(e){case yc:return"<BOM>";case Nc:return"<DOC>";case bc:return"<FLOW_END>";case kc:return"<SCALAR>";default:return JSON.stringify(e)}}function Gb(e){switch(e){case yc:return"byte-order-mark";case Nc:return"doc-mode";case bc:return"flow-error-end";case kc: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}de.createScalarToken=Ds.createScalarToken;de.resolveAsScalar=Ds.resolveAsScalar;de.setScalarValue=Ds.setScalarValue;de.stringify=mN.stringify;de.visit=vN.visit;de.BOM=Ms;de.DOCUMENT=Ls;de.FLOW_END=Bs;de.SCALAR=qs;de.isCollection=gN;de.isScalar=wN;de.prettyToken=yN;de.tokenType=NN});var zs=R(wf=>{"use strict";var mn=Xr();function xe(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var gf=new Set("0123456789ABCDEFabcdef"),bN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Qr=new Set(",[]{}"),kN=new Set(` ,[]{}
121
- \r `),Vs=e=>!e||kN.has(e),Ws=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}we.createScalarToken=wc.createScalarToken;we.resolveAsScalar=wc.resolveAsScalar;we.setScalarValue=wc.setScalarValue;we.stringify=qb.stringify;we.visit=Vb.visit;we.BOM=yc;we.DOCUMENT=Nc;we.FLOW_END=bc;we.SCALAR=kc;we.isCollection=Wb;we.isScalar=zb;we.prettyToken=Jb;we.tokenType=Gb});var Pc=C(vp=>{"use strict";var zr=Ta();function qe(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var mp=new Set("0123456789ABCDEFabcdef"),Ub=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ia=new Set(",[]{}"),Kb=new Set(` ,[]{}
121
+ \r `),Sc=e=>!e||Kb.has(e),Ec=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==="...")&&xe(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]===mn.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 mn.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==="...")&&xe(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&&!xe(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===":")&&xe(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(Vs),"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("..."))&&xe(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield mn.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(Vs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||xe(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=>xe(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==="...")&&qe(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]===zr.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 zr.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==="...")&&qe(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&&!qe(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===":")&&qe(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(Sc),"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("..."))&&qe(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield zr.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(Sc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||qe(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=>qe(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 mn.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(xe(a)||t&&Qr.has(a))break;i=n}else if(xe(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&&Qr.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&&Qr.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield mn.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(Vs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(xe(n)||i&&Qr.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(;!xe(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(bN.has(i))i=this.buffer[++t];else if(i==="%"&&gf.has(this.buffer[t+1])&&gf.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 zr.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(qe(a)||t&&Ia.has(a))break;i=r}else if(qe(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&&Ia.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&&Ia.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield zr.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(Sc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(qe(r)||i&&Ia.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(;!qe(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(Ub.has(i))i=this.buffer[++t];else if(i==="%"&&mp.has(this.buffer[t+1])&&mp.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)}};wf.Lexer=Ws});var Gs=R(yf=>{"use strict";var Js=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}}}};yf.LineCounter=Js});var Ks=R(Ef=>{"use strict";var SN=nr("process"),Nf=Xr(),EN=zs();function ht(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function bf(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 Sf(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 Zr(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 pi(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 ea(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 kf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!ht(t.start,"explicit-key-ind")&&!ht(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Sf(t.value)?t.value.end?ea(t.value.end,t.sep):t.value.end=t.sep:ea(t.start,t.sep),delete t.sep)}var Us=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 EN.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,SN.env.LOG_TOKENS&&console.log("|",Nf.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Nf.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"&&kf(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&&bf(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":{bf(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=Zr(this.peek(2)),n=pi(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)}};vp.Lexer=Ec});var Cc=C(gp=>{"use strict";var xc=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}}}};gp.LineCounter=xc});var Ac=C(kp=>{"use strict";var Yb=On("process"),wp=Ta(),Xb=Pc();function Ot(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function yp(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 bp(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 ja(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 ji(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 $a(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 Np(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ot(t.start,"explicit-key-ind")&&!Ot(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,bp(t.value)?t.value.end?$a(t.value.end,t.sep):t.value.end=t.sep:$a(t.start,t.sep),delete t.sep)}var Rc=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 Xb.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,Yb.env.LOG_TOKENS&&console.log("|",wp.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=wp.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"&&Np(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&&yp(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":{yp(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=ja(this.peek(2)),r=ji(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)){ea(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(ht(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(Sf(i.key)&&!ht(i.sep,"newline")){let o=pi(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(ht(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=pi(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]}):ht(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&&!ht(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)){ea(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||ht(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=Zr(n),a=pi(r);kf(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)){$a(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(Ot(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(bp(i.key)&&!Ot(i.sep,"newline")){let o=ji(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(Ot(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=ji(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]}):Ot(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&&!Ot(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)){$a(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||Ot(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=ja(r),a=ji(n);Np(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=Zr(t),n=pi(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=Zr(t),n=pi(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())}}};Ef.Parser=Us});var xf=R(gn=>{"use strict";var Cf=$s(),CN=cn(),vn=dn(),RN=jo(),PN=D(),AN=Gs(),Rf=Ks();function Pf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new AN.LineCounter||null,prettyErrors:t}}function xN(e,t={}){let{lineCounter:i,prettyErrors:n}=Pf(t),r=new Rf.Parser(i?.addNewLine),a=new Cf.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(vn.prettifyError(e,i)),s.warnings.forEach(vn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Af(e,t={}){let{lineCounter:i,prettyErrors:n}=Pf(t),r=new Rf.Parser(i?.addNewLine),a=new Cf.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 vn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(vn.prettifyError(e,i)),o.warnings.forEach(vn.prettifyError(e,i))),o}function TN(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Af(e,i);if(!r)return null;if(r.warnings.forEach(a=>RN.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 IN(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 PN.isDocument(e)&&!n?e.toString(i):new CN.Document(e,n,i).toString(i)}gn.parse=TN;gn.parseAllDocuments=xN;gn.parseDocument=Af;gn.stringify=IN});var ia=R(B=>{"use strict";var _N=$s(),jN=cn(),ON=ms(),Ys=dn(),$N=zi(),pt=D(),HN=lt(),FN=te(),DN=dt(),MN=ft(),LN=Xr(),BN=zs(),qN=Gs(),VN=Ks(),ta=xf(),Tf=Bi();B.Composer=_N.Composer;B.Document=jN.Document;B.Schema=ON.Schema;B.YAMLError=Ys.YAMLError;B.YAMLParseError=Ys.YAMLParseError;B.YAMLWarning=Ys.YAMLWarning;B.Alias=$N.Alias;B.isAlias=pt.isAlias;B.isCollection=pt.isCollection;B.isDocument=pt.isDocument;B.isMap=pt.isMap;B.isNode=pt.isNode;B.isPair=pt.isPair;B.isScalar=pt.isScalar;B.isSeq=pt.isSeq;B.Pair=HN.Pair;B.Scalar=FN.Scalar;B.YAMLMap=DN.YAMLMap;B.YAMLSeq=MN.YAMLSeq;B.CST=LN;B.Lexer=BN.Lexer;B.LineCounter=qN.LineCounter;B.Parser=VN.Parser;B.parse=ta.parse;B.parseAllDocuments=ta.parseAllDocuments;B.parseDocument=ta.parseDocument;B.stringify=ta.stringify;B.visit=Tf.visit;B.visitAsync=Tf.visitAsync});import{promises as uP}from"fs";import{promises as Mc}from"fs";import Lh from"path";var Hc=vo(ia(),1);import{promises as jh}from"fs";import kt from"path";import{createHash as GN}from"node:crypto";import{promises as Te}from"node:fs";import ke from"node:path";import{TextDecoder as UN}from"node:util";import Xs from"path";var WN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),zN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function JN(e){return e.toLowerCase().startsWith(".env")}function Ve(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>JN(n))?"environment-file":i.some(n=>zN.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>WN.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Qs(e,t){let i=Ve(t);if(i)return i;let n=Xs.resolve(e.projectRoot,...t.split("/")),r=Xs.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Xs.resolve(e.configFile)?"native-runtime":null}function mt(e){return e!==0&&e!==0n&&e!=="0"}function fe(e,t){return mt(e.dev)&&mt(t.dev)&&mt(e.ino)&&mt(t.ino)}function q(e,t){let i=mt(e.dev)&&mt(t.dev);if(i&&e.dev!==t.dev)return!1;let n=mt(e.ino)&&mt(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var wn=1024*1024;function Zs(e,t){let i=ke.relative(e,t);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function KN(e){let t=ke.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})||ke.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=Ve(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 YN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function XN(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function na(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return fe(i,n)?q(i,n):q(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function If(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function QN(e,t){let i=ke.resolve(e),n=ke.resolve(t);if(!Zs(i,n))throw new Error("Native artifact path is outside its root");let r=[await If(i)],a=i;for(let o of ke.relative(i,n).split(ke.sep).filter(Boolean)){a=ke.join(a,o);let s=await If(a);if(!Zs(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function _f(e){for(let t of e){let i=await Te.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!XN(t,i)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function le(e){let t=KN(e.ref),i=YN(e.maxBytes??wn),n=ke.resolve(e.root,...t.split("/")),r=await QN(e.root,ke.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Te.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 Te.realpath(n);if(!Zs(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Te.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await _f(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!na(a,c)||!na(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-f,b=await s.read(p,0,Math.min(p.length,k),null);if(b.bytesRead===0)break;if(f+=b.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await _f(r),!h.isFile()||h.isSymbolicLink()||g!==o||!na(c,m)||!na(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),N;try{N=new UN("utf-8",{fatal:!0}).decode(S)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:GN("sha256").update(S).digest("hex"),text:N}}finally{await s.close()}}var tc=vo(ia(),1);import ra from"path";var Nn=64*1024,aa=1024,oa=64,ic=5,ZN=[".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/**"],he={include:["**/*"],exclude:[...ZN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function eb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||ra.posix.isAbsolute(i)||ra.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 Ht(e){let t=eb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Of(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 nc(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||ra.posix.isAbsolute(n)||ra.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 yn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function $f(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 sa(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>aa)throw new Error(`${t} exceeds ${aa} 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>oa)throw new Error(`${t} contains more than ${oa} wildcard tokens`);return e}function jf(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=>sa(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function ec(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 tb(e){if(e===void 0)return{...he,include:[...he.include],exclude:[...he.exclude]};let t=yn(e,"native.snapshot");return{include:jf(t.include,"native.snapshot.include",he.include),exclude:jf(t.exclude,"native.snapshot.exclude",he.exclude),max_files:ec(t.max_files,he.max_files,"native.snapshot.max_files"),max_total_bytes:ec(t.max_total_bytes,he.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ec(t.max_duration_ms,he.max_duration_ms,"native.snapshot.max_duration_ms")}}function ib(e){if(e===void 0)return;let t=yn(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=yn(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:Ht(n),toArtifactRoot:Ht(r),stage:a,...o?{cleanup:o}:{}}}function nb(e,t={}){let i=yn(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??ic;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=ib(i.pending_root_move);return{artifact_root:Ht(n),language:$f(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:tb(i.snapshot),...s?{pending_root_move:s}:{}}}function rb(e){let t=yn(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:Of(t.artifact_layout),language:$f(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function ab(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function ob(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 bn(e,t={}){let i=(0,tc.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=ab(r.ambient_resume),o=r.native===void 0?void 0:nb(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:rb(r.classic),c=ob(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function ca(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Ht(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:ic,snapshot:{...he,include:[...he.include],exclude:[...he.exclude]}}}}import{createHash as cb}from"crypto";import{promises as da}from"fs";import vt from"path";import{constants as la,promises as Ft}from"fs";var We=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function rc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Hf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function kn(e){return{dev:e.dev,ino:e.ino,birthtime:rc(e)}}function ua(e,t){let i=kn(e),n=kn(t);return fe(i,n)?q(i,n):q(i,n)&&rc(e)===rc(t)&&Hf(e)===Hf(t)&&e.size===t.size}async function mi(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 Ft.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new We("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new We("too-large",`${n} exceeds ${t} bytes`);let o=await Ft.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:kn(a)});let s=process.platform==="win32"?la.O_RDONLY:la.O_RDONLY|la.O_NOFOLLOW|la.O_NONBLOCK,c;try{c=await Ft.open(e,s)}catch(l){throw l.code==="ELOOP"?new We("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Ft.lstat(e,{bigint:r}),Ft.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ua(a,l)||!ua(a,u))throw new We("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:kn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,N),null);if(k===0)break;if(p+=k,p>t)throw new We("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([c.stat({bigint:r}),Ft.lstat(e,{bigint:r}),Ft.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||S!==o||!ua(a,h)||!ua(a,g))throw new We("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:kn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function sb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ac(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}async function Ff(e,t){let i=vt.resolve(e),n=await da.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return da.realpath(i)}async function Df(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 da.lstat(r)}catch(u){if(sb(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 da.realpath(r);if(!ac(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 Sn(e,t,i){let n=nc(t,i.label),r=vt.resolve(e),a=await Ff(r,i.label),o=n.split("/"),s=vt.resolve(r,...o);if(!ac(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Df(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Dt(e,t,i,n){let r=await Sn(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 Ff(r.projectRoot,n.label);return mi(r.target,i,{...n,verify:async(o,s)=>{if(!ac(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Df(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var En=".comet/config.yaml";function lb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function oc(e,t={}){return(await fa(e,t)).document}async function ub(e){try{return(await Dt(e,En,Nn,{label:En})).bytes}catch(t){if(lb(t))return null;throw t}}function db(e){return e?{exists:!0,sha256:cb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fa(e,t={}){let i=await ub(e);return{document:i?bn(i.toString("utf8"),t):null,identity:db(i)}}var Nx=16*1024;import{promises as vi}from"fs";import z from"path";import vb from"os";var pa=".comet/config.yaml";async function lc(e){try{return await vi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gb(e){try{let t=await vi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Cn(e,t){let i=z.relative(e,t);return i===""||!z.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${z.sep}`)}async function Rn(e){let t=[],i=e;for(;!await lc(i);){let r=z.dirname(i);if(r===i)break;t.push(z.basename(i)),i=r}let n=await vi.realpath(i);return z.resolve(n,...t.reverse())}async function Lf(e){try{return(await vi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ma(e){let t=z.resolve(e);try{(await vi.stat(t)).isDirectory()||(t=z.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=z.resolve(vb.homedir());for(;;){if(!(t===n&&i!==n)){let o=z.join(t,...pa.split("/")),s=t===i||await gb(o);if(await lc(o)&&s)return t}if(await lc(z.join(t,".git")))return t;let a=z.dirname(t);if(a===t)return i;t=a}}function va(e){return Ht(e)}async function wb(e,t){let i=va(t),n=z.resolve(e,...i.split("/")),r=await vi.realpath(e),a=await Rn(n);if(!Cn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function uc(e,t){let i=va(t),n=await wb(e,i),r=z.join(n,"comet");if(await Lf(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Rn(n),Rn(r)]);if(!Cn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:z.resolve(e),configFile:z.join(e,...pa.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:z.join(r,"specs"),changesDir:z.join(r,"changes"),archiveDir:z.join(r,"archive"),runtimeDir:z.join(r,"runtime"),locksDir:z.join(r,"runtime","locks"),transactionsDir:z.join(r,"runtime","transactions")}}function V(e,t){return Cn(z.resolve(e),z.resolve(t))}async function G(e,t){let i=z.resolve(e),n=z.resolve(t);if(!Cn(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Lf(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([Rn(i),Rn(n)]);if(!Cn(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var fc=he;var ga=sa;function Nb(e="docs",t="en"){return ca(e,t)}async function Mt(e){let t=(await oc(e))?.config??null;return t?.native?t:null}async function Bf(e){let t=await ma(e.startPath),i=await Mt(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${pa} 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?va(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??Nb(n??"docs"),a=await uc(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{AsyncLocalStorage as bb}from"async_hooks";var Wx=16*1024;var zx=new bb;import{TextDecoder as Ab}from"util";import{createHash as kb}from"node:crypto";import{constants as wa,promises as ge}from"node:fs";import Ie from"node:path";import{TextDecoder as Sb}from"node:util";function Na(e,t){let i=Ie.relative(e,t);return i===""||!Ie.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ie.sep}`)}function qf(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Eb(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ya(e,t){return q({...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 hc(e,t){let i=await ge.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ge.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function pc(e,t,i){let n=Ie.resolve(e),r=Ie.resolve(t);if(!Na(n,r))throw new Error(`${i} is outside its managed root`);let a=[await hc(n,i)],o=n;for(let s of Ie.relative(n,r).split(Ie.sep).filter(Boolean)){await ze(a,i),o=Ie.join(o,s);let c=await hc(o,i);if(!Na(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ze(a,i),a}async function ze(e,t){for(let i of e){let n=await ge.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Eb(i,n)||await ge.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Rb(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 Ye(e){let t=qf(e.maxBytes),i=Ie.resolve(e.file),n=await pc(e.root,Ie.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>hc(Ie.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ze(n,e.label);let a=await ge.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=Cb(a),s=await ge.realpath(i);if(!Na(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Na(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?wa.O_RDONLY:wa.O_RDONLY|wa.O_NOFOLLOW|wa.O_NONBLOCK,l=await ge.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([ge.lstat(i),ge.realpath(i)]);if(await ze(n,e.label),await ze(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ya(o,u)||!ya(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Rb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),ge.lstat(i),ge.realpath(i)]);if(await ze(n,e.label),await ze(r,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!ya(o,m)||!ya(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:kb("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Vf(e){let t=await Ye(e),i;try{i=new Sb("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 Pn(e){let t=await pc(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await ge.readdir(e.directory,{withFileTypes:!0});else{let n=qf(e.maxEntries);i=[];let r=await ge.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 ze(t,e.label),{entries:i,verify:()=>ze(t,e.label)}}async function mc(e){let t=await pc(e.root,e.directory,e.label);return{verify:()=>ze(t,e.label)}}var sT=256*1024,cT=1024*1024,lT=16*1024;var uT=64*1024*1024;var dT=new Ab("utf-8",{fatal:!0});import{createHash as Ca}from"crypto";import{spawn as nh}from"node:child_process";import{promises as X}from"fs";import H from"path";import{createHash as Uf}from"crypto";import{createReadStream as Tb}from"fs";async function vc(e){let t=Uf("sha256");for await(let i of Tb(e))t.update(i);return t.digest("hex")}function U(e){return Uf("sha256").update(e).digest("hex")}var ba={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},kc=1e3,Ib=8*1024*1024,_b=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Ob=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),$b=new Set(["schema","include","exclude","hash"]),Hb=new Set(["provider","gitSelection","physicalSelection","projection"]),Fb=new Set(["provider","selection"]),Db=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Mb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Lb=new Set(["schema","status","before","after"]),Bb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),qb=new Set(["path","hash","size","type","gitObjectId"]),Vb=new Set(["path","size","type","reason"]),Wb=new Set(["ref","hash","count"]),zb=new Set(["change-created","legacy-migration","explicit"]),Jb=new Set(["file","directory","other"]),Gb=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"]),Ra=/^[a-f0-9]{64}$/u,rh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Ub=new Set(["EACCES","EPERM"]),bi=64*1024,Nc=64*1024,Kb=6e4,Yb=1e3,Xb=2,Sc={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Qb={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function ah(e){let t=e.deadlineMs??Kb;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 _e(e){return Math.max(0,e.deadlineAt-Date.now())}function _(e){return _e(e)>=1}function gc(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 yi(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function Zb(e){let t={...Qb,...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 ek(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,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=nh(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),Yb),u.unref()}catch{d(!1)}});for(let s=0;s<Xb;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 Ec(e,t,i,n){let r=_e(e);if(r<1)throw gc();let a=e.gitProcess,o=nh(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)}),d=setTimeout(()=>{c=!0,l=ek(o,a).then(()=>({error:null}),p=>({error:p}))},r);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let m=await l;throw m?.error?gc(m.error):gc()}return{code:p,spawnError:s}});return{child:o,completion:f}}function oh(e){let t={...Sc,...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 ka(e,t,i,n=Nc){let{child:r,completion:a}=Ec(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>=bi)return;let m=bi-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function wc(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function xn(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}=Ec(e,t,i,n.stdin!==void 0),c=[],l=Ca("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),g=!1,S=!1,N=!1,k=b=>{let C=0;for(;C<b.byteLength;){let y=b.indexOf(0,C),w=y<0?b.byteLength:y,v=b.subarray(C,w);if(!g&&v.byteLength>0&&(h.byteLength+v.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),g=!0,S=!0):h=Buffer.concat([h,v])),y<0)break;m+=1,h.byteLength===0&&!g&&(N=!0);let E=h.byteLength+1;!g&&m<=n.maxRecords&&p+E<=n.maxBytes?(c.push(h),p+=E):S=!0,h=Buffer.alloc(0),g=!1,C=y+1}};o.stdout.on("data",b=>{l.update(b),f+=b.byteLength,f>n.maxBytes&&(S=!0);let C=n.outputChunkBytes;if(C===void 0){k(b);return}for(let y=0;y<b.byteLength;y+=C)k(b.subarray(y,Math.min(b.byteLength,y+C)))}),o.stderr.on("data",b=>{if(d>=bi)return;let C=bi-d,y=Buffer.from(b).subarray(0,C);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:b,spawnError:C})=>{let y=n.acceptedExitCodes??[0];if(b!==null&&y.includes(b)&&C===null&&!N&&h.byteLength===0&&!g){r({records:c,digest:l.digest("hex"),overflow:S,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${C?`: ${C.message}`:N||h.byteLength>0||g?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function Sa(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 tk(e,t,i){if(i.length===0)return new Set;let n=await xn(e,t,["check-ignore","--no-index","-z","--stdin"],{...Sc,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(n.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(n.records.map(r=>{let a=Sa(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function ik(e,t,i){let{child:n,completion:r}=Ec(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>=bi)return;let d=bi-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.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 Ni(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 nk(e,t){return e.map(i=>{let n=Ni(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function rk(e){let t=H.resolve(e);for(;;){try{return await X.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 sh(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(f=>{let p=H.relative(r,H.resolve(f)).replaceAll("\\","/"),m=Ni(p);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},l=await xn(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await xn(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await xn(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function ch(e){return{stageBefore:wc(e.stagedBefore),combined:wc(e.combined),stageAfter:wc(e.stagedAfter)}}async function lh(e,t,i=Sc,n={}){let r=H.resolve(t.projectRoot);if(!await rk(r))return null;let a;try{a=await ka(e,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw yi(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}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 sh(e,t,i,n)}catch(N){throw yi(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=N=>{for(let k of N){let b=Sa(k),C=b.indexOf(" ");if(C<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let y=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(b.slice(0,C))?.groups;if(!y)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=Ni(b.slice(C+1));if(w===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(w),y.stage==="0"&&d.set(w,y.objectId),y.mode==="160000"&&y.stage==="0"&&f.add(w)}};p(s.records),p(l.records);let m=c.records.map(Sa),h=nk(m,"combined"),g=new Set(h.filter(N=>!u.has(N))),S=new Set(h.filter((N,k)=>!u.has(N)&&m[k].endsWith("/")));for(let N of f)S.delete(N);return{tracked:u,trackedObjectIds:d,untracked:g,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:ch(o)}}function wt(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Kf(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function ak(e,t){return!wt(e.stageBefore,e.stageAfter)||!wt(e.stageAfter,t.stageBefore)||!wt(e.combined,t.combined)||!wt(t.stageBefore,t.stageAfter)}async function uh(e,t,i,n,r){let a;try{a=await sh(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw yi(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=ch(a),c=Kf(o)||Kf(s),l=ak(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:U(`comet.native.git-selection-overflow.v2
143
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var ok=(1n<<256n)-1n;function sk(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Yf(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,d=0,f=!1,p=!1,m=!1,h=()=>_e(e.execution)>=1?!0:(f=!0,m=!0,!1),g=k=>{let b=Buffer.from(`${k.type}\0${k.path}`,"utf8"),C=Ca("sha256").update("comet.native.physical-selection-record.v1\0").update(b).digest();for(let y=0;y<s.length;y+=1)s[y]^=C[y];if(c=c+BigInt(`0x${C.toString("hex")}`)&ok,u+=1,d+=b.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(k)},S=async k=>{if(m||!h())return;let b;try{b=await X.opendir(k)}catch(E){if(!h())return;if(!ne(E)&&!ie(E)||k===t&&ne(E))throw E;p||=ie(E),f||=ne(E),m=!0;return}if(!h()){try{await b.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let C=!1,y;try{for(;!m&&h();){let E;try{E=await b.read()}catch(K){if(!h())break;if(!ne(K)&&!ie(K)||k===t&&ne(K))throw K;p||=ie(K),f||=ne(K),m=!0;break}if(!h()||E===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let I=H.join(k,E.name),J=lk(t,I);if(I===n||I===r||yt(i,I)||e.denylist.some(K=>yt(K,I))||Ve(J)!==null)continue;if(!h())break;let L;try{L=await X.lstat(I)}catch(K){if(!h())break;if(!ne(K)&&!ie(K))throw K;if(p=!0,g({path:J,type:"other"}),o.push({path:J,size:null,type:"file",reason:ne(K)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(J),m||!h())break;continue}if(!h())break;let W=sk(L);if(W==="directory"){if(hk(e.policy,J))continue;if(!h())break;let K;try{K=await X.realpath(I)}catch(Me){if(!h())break;if(!ne(Me)&&!ie(Me))throw Me;if(p=!0,g({path:J,type:W}),o.push({path:J,size:null,type:"directory",reason:ne(Me)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(J),m||!h())break;continue}if(!h())break;if(!V(e.physicalProjectRoot,K)||yt(e.physicalNativeRoot,K))continue;if(g({path:J,type:W}),await e.hooks?.afterNode?.(J),!h()||(await S(I),m))break;continue}if(g({path:J,type:W}),await e.hooks?.afterNode?.(J),!h()||m)break}}catch(E){C=!0,y=E}let w;try{await b.close()}catch(E){w=E}let v=h();if(C)throw y;if(v&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await S(t),h(),f?(a.length=0,u=0,d=0):(a.sort((k,b)=>k.path.localeCompare(b.path,"en")),o.sort((k,b)=>k.path.localeCompare(b.path,"en")));let N=f?U(`comet.native.physical-selection-incomplete.v1
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=ja(t),r=ji(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=ja(t),r=ji(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())}}};kp.Parser=Rc});var Cp=C(Gr=>{"use strict";var Sp=mc(),Qb=Br(),Jr=Mr(),Zb=ps(),ek=L(),tk=Cc(),Ep=Ac();function Pp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new tk.LineCounter||null,prettyErrors:t}}function ik(e,t={}){let{lineCounter:i,prettyErrors:r}=Pp(t),n=new Ep.Parser(i?.addNewLine),a=new Sp.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Jr.prettifyError(e,i)),s.warnings.forEach(Jr.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function xp(e,t={}){let{lineCounter:i,prettyErrors:r}=Pp(t),n=new Ep.Parser(i?.addNewLine),a=new Sp.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 Jr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Jr.prettifyError(e,i)),o.warnings.forEach(Jr.prettifyError(e,i))),o}function rk(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=xp(e,i);if(!n)return null;if(n.warnings.forEach(a=>Zb.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 nk(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 ek.isDocument(e)&&!r?e.toString(i):new Qb.Document(e,r,i).toString(i)}Gr.parse=rk;Gr.parseAllDocuments=ik;Gr.parseDocument=xp;Gr.stringify=nk});var Ur=C(V=>{"use strict";var ak=mc(),ok=Br(),sk=Ks(),_c=Mr(),ck=kr(),Ht=L(),lk=Tt(),uk=ie(),dk=jt(),fk=$t(),pk=Ta(),hk=Pc(),mk=Cc(),vk=Ac(),Oa=Cp(),Rp=wr();V.Composer=ak.Composer;V.Document=ok.Document;V.Schema=sk.Schema;V.YAMLError=_c.YAMLError;V.YAMLParseError=_c.YAMLParseError;V.YAMLWarning=_c.YAMLWarning;V.Alias=ck.Alias;V.isAlias=Ht.isAlias;V.isCollection=Ht.isCollection;V.isDocument=Ht.isDocument;V.isMap=Ht.isMap;V.isNode=Ht.isNode;V.isPair=Ht.isPair;V.isScalar=Ht.isScalar;V.isSeq=Ht.isSeq;V.Pair=lk.Pair;V.Scalar=uk.Scalar;V.YAMLMap=dk.YAMLMap;V.YAMLSeq=fk.YAMLSeq;V.CST=pk;V.Lexer=hk.Lexer;V.LineCounter=mk.LineCounter;V.Parser=vk.Parser;V.parse=Oa.parse;V.parseAllDocuments=Oa.parseAllDocuments;V.parseDocument=Oa.parseDocument;V.stringify=Oa.stringify;V.visit=Rp.visit;V.visitAsync=Rp.visitAsync});import ai from"node:path";import{execFileSync as Fg}from"child_process";import vr from"path";function ki(e,t){return Fg("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Lg(e,t){let i=vr.normalize(e),r=vr.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Fe(e){try{let t=vr.resolve(ki(e,["rev-parse","--show-toplevel"])),r=ki(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?vr.resolve(r.slice(9)):t,a=null;try{a=ki(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Lg(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Dn(e){try{ki(e,["rev-parse","--is-inside-work-tree"])}catch{return[]}return ki(e,["worktree","list","--porcelain","-z"]).split("\0").filter(i=>i.startsWith("worktree ")).map(i=>vr.resolve(i.slice(9)))}function Ko(e,t){try{let i=ki(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as Mg}from"crypto";function Le(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function qg(e,t){t.has(e)&&Le("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)||Le("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Le("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Le("symbol properties are not supported"),`[${e.map(r=>Yo(r,t)).join(",")}]`}finally{t.delete(e)}}function Vg(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Le("only plain objects are supported"),t.has(e)&&Le("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Le("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))&&Le("accessor properties are not supported"),`${JSON.stringify(o)}:${Yo(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Yo(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)||Le("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?qg(e,t):Vg(e,t);case"bigint":case"function":case"symbol":case"undefined":return Le(`${typeof e} values are not supported`)}return Le("unsupported value type")}function gr(e){return Yo(e,new Set)}function O(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return Mg("sha256").update(`${e}
143
+ ${gr(t)}`).digest("hex")}var Rl=Hn(Ur(),1);import{promises as Uh}from"fs";import yt from"path";import{createHash as Nk}from"node:crypto";import{promises as Ve}from"node:fs";import Te from"node:path";import{TextDecoder as bk}from"node:util";import Tc from"path";var gk=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),wk=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function yk(e){return e.toLowerCase().startsWith(".env")}function nt(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>yk(r))?"environment-file":i.some(r=>wk.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>gk.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Ic(e,t){let i=nt(t);if(i)return i;let r=Tc.resolve(e.projectRoot,...t.split("/")),n=Tc.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Tc.resolve(e.configFile)?"native-runtime":null}function Dt(e){return e!==0&&e!==0n&&e!=="0"}function ye(e,t){return Dt(e.dev)&&Dt(t.dev)&&Dt(e.ino)&&Dt(t.ino)}function W(e,t){let i=Dt(e.dev)&&Dt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Dt(e.ino)&&Dt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var Kr=1024*1024;function jc(e,t){let i=Te.relative(e,t);return i===""||!Te.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Te.sep}`)}function kk(e){let t=Te.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})||Te.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=nt(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 Sk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Ek(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ha(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ye(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ap(e){let t=await Ve.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact 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 Pk(e,t){let i=Te.resolve(e),r=Te.resolve(t);if(!jc(i,r))throw new Error("Native artifact path is outside its root");let n=[await Ap(i)],a=i;for(let o of Te.relative(i,r).split(Te.sep).filter(Boolean)){a=Te.join(a,o);let s=await Ap(a);if(!jc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function _p(e){for(let t of e){let i=await Ve.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ek(t,i)||await Ve.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ce(e){let t=kk(e.ref),i=e.maxBytes===null?null:Sk(e.maxBytes??Kr),r=Te.resolve(e.root,...t.split("/")),n=await Pk(e.root,Te.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ve.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 Ve.realpath(r);if(!jc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ve.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ve.lstat(r),Ve.realpath(r)]);if(await _p(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ha(a,c)||!Ha(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let P=i===null?h.length:i+1-f,k=await s.read(h,0,Math.min(h.length,P),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),Ve.lstat(r),Ve.realpath(r)]);if(await _p(n),!p.isFile()||p.isSymbolicLink()||m!==o||!Ha(c,v)||!Ha(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),N;try{N=new bk("utf-8",{fatal:!0}).decode(b)}catch(P){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:P})}return{ref:t,size:f,hash:e.includeHash===!1?null:Nk("sha256").update(b).digest("hex"),text:N}}finally{await s.close()}}var Oc=Hn(Ur(),1);import Da from"path";var Xr=64*1024,Ba=1024,Fa=64,Ip=5,xk=[".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/**"],Ck=["**/.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"],Rk=[...xk,...Ck].sort((e,t)=>e.localeCompare(t,"en"));var We={include:["**/*"],exclude:[...Rk],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Ak(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Da.posix.isAbsolute(i)||Da.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 $i(e){let t=Ak(e,"native.artifact_root");return t.length===0?".":t.join("/")}function jp(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 Hc(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||Da.posix.isAbsolute(r)||Da.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 Yr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function $p(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 La(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>Ba)throw new Error(`${t} exceeds ${Ba} 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>Fa)throw new Error(`${t} contains more than ${Fa} wildcard tokens`);return e}function Tp(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=>La(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function $c(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 _k(e){if(e===void 0)return{...We,include:[...We.include],exclude:[...We.exclude]};let t=Yr(e,"native.snapshot");return{include:Tp(t.include,"native.snapshot.include",We.include),exclude:Tp(t.exclude,"native.snapshot.exclude",We.exclude),max_files:$c(t.max_files,We.max_files,"native.snapshot.max_files"),max_total_bytes:$c(t.max_total_bytes,We.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:$c(t.max_duration_ms,We.max_duration_ms,"native.snapshot.max_duration_ms")}}function Tk(e){if(e===void 0)return;let t=Yr(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=Yr(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:$i(r),toArtifactRoot:$i(n),stage:a,...o?{cleanup:o}:{}}}function Ik(e,t={}){let i=Yr(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??Ip;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Tk(i.pending_root_move);return{artifact_root:$i(r),language:$p(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:_k(i.snapshot),...s?{pending_root_move:s}:{}}}function jk(e){let t=Yr(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:jp(t.artifact_layout),language:$p(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function $k(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Ok(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 Qr(e,t={}){let i=(0,Oc.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=$k(n.ambient_resume),o=n.native===void 0?void 0:Ik(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=n.classic===void 0?void 0:jk(n.classic),c=Ok(n,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}import{createHash as Dk}from"crypto";import{promises as Va}from"fs";import Bt from"path";import{constants as Ma,promises as fi}from"fs";var at=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Dc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Op(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Zr(e){return{dev:e.dev,ino:e.ino,birthtime:Dc(e)}}function qa(e,t){let i=Zr(e),r=Zr(t);return ye(i,r)?W(i,r):W(i,r)&&Dc(e)===Dc(t)&&Op(e)===Op(t)&&e.size===t.size}async function Oi(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 fi.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new at("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new at("too-large",`${r} exceeds ${t} bytes`);let o=await fi.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Zr(a)});let s=process.platform==="win32"?Ma.O_RDONLY:Ma.O_RDONLY|Ma.O_NOFOLLOW|Ma.O_NONBLOCK,c;try{c=await fi.open(e,s)}catch(l){throw l.code==="ELOOP"?new at("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),fi.lstat(e,{bigint:n}),fi.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!qa(a,l)||!qa(a,u))throw new at("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Zr(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-h,{bytesRead:P}=await c.read(v,0,Math.min(v.length,N),null);if(P===0)break;if(h+=P,h>t)throw new at("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,P)))}await i.hooks?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([c.stat({bigint:n}),fi.lstat(e,{bigint:n}),fi.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||b!==o||!qa(a,p)||!qa(a,m))throw new at("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Zr(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:b}}finally{await c.close()}}function Hk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Bc(e,t){let i=Bt.relative(e,t);return i===""||!Bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Bt.sep}`)}async function Hp(e,t){let i=Bt.resolve(e),r=await Va.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Va.realpath(i)}async function Dp(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Bt.join(n,i[a]);let o;try{o=await Va.lstat(n)}catch(u){if(Hk(u))return{exists:!1,kind:"missing"};throw u}let s=Bt.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 Va.realpath(n);if(!Bc(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 Hi(e,t,i){let r=Hc(t,i.label),n=Bt.resolve(e),a=await Hp(n,i.label),o=r.split("/"),s=Bt.resolve(n,...o);if(!Bc(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Dp(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Ft(e,t,i,r){let n=await Hi(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 Hp(n.projectRoot,r.label);return Oi(n.target,i,{...r,verify:async(o,s)=>{if(!Bc(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Dp(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var en=".comet/config.yaml";function Bk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Fc(e,t={}){return(await Wa(e,t)).document}async function Fk(e){try{return(await Ft(e,en,Xr,{label:en})).bytes}catch(t){if(Bk(t))return null;throw t}}function Lk(e){return e?{exists:!0,sha256:Dk("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Wa(e,t={}){let i=await Fk(e);return{document:i?Qr(i.toString("utf8"),t):null,identity:Lk(i)}}var VT=16*1024;import{existsSync as Fp,promises as Lt}from"fs";import q from"path";import zk from"os";var Wc=".comet/config.yaml",Jk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function qc(e){try{return await Lt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gk(e){try{let t=await Lt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Bi(e,t){let i=q.relative(e,t);return i===""||!q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${q.sep}`)}async function Di(e){let t=[],i=e;for(;!await qc(i);){let n=q.dirname(i);if(n===i)break;t.push(q.basename(i)),i=n}let r=await Lt.realpath(i);return q.resolve(r,...t.reverse())}async function Vc(e){try{return(await Lt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function zc(e){let t=q.resolve(e);try{(await Lt.stat(t)).isDirectory()||(t=q.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=q.resolve(zk.homedir());for(;;){if(!(t===r&&i!==r)){let o=q.join(t,...Wc.split("/")),s=t===i||await Gk(o);if(await qc(o)&&s)return t}if(await qc(q.join(t,".git")))return t;let a=q.dirname(t);if(a===t)return i;t=a}}function Jc(e){return $i(e)}async function Uk(e,t){let i=Jc(t),r=q.resolve(e,...i.split("/")),n=await Lt.realpath(e),a=await Di(r);if(!Bi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Fi(e,t){let i=Jc(t),r=await Uk(e,i),n=q.join(r,"comet");if(await Vc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Di(r),Di(n)]);if(!Bi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=q.resolve(e),c=q.join(s,".comet","runtime","native");if(await Vc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Lt.realpath(s),Di(c)]);if(!Bi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:q.join(e,...Wc.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:q.join(n,"specs"),changesDir:q.join(n,"changes"),archiveDir:q.join(n,"archive"),runtimeDir:c,changesRuntimeDir:q.join(c,"changes"),locksDir:q.join(c,"locks"),transactionsDir:q.join(c,"transactions")}}function Mp(e){if(!Jk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Li(e,t){Mp(t);let i=q.join(e.changesRuntimeDir,t);if(!F(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function qp(e,t){Mp(t);let i=q.join(e.changesDir,t,"runtime");if(!F(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function G(e,t){let i=Li(e,t);if(Fp(i))return i;let r=qp(e,t);return Fp(r)?r:i}async function Lp(e){try{let t=await Lt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Gc(e,t){let i=Li(e,t),r=qp(e,t),[n,a]=await Promise.all([Lp(i),Lp(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Mt(e,t){if(!t.startsWith("runtime/")||q.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=q.resolve(e,...t.slice(8).split("/"));if(!F(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function oe(e,t){let i=q.resolve(t);if(F(e.runtimeDir,i))return e.runtimeDir;if(F(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function F(e,t){return Bi(q.resolve(e),q.resolve(t))}async function z(e,t){let i=q.resolve(e),r=q.resolve(t);if(!Bi(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Vc(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Di(i),Di(r)]);if(!Bi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Uc=We;var za=La;async function ze(e){let t=(await Fc(e))?.config??null;return t?.native?t:null}import{AsyncLocalStorage as Yk}from"async_hooks";var hI=16*1024;var mI=new Yk;import Wp from"node:path";var Xk="comet.native.acceptance.v1",Qk=/^acceptance-[a-f0-9]{64}$/u,Zk=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),eS=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,tS=/^[a-f0-9]{64}$/u,iS=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function rS(e,t){return e<t?-1:e>t?1:0}var mt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),rn=Object.freeze({maxCriteria:1024}),zp="<!-- comet-native:acceptance-evidence:start -->",Jp="<!-- comet-native:acceptance-evidence:end -->";function Gp(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value: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{value:i,truncated:!0}}function Up(e,t){let i=t.toString(36),r=O("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function nS(e){if(!tS.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=iS.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==O("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function aS(e,t){let i=Gp(e.text,mt.maxTextBytes),r=e.context.slice(0,mt.maxContextItems).map(n=>Gp(n,mt.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Yp(e){let t=nS({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(rS),n=r.slice(0,mt.maxFailedCheckIds),a=e.criteria.slice(t,t+mt.maxItems);for(let c of a){let l=[...i,aS(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Up(e.acceptanceHash,u):null,limits:{...mt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>mt.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Up(e.acceptanceHash,o):null,limits:{...mt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>mt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Yc(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 Kc(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 Kp(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,`
144
+ `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
145
+ `,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=Kc(l,t);else if(i)Kp(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Kc(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Kp(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function oS(e){return[...Mi(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Ja(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function sS(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Xc(e,t,i,r=[],n="content-hash"){let a=Ja(i),o=t.replaceAll("\\","/").trim(),s=r.map(Ja);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${O(Xk,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Qc(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 cS(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?Yc(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 Zc(e,t="brief.md",i=rn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=cS(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Mi(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}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:u,index:d}of Mi(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Qc(o.map(l=>Xc("brief-example",t,l.join(`
146
+ `),[],r)),"Brief",r)}function el(e,t="spec.md",i=rn.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(Xc("spec-scenario",t,[o.title,...o.body].join(`
147
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of Mi(e)){let u=l?Yc(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Ja(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Qc(n,"Specification",r)}function tl(e,t="spec.md",i=rn.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(Xc("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Mi(e)){let f=d?Yc(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||Kc(u,null)!==null||h.startsWith("<!--")||h==="-->"||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(p=>p.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(p=>p.text)},c();continue}s===null?s={parts:[h],context:a.map(p=>p.text)}:s.parts.push(h)}return c(),Qc(n,"Specification mandatory requirements",r)}function lS(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||sS(i)||Wp.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 r=Wp.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!eS.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function uS(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,r=Object.keys(i).filter(n=>!Zk.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Xp(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,r)=>{let n=uS(i,r),a=n.acceptance_id;if(typeof a!="string"||!Qk.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return lS(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Qp(e){let t=oS(e);if(t.some(({line:l,body:u})=>!u&&(l===zp||l===Jp)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===zp?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Jp?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
148
+ `).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=Xp(o),c=dS(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function dS(e){let t=Xp([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var rl=Hn(Ur(),1);import{promises as pS}from"node:fs";var nn="comet.native.v4",Ga="comet.native.local-execution.v4";var hS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vS=/^A[1-9][0-9]*$/u,gS=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"]);function Ne(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function be(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 pe(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 il(e,t){return e===null?null:pe(e,t)}function qi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function te(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 wS(e,t){return e===null?null:te(e,t,Number.MIN_SAFE_INTEGER)}function le(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ot(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Ua(e,t){return ot(e,t,(i,r)=>pe(i,`${t}[${r}]`))}function hi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Vi(e,t){let i=pe(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function nl(e,t,i=!1){let r=pe(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 Je(e,t){let i=Ne(e,t);return be(i,new Set(["text","truncated"]),t),{text:pe(i.text,`${t}.text`,{empty:!0}),truncated:qi(i.truncated,`${t}.truncated`)}}function yS(e,t){let i=`Native spec_changes[${t}]`,r=Ne(e,i);be(r,new Set(["capability","operation","source"]),i);let n=pe(r.capability,`${i}.capability`);if(!mS.test(n))throw new Error(`${i}.capability is invalid`);let a=le(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:nl(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 NS(e){let t="Native workspace",i=Ne(e,t);be(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=le(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=il(i.change_branch,`${t}.change_branch`),a=il(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:le(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 bS(e){let t="Native loop",i=Ne(e,t);be(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=Ua(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return hi(r,`${t}.previous_unresolved_ids`),{stage:le(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:te(i.goal_cycle,`${t}.goal_cycle`,1),iteration:te(i.iteration,`${t}.iteration`),attempt:te(i.attempt,`${t}.attempt`),retry_epoch:te(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:te(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:te(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:te(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:il(i.next_action,`${t}.next_action`)}}function kS(e,t){let i=`Native acceptance[${t}]`,r=Ne(e,i);be(r,new Set(["id","source","text","result","reason"]),i);let n=pe(r.id,`${i}.id`);if(!vS.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:nl(r.source,`${i}.source`),text:pe(r.text,`${i}.text`),result:le(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Je(r.reason,`${i}.reason`)}}function SS(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["name","result","note"]),i),{name:Je(r.name,`${i}.name`),result:le(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Je(r.note,`${i}.note`)}}function ES(e){let t="Native builder_handoff",i=Ne(e,t);be(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=Ua(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return hi(r,`${t}.addressed_acceptance_ids`),{candidate_id:pe(i.candidate_id,`${t}.candidate_id`),identity_provider:pe(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:pe(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),summary:Je(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ot(i.checks,`${t}.checks`,SS),checks_truncated:qi(i.checks_truncated,`${t}.checks_truncated`),known_limits:ot(i.known_limits,`${t}.known_limits`,(n,a)=>Je(n,`${t}.known_limits[${a}]`)),known_limits_truncated:qi(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Vi(i.submitted_at,`${t}.submitted_at`)}}function PS(e,t){let i=`Native blockers[${t}]`,r=Ne(e,i);be(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Ua(r.acceptance_ids,`${i}.acceptance_ids`);return hi(n,`${i}.acceptance_ids`),{owner:le(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Je(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:le(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function xS(e,t){let i=`Native verification.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:pe(r.id,`${i}.id`),name:Je(r.name,`${i}.name`),argv_display:ot(r.argv_display,`${i}.argv_display`,(n,a)=>Je(n,`${i}.argv_display[${a}]`)),argv_truncated:qi(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:nl(r.cwd_ref,`${i}.cwd_ref`,!0),status:le(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:wS(r.exit_code,`${i}.exit_code`),duration_ms:te(r.duration_ms,`${i}.duration_ms`)}}function CS(e){let t="Native verification",i=Ne(e,t);be(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ot(i.checks,`${t}.checks`,xS);hi(r.map(a=>a.id),`${t}.checks IDs`);let n=pe(i.identity_provider,`${t}.identity_provider`);return{candidate_id:pe(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:pe(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),attempt:te(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":le(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:le(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Je(i.summary,`${t}.summary`),risks:ot(i.risks,`${t}.risks`,(a,o)=>Je(a,`${t}.risks[${o}]`)),risks_truncated:qi(i.risks_truncated,`${t}.risks_truncated`),completed_at:Vi(i.completed_at,`${t}.completed_at`)}}function RS(e,t){let i=`Native history[${t}]`,r=Ne(e,i);be(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Ua(r.unresolved_ids,`${i}.unresolved_ids`);return hi(n,`${i}.unresolved_ids`),{goal_cycle:te(r.goal_cycle,`${i}.goal_cycle`,1),iteration:te(r.iteration,`${i}.iteration`),attempt:te(r.attempt,`${i}.attempt`),outcome:le(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Je(r.summary,`${i}.summary`),completed_at:Vi(r.completed_at,`${i}.completed_at`)}}function AS(e){let t="Native history_overflow.outcome_counts",i=Ne(e,t),r=["pass","fail","blocked","execution-error","recovery"];return be(i,new Set(r),t),{pass:te(i.pass,`${t}.pass`),fail:te(i.fail,`${t}.fail`),blocked:te(i.blocked,`${t}.blocked`),"execution-error":te(i["execution-error"],`${t}.execution-error`),recovery:te(i.recovery,`${t}.recovery`)}}function _S(e){let t="Native history_overflow",i=Ne(e,t);be(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=te(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Vi(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Vi(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=AS(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 TS(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 IS(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 al(e){let t=Ne(e,"Native portable state");if(be(t,gS,"Native portable state"),t.schema!==nn)throw new Error(`Native portable state schema must be ${nn}`);let i=pe(t.name,"Native state name");if(!hS.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=ot(t.spec_changes,"Native spec_changes",yS);hi(r.map(s=>s.capability),"Native spec change capabilities");let n=ot(t.acceptance,"Native acceptance",kS);hi(n.map(s=>s.id),"Native acceptance IDs");let a=ot(t.history,"Native history",RS);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:nn,name:i,language:le(t.language,["en","zh-CN"],"Native state language"),phase:le(t.phase,["shape","build","verify","archive"],"Native state phase"),status:le(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:te(t.state_version,"Native state_version",1),brief:"brief.md",spec_changes:r,workspace:NS(t.workspace),loop:bS(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ES(t.builder_handoff),blockers:ot(t.blockers,"Native blockers",PS),verification:t.verification===null?null:CS(t.verification),history:a,history_overflow:_S(t.history_overflow),verification_result:le(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:le(t.verification_report,["verification.md"],"Native verification_report"),archived:qi(t.archived,"Native archived"),created_at:Vi(t.created_at,"Native created_at")};return TS(o),IS(o),o}function jS(e,t){let i=(0,rl.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 eh(e){let t=await pS.readFile(e,"utf8");return al(jS(t,"Native portable state"))}var qt="comet.native.v3",Vt="comet.native.v2",Wt="comet.native.v1",Wi="comet.native.transition.v3",zi="comet.native.transition.v2",an="comet.native.transition.v1";var ih="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",LI=new RegExp(`^portable-archive-(${ih})\\.json$`,"u"),MI=new RegExp(`^portable-migration-(${ih})\\.json$`,"u");import{TextDecoder as LS}from"util";import{createHash as $S}from"node:crypto";import{constants as Ka,promises as xe}from"node:fs";import Ge from"node:path";import{TextDecoder as OS}from"node:util";function Xa(e,t){let i=Ge.relative(e,t);return i===""||!Ge.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ge.sep}`)}function rh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function HS(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function DS(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ya(e,t){return W({...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 ol(e,t){let i=await xe.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await xe.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function sl(e,t,i){let r=Ge.resolve(e),n=Ge.resolve(t);if(!Xa(r,n))throw new Error(`${i} is outside its managed root`);let a=[await ol(r,i)],o=r;for(let s of Ge.relative(r,n).split(Ge.sep).filter(Boolean)){await st(a,i),o=Ge.join(o,s);let c=await ol(o,i);if(!Xa(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await st(a,i),a}async function st(e,t){for(let i of e){let r=await xe.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!HS(i,r)||await xe.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function BS(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 vt(e){let t=rh(e.maxBytes),i=Ge.resolve(e.file),r=await sl(e.root,Ge.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>ol(Ge.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await st(r,e.label);let a=await xe.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=DS(a),s=await xe.realpath(i);if(!Xa(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Xa(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ka.O_RDONLY:Ka.O_RDONLY|Ka.O_NOFOLLOW|Ka.O_NONBLOCK,l=await xe.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([xe.lstat(i),xe.realpath(i)]);if(await st(r,e.label),await st(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Ya(o,u)||!Ya(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await BS(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),xe.lstat(i),xe.realpath(i)]);if(await st(r,e.label),await st(n,e.label),!p.isFile()||p.isSymbolicLink()||m!==s||!Ya(o,v)||!Ya(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:$S("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function nh(e){let t=await vt(e),i;try{i=new OS("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function on(e){let t=await sl(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await xe.readdir(e.directory,{withFileTypes:!0});else{let r=rh(e.maxEntries);i=[];let n=await xe.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await st(t,e.label),{entries:i,verify:()=>st(t,e.label)}}async function cl(e){let t=await sl(e.root,e.directory,e.label);return{verify:()=>st(t,e.label)}}var rj=256*1024,nj=1024*1024,aj=16*1024;var oj=64*1024*1024;var sj=new LS("utf-8",{fatal:!0});import{createHash as io}from"crypto";import{spawn as wh}from"node:child_process";import{promises as Y}from"fs";import H from"path";import{createHash as lh}from"crypto";import{createReadStream as qS}from"fs";async function ll(e){let t=lh("sha256");for await(let i of qS(e))t.update(i);return t.digest("hex")}function U(e){return lh("sha256").update(e).digest("hex")}var Qa={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},ml=1e3,VS=8*1024*1024,WS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zS=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),JS=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),GS=new Set(["schema","include","exclude","hash"]),US=new Set(["provider","gitSelection","physicalSelection","projection"]),KS=new Set(["provider","selection"]),YS=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),XS=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),QS=new Set(["schema","status","before","after"]),ZS=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),eE=new Set(["path","hash","size","type","gitObjectId"]),tE=new Set(["path","size","type","reason"]),iE=new Set(["ref","hash","count"]),rE=new Set(["change-created","legacy-migration","explicit"]),nE=new Set(["file","directory","other"]),aE=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"]),ro=/^[a-f0-9]{64}$/u,yh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,oE=new Set(["EACCES","EPERM"]),Qi=64*1024,pl=64*1024,sE=6e4,cE=1e3,lE=2,vl={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},uE={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Nh(e){let t=e.deadlineMs??sE;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 Ue(e){return Math.max(0,e.deadlineAt-Date.now())}function j(e){return Ue(e)>=1}function ul(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 Yi(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function dE(e){let t={...uE,...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 fE(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 r=process.env.SystemRoot??process.env.WINDIR,n=r&&H.win32.isAbsolute(r)?H.win32.resolve(r):"C:\\Windows",a=H.win32.join(n,"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,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=wh(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),cE),u.unref()}catch{d(!1)}});for(let s=0;s<lE;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(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function gl(e,t,i,r){let n=Ue(e);if(n<1)throw ul();let a=e.gitProcess,o=wh(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=fE(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?ul(v.error):ul()}return{code:h,spawnError:s}});return{child:o,completion:f}}function bh(e){let t={...vl,...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 Za(e,t,i,r=pl){let{child:n,completion:a}=gl(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=Qi)return;let v=Qi-c,p=Buffer.from(h).subarray(0,v);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function dl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function cn(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=gl(e,t,i,r.stdin!==void 0),c=[],l=io("sha256"),u=[],d=0,f=0,h=0,v=0,p=Buffer.alloc(0),m=!1,b=!1,N=!1,P=k=>{let E=0;for(;E<k.byteLength;){let y=k.indexOf(0,E),x=y<0?k.byteLength:y,w=k.subarray(E,x);if(!m&&w.byteLength>0&&(p.byteLength+w.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),m=!0,b=!0):p=Buffer.concat([p,w])),y<0)break;v+=1,p.byteLength===0&&!m&&(N=!0);let g=p.byteLength+1;!m&&v<=r.maxRecords&&h+g<=r.maxBytes?(c.push(p),h+=g):b=!0,p=Buffer.alloc(0),m=!1,E=y+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(b=!0);let E=r.outputChunkBytes;if(E===void 0){P(k);return}for(let y=0;y<k.byteLength;y+=E)P(k.subarray(y,Math.min(k.byteLength,y+E)))}),o.stderr.on("data",k=>{if(d>=Qi)return;let E=Qi-d,y=Buffer.from(k).subarray(0,E);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:E})=>{let y=r.acceptedExitCodes??[0];if(k!==null&&y.includes(k)&&E===null&&!N&&p.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:N||p.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function eo(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 pE(e,t,i){if(i.length===0)return new Set;let r=await cn(e,t,["check-ignore","--no-index","-z","--stdin"],{...vl,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=eo(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function hE(e,t,i){let{child:r,completion:n}=gl(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Qi)return;let d=Qi-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Xi(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 mE(e,t){return e.map(i=>{let r=Xi(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function vE(e){let t=H.resolve(e);for(;;){try{return await Y.lstat(H.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=H.dirname(t);if(i===t)return!1;t=i}}async function kh(e,t,i,r={}){let n=H.resolve(t.projectRoot),a=H.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=H.relative(n,H.resolve(f)).replaceAll("\\","/"),v=Xi(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await cn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await cn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await cn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Sh(e){return{stageBefore:dl(e.stagedBefore),combined:dl(e.combined),stageAfter:dl(e.stagedAfter)}}async function Eh(e,t,i=vl,r={}){let n=H.resolve(t.projectRoot);if(!await vE(n))return null;let a;try{a=await Za(e,n,["rev-parse","--is-inside-work-tree"])}catch(N){throw Yi(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}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 kh(e,t,i,r)}catch(N){throw Yi(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=N=>{for(let P of N){let k=eo(P),E=k.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let y=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,E))?.groups;if(!y)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=Xi(k.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),y.stage==="0"&&d.set(x,y.objectId),y.mode==="160000"&&y.stage==="0"&&f.add(x)}};h(s.records),h(l.records);let v=c.records.map(eo),p=mE(v,"combined"),m=new Set(p.filter(N=>!u.has(N))),b=new Set(p.filter((N,P)=>!u.has(N)&&v[P].endsWith("/")));for(let N of f)b.delete(N);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:Sh(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 uh(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function gE(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 Ph(e,t,i,r,n){let a;try{a=await kh(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Yi(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=Sh(a),c=uh(o)||uh(s),l=gE(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.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)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:U(`comet.native.git-selection-overflow.v2
149
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var wE=(1n<<256n)-1n;function yE(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function dh(e){let t=H.resolve(e.paths.projectRoot),i=H.resolve(e.paths.nativeRoot),r=H.resolve(e.paths.runtimeDir),n=H.resolve(e.paths.configFile),a=H.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,p=!1,m=()=>Ue(e.execution)>=1?!0:(h=!0,p=!0,!1),b=k=>{let E=Buffer.from(`${k.type}\0${k.path}`,"utf8"),y=io("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=y[x];if(l=l+BigInt(`0x${y.toString("hex")}`)&wE,d+=1,f+=E.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,p=!0;return}o.push(k)},N=async k=>{if(p||!m())return;let E;try{E=await Y.opendir(k)}catch(S){if(!m())return;if(!ne(S)&&!re(S)||k===t&&ne(S))throw S;v||=re(S),h||=ne(S),p=!0;return}if(!m()){try{await E.close()}catch(S){if(S.code!=="ERR_DIR_CLOSED")throw S}return}let y=!1,x;try{for(;!p&&m();){let S;try{S=await E.read()}catch(J){if(!m())break;if(!ne(J)&&!re(J)||k===t&&ne(J))throw J;v||=re(J),h||=ne(J),p=!0;break}if(!m()||S===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,p=!0;break}let D=H.join(k,S.name),I=bE(t,D);if(D===n||D===a||Ke(i,D)||Ke(r,D)||e.denylist.some(J=>Ke(J,D))||nt(I)!==null)continue;if(!m())break;let de;try{de=await Y.lstat(D)}catch(J){if(!m())break;if(!ne(J)&&!re(J))throw J;if(v=!0,b({path:I,type:"other"}),s.push({path:I,size:null,type:"file",reason:ne(J)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(I),p||!m())break;continue}if(!m())break;let X=yE(de);if(X==="directory"){if(PE(e.policy,I))continue;if(!m())break;let J;try{J=await Y.realpath(D)}catch(tt){if(!m())break;if(!ne(tt)&&!re(tt))throw tt;if(v=!0,b({path:I,type:X}),s.push({path:I,size:null,type:"directory",reason:ne(tt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(I),p||!m())break;continue}if(!m())break;if(!F(e.physicalProjectRoot,J)||Ke(e.physicalNativeRoot,J))continue;if(b({path:I,type:X}),await e.hooks?.afterNode?.(I),!m()||(await N(D),p))break;continue}if(b({path:I,type:X}),await e.hooks?.afterNode?.(I),!m()||p)break}}catch(S){y=!0,x=S}let w;try{await E.close()}catch(S){w=S}let g=m();if(y)throw x;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await N(t),m(),h?(o.length=0,d=0,f=0):(o.sort((k,E)=>k.path.localeCompare(E.path,"en")),s.sort((k,E)=>k.path.localeCompare(E.path,"en")));let P=h?U(`comet.native.physical-selection-incomplete.v1
144
150
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):U(`comet.native.physical-selection.v1
145
- ${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:d,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:N,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:p}}}function dh(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 ck(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!dh(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 fh(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Xf(e,t){let n=(await ka(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!rh.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return U(`gitlink:${n}`)}async function Qf(e,t){let i=await Xf(e,t),n=await ik(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await Xf(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function An(e,t){if(Ve(t)!==null)return!1;let i=H.resolve(e.projectRoot,...t.split("/"));return!yt(H.resolve(e.nativeRoot),i)}function lk(e,t){return H.relative(e,t).split(H.sep).join("/")}function uk(e,t){return t.map(i=>H.resolve(e,...i.split(/[\\/]/u)))}function yt(e,t){let i=H.resolve(e),n=H.resolve(t);return n===i||V(i,n)}function ne(e){return Ub.has(e.code??"")}function ie(e){return e.code==="ENOENT"}function Cc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
146
- `)}function dk(e,t){return U(`comet.native.snapshot-policy.v1
147
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function yc(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 fk(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Zf(e){let t=ga(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?fk(r):void 0;if(a&&!a())return!1;let o=yc(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=yc(i,c,a),o===null||o.size===0)return!1}return yc(i,o,a)?.has(i.length)??!1}}function hh(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>ga(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>ga(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=dk(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(Zf),excludeMatchers:i.map(Zf),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 hk(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function eh(e,t,i){if(!e)return!0;let n=()=>_(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 Tn(e,t,i){let n=JSON.stringify(i);return U(`${e}
151
+ ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:P,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function xh(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 NE(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!xh(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Ch(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function fh(e,t){let r=(await Za(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!yh.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return U(`gitlink:${r}`)}async function ph(e,t){let i=await fh(e,t),r=await hE(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await fh(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function sn(e,t){if(nt(t)!==null)return!1;let i=H.resolve(e.projectRoot,...t.split("/"));return!Ke(H.resolve(e.nativeRoot),i)&&!Ke(H.resolve(e.runtimeDir),i)}function bE(e,t){return H.relative(e,t).split(H.sep).join("/")}function kE(e,t){return t.map(i=>H.resolve(e,...i.split(/[\\/]/u)))}function Ke(e,t){let i=H.resolve(e),r=H.resolve(t);return r===i||F(i,r)}function ne(e){return oE.has(e.code??"")}function re(e){return e.code==="ENOENT"}function wl(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
152
+ `)}function SE(e,t){return U(`comet.native.snapshot-policy.v1
153
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function fl(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function EE(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function hh(e){let t=za(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?EE(n):void 0;if(a&&!a())return!1;let o=fl(i,new Set([0]),a);if(o===null)return!1;for(let s of r){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=fl(i,c,a),o===null||o.size===0)return!1}return fl(i,o,a)?.has(i.length)??!1}}function Rh(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>za(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>za(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=SE(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(hh),excludeMatchers:i.map(hh),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function PE(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function mh(e,t,i){if(!e)return!0;let r=()=>j(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function ln(e,t,i){let r=JSON.stringify(i);return U(`${e}
148
154
  ${Buffer.byteLength(t)}:${t}
149
- ${Buffer.byteLength(n)}:${n}`)}function bc(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ea(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!bc(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 fe(i,n)?q(i,n):q(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function pk(e,t,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await X.open(e,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=Ca("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!_(n))return{status:"budget-exhausted"};let c=await r.stat();if(!_(n))return{status:"budget-exhausted"};if(!c.isFile()||!gt(i,c))return{status:"changed"};for(;;){if(!_(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(!_(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!_(n))return{status:"budget-exhausted"};let d=await r.stat();return _(n)?!d.isFile()||!gt(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function Se(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ee(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function wi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Je(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ph(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 mk(e,t){let i=Se(e,`Native snapshot entry ${t}`);Ee(i,qb,`Native snapshot entry ${t}`);let n=ph(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Ra.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:Je(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!rh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function vk(e,t){let i=Se(e,`Native snapshot omission ${t}`);if(Ee(i,Vb,`Native snapshot omission ${t}`),!Jb.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!Gb.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:ph(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:Je(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function gk(e){let t=Se(e,"Native snapshot omission overflow");if(Ee(t,Wb,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ra.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:wi(t.count,"Native snapshot omission overflow count")}}function gi(e,t){let i=Se(e,t);if(Ee(i,Mb,t),typeof i.hash!="string"||!Ra.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=Je(i.recordCount,`${t} recordCount`),r=Je(i.storedRecordCount,`${t} storedRecordCount`),a=Je(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 th(e){let t=Se(e,"Native Git selection evidence");if(Ee(t,Db,"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=gi(t.stageBefore,"Native Git selection stageBefore"),n=gi(t.combined,"Native Git selection combined"),r=gi(t.stageAfter,"Native Git selection stageAfter"),a=gi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=gi(t.finalCombined,"Native Git selection finalCombined"),s=gi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!wt(i,r)||!wt(r,a)||!wt(n,o)||!wt(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 ih(e,t){let i=Se(e,t);if(Ee(i,Bb,t),typeof i.hash!="string"||!Ra.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=Je(i.visitedNodeCount,`${t} visitedNodeCount`),r=Je(i.recordCount,`${t} recordCount`),a=Je(i.storedRecordCount,`${t} storedRecordCount`),o=Je(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 wk(e){let t=Se(e,"Native physical selection evidence");if(Ee(t,Lb,"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=ih(t.before,"Native physical selection before"),n=ih(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!dh(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 Bt(e){let t=Se(e,"Native content snapshot manifest");if(Ee(t,jb,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zb.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=Se(t.capture,"Native content snapshot capture");if(Ee(y,Hb,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let w=y.gitSelection===void 0?void 0:th(y.gitSelection),v=y.physicalSelection===void 0?void 0:wk(y.physicalSelection),E=null;if(y.projection!==void 0){let I=Se(y.projection,"Native content snapshot projection");if(Ee(I,Fb,"Native content snapshot projection"),I.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...I.selection===void 0?{}:{selection:th(I.selection)}}}if(y.provider==="git"){if(v||E)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...w?{gitSelection:w}:{}}}else{if(w)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(v&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...v?{physicalSelection:v}:{}}}}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=Se(t.limits,"Native content snapshot limits");Ee(n,Ob,"Native content snapshot limits");let r={maxFiles:wi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:wi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:wi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:wi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:wi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=Se(t.policy,"Native snapshot policy");if(Ee(y,$b,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=hh({include:y.include,exclude:y.exclude,hash:y.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(mk),s=t.omitted.map(vk),c=Je(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:gk(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>r.maxFileBytes)||o.reduce((y,w)=>y+w.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>kc||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=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!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let g=s.filter(y=>y.reason==="physical-enumeration-limit"),S=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...g,...S])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",b=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let C={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(Cc(C)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return C}async function mh(e,t,i={}){let n=Bt(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=H.resolve(e.projectRoot),a=ah(i),o=oh(i.gitSelectionLimits),s=await lh(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(fh(s).filter(v=>An(e,v))),l=[...s.gitlinks].filter(v=>c.has(v)),u=[...s.nestedRepositories].filter(v=>An(e,v)),d=(v,E)=>E.some(I=>v===I||v.startsWith(`${I}/`)),f=v=>d(v,l),p=v=>d(v,u),m=[...n.entries.map(v=>v.path),...n.omitted.flatMap(v=>v.type==="directory"?[v.path,`${v.path}/`]:[v.path])].filter(v=>!c.has(v)&&!f(v)&&!p(v)),h=await tk(a,r,m),g=n.entries.filter(v=>!f(v.path)&&!p(v.path)&&An(e,v.path)&&(c.has(v.path)||!h.has(v.path)));await uh(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let v of l)S.push({path:v,size:null,type:"directory",reason:"legacy-gitlink-boundary"});g.sort((v,E)=>v.path.localeCompare(E.path,"en"));let N=n.omitted.filter(v=>f(v.path)||p(v.path)||!An(e,v.path)?!1:h.has(v.path)?c.has(v.path)||[...c].some(E=>E.startsWith(`${v.path}/`)):!0);for(let v of S)N.some(E=>E.path===v.path&&E.reason===v.reason)||N.push(v);N.sort((v,E)=>v.path.localeCompare(E.path,"en"));let k=n.omissionOverflow?.count??0,b=n.omissionOverflow?.hash??U("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,b=Tn(b,"git-selection",{source:"git-selection",...s.overflow}));let C=v=>{k+=1,b=Tn(b,"omission",v)};for(;N.length>kc;){let v=Ea(N);if(v===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");C(v)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:N.length+k===0,entries:g,omitted:N,omittedCount:N.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:k}}:{}}),w=y();for(;Cc(w)>n.limits.maxManifestBytes;){let v=Ea(N);if(v===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");C(v),w=y()}return Bt(w)}function yk(e,t){if(!_b.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=H.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return H.join(i,"runtime","baseline-manifest.json")}async function vh(e,t={}){let i={maxFiles:t.limits?.maxFiles??ba.maxFiles,maxFileBytes:t.limits?.maxFileBytes??ba.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??ba.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??ba.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=hh(t.policy),r=ah({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=oh(t.gitSelectionLimits),o=Zb(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 X.realpath(s),l=H.resolve(e.nativeRoot),u=await X.realpath(l),d=H.resolve(e.configFile),f=H.join(s,".comet","current-change.json"),p=uk(s,t.denylist??[]),m=[],h=[],g=new Map,S=new Map,N=0,k=0,b=U("comet.native.snapshot-omission-overflow.v1"),C=0,y=!1,w=null,v=x=>{k+=1,b=Tn(b,"omission",x)},E=x=>{if(N+=1,h.length<kc){h.push(x);return}if(bc(x)){let A=Ea(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");v(A),h.push(x);return}v(x)},I=x=>{N+=x.count,k+=x.count,b=Tn(b,"git-selection",{source:"git-selection",...x})},J=x=>{k+=1,b=Tn(b,"manifest-entry",{reason:"manifest-size",entry:x})},L=async(x,A)=>{m.push(x),C+=x.size,g.set(x.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},W=(x,A)=>{let T=m.findIndex(Y=>Y.path===x);if(T<0)return;let[$]=m.splice(T,1);C-=$.size,g.delete(x),E(A)},K=async(x,A,T,$)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let Y;try{Y=await X.realpath(x)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:T.size,type:"file",reason:ie(P)?"changed-during-read":"unreadable"});return}if(!_(r)||!V(c,Y)||yt(u,Y))return;if(m.length>=i.maxFiles){E({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){E({path:A,size:T.size,type:"file",reason:"file-size"});return}if(C+T.size>i.maxTotalBytes){E({path:A,size:T.size,type:"file",reason:"total-size"});return}let M,j,Q;try{if(M=await pk(Y,T.size,T,r),M.status==="budget-exhausted"||!_(r))return;if(M.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(Q=await X.realpath(x),!_(r)))return;j=await X.lstat(x)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:T.size,type:"file",reason:ie(P)?"changed-during-read":"unreadable"});return}if(_(r)){if(M.bytes!==T.size||Q!==Y||!gt(T,M.finalStat)||!gt(M.finalStat,j)||!j.isFile()||j.isSymbolicLink()||j.size!==T.size||j.mtimeMs!==T.mtimeMs||j.ctimeMs!==T.ctimeMs){E({path:A,size:j.isFile()?j.size:null,type:j.isFile()?"file":"other",reason:"changed-during-read"});return}_(r)&&await L({path:A,hash:M.hash,size:j.size,type:"file",...$===void 0?{}:{gitObjectId:$}},{kind:"file",target:x,realTarget:Y,stat:j})}},Me=async(x,A,T)=>{if(!_(r))return;let $,Y,M;try{if($=await X.readlink(x,{encoding:"buffer"}),!_(r)||(M=await X.lstat(x),!_(r)))return;Y=await X.readlink(x,{encoding:"buffer"})}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:null,type:"other",reason:ie(P)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!M.isSymbolicLink()||!gt(T,M)||M.mtimeMs!==T.mtimeMs||M.ctimeMs!==T.ctimeMs||!$.equals(Y)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=$.byteLength;if(m.length>=i.maxFiles){E({path:A,size:j,type:"other",reason:"file-count"});return}if(j>i.maxFileBytes){E({path:A,size:j,type:"other",reason:"file-size"});return}if(C+j>i.maxTotalBytes){E({path:A,size:j,type:"other",reason:"total-size"});return}let Q=Ca("sha256").update("symlink\0").update($).digest("hex");_(r)&&await L({path:A,hash:Q,size:j,type:"file"},{kind:"symlink",target:x,rawTarget:$,stat:M})},Le=async()=>{for(let[x,A]of[...g]){if(!_(r))return;if(A.kind==="file"){let j,Q;try{if(j=await X.realpath(A.target),!_(r))return;Q=await X.lstat(A.target)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;W(x,{path:x,size:null,type:"file",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(j!==A.realTarget||!Q.isFile()||Q.isSymbolicLink()||!gt(A.stat,Q)||Q.size!==A.stat.size||Q.mtimeMs!==A.stat.mtimeMs||Q.ctimeMs!==A.stat.ctimeMs)&&W(x,{path:x,size:Q.isFile()?Q.size:null,type:Q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let j,Q;try{if(j=await X.lstat(A.target),!_(r))return;Q=await X.readlink(A.target,{encoding:"buffer"})}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;W(x,{path:x,size:null,type:"other",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!gt(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Q))&&W(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,$;try{if(T=await X.realpath(A.target),!_(r))return;$=await X.lstat(A.target)}catch{if(!_(r))return;W(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&$.isDirectory()&&!$.isSymbolicLink()&&gt(A.stat,$)&&V(c,T)&&!yt(u,T))){W(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!_(r))return;M=await Qf(r,T)}catch(j){if(yi(j))throw j;W(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;M.dirty?W(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&W(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of S){if(!_(r))return;try{let T=await X.lstat(A);if(!_(r))return;E({path:x,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!_(r))return;if(ie(T))continue;if(!ne(T))throw T;E({path:x,size:null,type:"file",reason:"unreadable"})}}},me=await lh(r,e,a,t.gitSelectionHooks);if(me===null){let x=await Yf({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let $ of x.records){if($.type!=="file"&&$.type!=="symlink"||g.has($.path))continue;if(_e(r)<1)break;if(!eh(n,$.path,r))continue;if(_e(r)<1)break;let Y=H.resolve(s,...$.path.split("/")),M;try{M=await X.lstat(Y)}catch(j){if(!_(r))break;if(!ne(j)&&!ie(j))throw j;E({path:$.path,size:null,type:"file",reason:ie(j)?"changed-during-read":"unreadable"});continue}if(_e(r)<1)break;if($.type==="symlink"&&M.isSymbolicLink()){if(await Me(Y,$.path,M),_e(r)<1)break;continue}if($.type!=="file"||!M.isFile()||M.isSymbolicLink()){E({path:$.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await K(Y,$.path,M),_e(r)<1)break}_e(r)>=1&&await Le();let A=await Yf({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=ck(x.evidence,A.evidence);w=T.evidence;for(let $ of[...x.omissions,...A.omissions,...T.omissions])h.some(Y=>Y.path===$.path&&Y.reason===$.reason)||E($)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,T=!1;if(x){let P=Bt(x);for(let Z of P.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);T=A.size>0}let $=new Set,Y=!0;try{let P=await xn(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)T=!1,Y=!1,A.clear();else for(let Z of P.records){let ee=Sa(Z),ce=ee.indexOf(" "),oe=ce<0?null:Ni(ee.slice(ce+1));if(ce!==1||oe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&$.add(oe)}}catch(P){if(yi(P))throw P;T=!1,Y=!1,A.clear()}let M=new Set;try{let P=await ka(r,s,["ls-files","--modified","-z"],Nc);for(let Z of P.toString("utf8").split("\0")){let ee=Ni(Z);ee!==null&&M.add(ee)}}catch{T=!1,Y=!1,A.clear()}let j=new Set,Q=new Set;for(let P of fh(me)){if(g.has(P)||!An(e,P))continue;if(_e(r)<1)break;if(!eh(n,P,r))continue;if(_e(r)<1)break;let Z=H.resolve(s,...P.split("/"));if(Z===d||Z===f||p.some(ve=>yt(ve,Z)))continue;if(me.gitlinks.has(P)){if(m.length>=i.maxFiles){E({path:P,size:0,type:"file",reason:"file-count"});continue}let ve,ir;try{[ve,ir]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ir.isSymbolicLink()||!ir.isDirectory()||!V(c,ve)||yt(u,ve)){E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ni=await Qf(r,ve);if(ni.dirty){E({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await L({path:P,hash:ni.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:ve,stat:ir,hash:ni.hash})}catch(ni){if(yi(ni))throw ni;E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await X.lstat(Z)}catch(ve){if(ie(ve)&&me.tracked.has(P)){S.set(P,Z);continue}if(!ne(ve)&&!ie(ve))throw ve;E({path:P,size:null,type:"file",reason:ie(ve)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await Me(Z,P,ee);continue}if(!ee.isFile()){me.nestedRepositories.has(P)||E({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let ce=me.trackedObjectIds.get(P),oe=ce?A.get(P):void 0;if(T&&oe?.gitObjectId!==void 0&&oe.gitObjectId===ce&&!$.has(P)&&!M.has(P)){if(m.length>=i.maxFiles){E({path:P,size:oe.size,type:"file",reason:"file-count"});continue}if(oe.size>i.maxFileBytes){E({path:P,size:oe.size,type:"file",reason:"file-size"});continue}if(C+oe.size>i.maxTotalBytes){E({path:P,size:oe.size,type:"file",reason:"total-size"});continue}m.push({...oe}),C+=oe.size,j.add(P);continue}let Ll=Y&&!$.has(P)&&!M.has(P)?ce:void 0;await K(Z,P,ee,Ll),Ll!==void 0&&Q.add(P)}if(await Le(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await uh(r,e,a,me,t.gitSelectionHooks?.outputChunkBytes),j.size>0||T&&Q.size>0){let P=await ka(r,s,["ls-files","--modified","-z"],Nc),Z=new Set;for(let ee of P.toString("utf8").split("\0")){let ce=Ni(ee);ce!==null&&Z.add(ce)}for(let ee of j){if(!Z.has(ee))continue;let ce=m.find(oe=>oe.path===ee);W(ee,{path:ee,size:ce?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Q){if(!Z.has(ee))continue;let ce=m.find(oe=>oe.path===ee);ce&&delete ce.gitObjectId}}for(let P of me.omissions)E(P);me.overflow&&I(me.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let uv=me===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...me.evidence?{gitSelection:me.evidence}:{}},Ml=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:uv,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:k}}:{}}),mo=Ml();for(;Cc(mo)>i.maxManifestBytes;){if(h.filter(A=>!bc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let $=Ea(h);if($===null)break;v($)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))N+=1,J(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");mo=Ml()}return mo}async function Rc(e,t,i={}){let r=(await Mt(e.projectRoot))?.native.snapshot??fc;return vh(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 Pa(e,t){let i=yk(e,t);await G(e.nativeRoot,i);try{let n=await Vf({root:e.nativeRoot,file:i,maxBytes:Ib,label:"Native baseline snapshot manifest"});return Bt(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Hk}from"crypto";import Tc from"path";var Ce=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 Aa,promises as je}from"node:fs";import Oe from"node:path";import{TextDecoder as Ik}from"node:util";import Pk from"path";var Ck=vo(ia(),1);var gh=(e,t)=>{let i=e[t];return i==null?null:String(i)};function _n(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 In(e,t){let i=_n(e,t);if(Pk.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 Ak(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 wh(e){if(!e.run_id)return null;let t=_n(e,"run_id"),i=_n(e,"skill"),n=_n(e,"skill_version"),r=_n(e,"skill_hash"),a=In(e,"pending_ref"),o=In(e,"trajectory_ref"),s=In(e,"context_ref"),c=In(e,"artifacts_ref"),l=In(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:gh(e,"current_step"),iteration:u,pending:gh(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Ak(e)}}var HI=256*1024;var xk=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Tk(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=wh(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Pc(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=>!xk.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 Tk(t)}var ki={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 Ta(e,t){let i=Oe.relative(e,t);return i===""||!Oe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Oe.sep}`)}function _k(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function xa(e,t){return q({...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 jk(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ia(e,t,i){let n=Ce[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Oe.resolve(e),a=Oe.resolve(r,...n.split("/"));if(!Ta(r,a))throw new Error("Native Run path must stay inside its change");return a}async function yh(e){let t=await je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ok(e,t){let i=Oe.resolve(e),n=Oe.resolve(t);if(!Ta(i,n))throw new Error("Native Run path is outside its change");let r=[await yh(i)],a=i;for(let o of Oe.relative(i,n).split(Oe.sep).filter(Boolean)){a=Oe.join(a,o);let s;try{s=await yh(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ta(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function Nh(e){for(let t of e){let i=await je.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!jk(t,i)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function $k(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 _a(e,t,i,n,r){let a=await Ok(e,Oe.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await je.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}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=_k(o),c=await je.realpath(t);if(!Ta(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Aa.O_RDONLY:Aa.O_RDONLY|Aa.O_NOFOLLOW|Aa.O_NONBLOCK,u;try{u=await je.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),je.lstat(t),je.realpath(t)]);if(await Nh(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!xa(s,d)||!xa(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await $k(u,i,n);await r?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([u.stat(),je.lstat(t),je.realpath(t)]);if(await Nh(a),!g.isFile()||g.isSymbolicLink()||S!==c||!xa(s,h)||!xa(s,g))throw new Error(`${n} changed while reading`);let N;try{N=new Ik("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${n} is not valid UTF-8`,{cause:k})}return{text:N,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function bh(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Ac(e){return Pc(e)}async function Si(e,t){let i=Ia(e,"stateRef"),n=await _a(e,i,ki.runStateBytes,"Native Run state",t);return n?Pc(bh(n.text,"Native Run state")):null}async function qt(e,t,i){let n=Ia(e,"trajectoryRef",t),r=await _a(e,n,ki.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>ki.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ki.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 kh(e,t,i){return(await _a(e,Ia(e,"trajectoryRef",t),ki.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function ja(e,t,i){let n=await _a(e,Ia(e,"checkpointRef",t),ki.checkpointBytes,"Native Run checkpoint",i);return n?bh(n.text,"Native Run checkpoint"):null}var Fk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function xc(e){return Hk("sha256").update(e).digest("hex")}function Dk(e,t){if(!Fk.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Tc.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return Tc.join(i,"runtime","trajectory.jsonl")}function Mk(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 Lk(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 Bk(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=Mk(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(`
150
- `)])}catch(d){if(!Lk(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:xc(t),targetHash:xc(l),tailHash:xc(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function qk(e,t){let i=Dk(e,t);await G(e.nativeRoot,i);let n=Tc.join(e.changesDir,t),r=await kh(n,Ce.trajectoryRef);return r===null?{status:"clean",file:i}:Bk(i,Buffer.from(r))}async function Sh(e,t){let i=await qk(e,t);return"inspection"in i?i.inspection:i}import{createHash as zk}from"node:crypto";import{promises as $a}from"node:fs";import Nt from"node:path";import{execFileSync as Vk}from"child_process";import Oa from"path";function Ic(e,t){return Vk("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Wk(e,t){let i=Oa.normalize(e),n=Oa.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Eh(e){try{let t=Oa.resolve(Ic(e,["rev-parse","--show-toplevel"])),n=Ic(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?Oa.resolve(n.slice(9)):t,a=null;try{a=Ic(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Wk(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var jn=/^[a-f0-9]{64}$/u,Jk=16*1024,_c=process.platform,Gk=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Ei(e){return Gk.has(e)}function Ah(e,t){let i=Nt.relative(e,t);return Nt.isAbsolute(i)||i===".."||i.startsWith(`..${Nt.sep}`)?null:i.replaceAll("\\","/")||"."}function xh(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Th(e,t){if(e.length===0||xh(e)||e.includes("\\")||Nt.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=Nt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function jc(e,t){return zk("sha256").update(`${e}
151
- ${t}`).digest("hex")}async function Ch(e,t){let i=await $a.realpath(t),n=await $a.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=_c==="win32"?Nt.normalize(i).toLowerCase():i;return jc(e,`${r}
152
- ${n.dev}
153
- ${n.ino}
154
- ${n.birthtimeMs}`)}async function Rh(e,t){let i=await $a.realpath(t),n=await $a.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=_c==="win32"?Nt.normalize(i).toLowerCase():i;return jc(e,r)}function Uk(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 Ph(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||xh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ih(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Ph(e.changeBranch,"Native workspace change branch"),Ph(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 Ha(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"||!jn.test(String(t.projectRootId))||!jn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Uk(t.capturedAt),Th(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&&!jn.test(String(t.projectRootPathId))||a&&!jn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!jn.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(Ih(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 Kk(e,t){return Nt.join(e.changesDir,t,"runtime","workspace.json")}function Yk(e,t){let i=Ah(e.nativeRoot,Kk(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Th(i,"Native workspace file ref")}async function Xk(e,t){try{let i=await le({root:e.nativeRoot,ref:Yk(e,t),maxBytes:Jk});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Qk(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Ah(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([Ch("comet.native.workspace-project-root.v2",e.paths.projectRoot),Ch("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Rh("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Rh("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&&Ih(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:jc("comet.native.workspace-session.v2",`${i}
155
- ${n}
156
- ${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return Ha(c),c}async function bt(e,t){let i=await Xk(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Ha(i),i)}async function Fa(e){Ha(e.identity);let t=await Qk({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")),_c==="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 Da(e){if(Ha(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 Fa(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Eh(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 _h(e,t){let i=await bt(e,t);if(i===null)return null;let n=await Da({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var Wt="comet.native.v3",zt="comet.native.v2",Jt="comet.native.v1",Ci="comet.native.transition.v3",Ri="comet.native.transition.v2",On="comet.native.transition.v1";var Oh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],eS=new Set(Oh),$h=new Set([...Oh,"minimum_runtime_version","revision"]),tS=new Set([...$h,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),iS=new Set(["capability","operation","source","base_hash"]),nS=new Set(["shape","build","verify","archive"]),rS=new Set(["implicit","confirmed"]),aS=new Set(["pending","pass","fail"]),Ut="comet-state.yaml",$c=/^[a-f0-9]{64}$/u,Hh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ma=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"},Gt=class extends Error{constructor(i,n){super(i!==Wt||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"},La=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"},Ba=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"},qa=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"},D_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
157
- `);function Hn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Fh(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 Va(e){if(!Hh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function sS(e){if(!Hh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Dh(e,t){if(e.length===0||kt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cS(e,t){let i=Hn(e,`spec_changes[${t}]`);if(Fh(i,iS,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(sS(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"&&Dh(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"||!$c.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"||!$c.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 lS(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 Fc(e,t){if(Fh(e,t,Ut),typeof e.name!="string")throw new Error("Native change name is required");if(Va(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"||!nS.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&&!rS.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(cS),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"||!aS.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"&&Dh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lS(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 Fn(e){let t=Hn(e,Ut);if(t.schema!==Jt)throw new Error(`Expected ${Jt}`);return{schema:Jt,...Fc(t,eS)}}function $n(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Oc(e,t,i){if(e===null)return null;let n=typeof e=="string"?oS.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 uS(e){if(e==null)return null;if(typeof e!="string"||!$c.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function dS(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 Dn(e){let t=Hn(e,Ut);if(t.schema!==zt)throw new Error(`Expected ${zt}`);if($n(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${zt} minimum_runtime_version must be 2`);return{schema:zt,minimum_runtime_version:2,revision:$n(t.revision,"Native v2 revision"),...Fc(t,$h)}}function Kt(e){let t=Hn(e,Ut);if(t.schema!==Wt){if(t.schema===Jt||t.schema===zt){let o=t.schema===Jt?Fn(t):Dn(t);throw new Ma(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=$n(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 n=$n(t.revision,"Native revision"),r=Fc(t,tS),a=uS(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Wt,minimum_runtime_version:3,revision:n,verification_protocol:dS(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Oc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Oc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Oc(t.partial_allowance,"Native partial_allowance","allowances")}}function fS(e){let t=Hn(e,Ut);if(t.schema===Jt){let r=Fn(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Wt}`}}if(t.schema===zt){let r=Dn(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Wt}`}}if(t.schema!==Wt){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 Gt(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=$n(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 n=Kt(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function F(e,t){Va(t);let i=kt.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Wa(e,t){let i=kt.join(F(e,t),"runtime","schema-migration.json");await G(e.nativeRoot,i);try{return await jh.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Mh(e,t){let i=kt.join(F(e,t),"runtime","checkpoint-journal.json");await G(e.nativeRoot,i);try{return await jh.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var hS=256*1024;async function pS(e,t=kt.dirname(e)){let i=kt.relative(t,e).split(kt.sep).join("/"),n=await le({root:t,ref:i,maxBytes:hS}),r=(0,Hc.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 Dc(e,t){let i=kt.join(F(e,t),Ut);await G(e.nativeRoot,i);let n=fS(await pS(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Wa(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 mS(e,n.state),n)}async function mS(e,t){if(await Pa(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function St(e,t){let i=await Dc(e,t);if(i.status==="migration-required")throw new Ma(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Gt(i.schema,i.minimumRuntimeVersion);return await _h(e,t),i.state}var Bh=["Outcome","Scope","Non-goals","Acceptance examples"],vS=[...Bh,"Constraints and invariants","Decisions","Open questions","Verification expectations"],gS=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],qh={maxFileBytes:wn};function Vh(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
158
- `).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 wS(e,t){let i=Lh.resolve(e,...t.split(/[\\/]/u));if(!V(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Mc.realpath(e),r=await Mc.realpath(i);if(!V(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Mc.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Mn(e){return{valid:e.length===0,findings:e}}async function Lc(e,t){let i=[],n;try{n=(await le({root:e,ref:t,maxBytes:qh.maxFileBytes})).text}catch(o){return Mn([{code:"brief-missing",message:o.message,path:t}])}let r=Vh(n);for(let o of vS)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Bh)(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}),Mn(i)}async function Bc(e,t){let i=[],n;try{n=(await le({root:e,ref:t,maxBytes:qh.maxFileBytes})).text}catch(a){return Mn([{code:"verification-missing",message:a.message,path:t}])}let r=Vh(n);for(let a of gS)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 Mn(i)}function za(e,t){return Lh.join(e.specsDir,t,"spec.md")}async function Wh(e,t){let i=[],n=F(e,t.name);for(let r of t.spec_changes){let a=za(e,r.capability),o=null;try{await G(e.nativeRoot,a),o=await vc(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(r.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${r.capability}`,path:a}),r.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${r.capability}`,path:a}),r.operation!=="create"&&o!==null&&o!==r.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${r.capability}: expected ${r.base_hash}, actual ${o}`,path:a}),r.source)try{await wS(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Mn(i)}import zh from"node:path";import{createHash as yS}from"crypto";function $e(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function NS(e,t){t.has(e)&&$e("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)||$e("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&$e("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&$e("symbol properties are not supported"),`[${e.map(n=>qc(n,t)).join(",")}]`}finally{t.delete(e)}}function bS(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&$e("only plain objects are supported"),t.has(e)&&$e("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&$e("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))&&$e("accessor properties are not supported"),`${JSON.stringify(o)}:${qc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function qc(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)||$e("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?NS(e,t):bS(e,t);case"bigint":case"function":case"symbol":case"undefined":return $e(`${typeof e} values are not supported`)}return $e("unsupported value type")}function Ln(e){return qc(e,new Set)}function O(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return yS("sha256").update(`${e}
159
- ${Ln(t)}`).digest("hex")}var kS="comet.native.acceptance.v1",SS=/^acceptance-[a-f0-9]{64}$/u,ES=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),CS=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,RS=/^[a-f0-9]{64}$/u,PS=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function AS(e,t){return e<t?-1:e>t?1:0}var Xe=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Bn=Object.freeze({maxCriteria:1024}),Jh="<!-- comet-native:acceptance-evidence:start -->",Gh="<!-- comet-native:acceptance-evidence:end -->";function Uh(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",n=0;for(let r of e){let a=Buffer.byteLength(r,"utf8");if(n+a>t)break;i+=r,n+=a}return{value:i,truncated:!0}}function Kh(e,t){let i=t.toString(36),n=O("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function xS(e){if(!RS.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=PS.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==O("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function TS(e,t){let i=Uh(e.text,Xe.maxTextBytes),n=e.context.slice(0,Xe.maxContextItems).map(r=>Uh(r,Xe.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:n.map(r=>r.value),text:i.value,contextTruncated:e.context.length>n.length||n.some(r=>r.truncated),textTruncated:i.truncated,verificationStatus:t}}function Xh(e){let t=xS({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(AS),r=n.slice(0,Xe.maxFailedCheckIds),a=e.criteria.slice(t,t+Xe.maxItems);for(let c of a){let l=[...i,TS(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:u<e.criteria.length?Kh(e.acceptanceHash,u):null,limits:{...Xe}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Xe.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:o<e.criteria.length?Kh(e.acceptanceHash,o):null,limits:{...Xe}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Xe.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function zc(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 Vc(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 Yh(e){return e.includes("-->")||e.includes("--!>")}function*Pi(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
160
- `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
161
- `,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=Vc(l,t);else if(i)Yh(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=Vc(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Yh(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&r.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(n=p[1])}}}if(c===-1)break;o=c+1}}function IS(e){return[...Pi(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Wc(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function _S(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Jc(e,t,i,n=[]){let r=Wc(i),a=t.replaceAll("\\","/").trim(),o=n.map(Wc);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-${O(kS,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function Gc(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 jS(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of Pi(e)){r=s+1;let c=o?zc(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 Qh(e,t="brief.md",i=Bn.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=jS(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of Pi(e)){if(u<n.start||u>=n.end)continue;let d=l?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(d===null)continue;let f=d[1].length;r=r===null?f:Math.min(r,f)}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 Pi(e)){if(u<n.start||u>=n.end)continue;let d=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;d&&d[1].length===r?(s(),o=[d[2]]):o!==null&&o.push(c)}return s(),Gc(a.map(c=>Jc("brief-example",t,c.join(`
162
- `))),"Brief")}function Zh(e,t="spec.md",i=Bn.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(Jc("spec-scenario",t,[a.title,...a.body].join(`
163
- `),a.context)),a=null}};for(let{line:s,body:c}of Pi(e)){let l=c?zc(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 d=Wc(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:d,body:[],context:r.map(f=>f.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(),Gc(n,"Specification")}function ep(e,t="spec.md",i=Bn.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(Jc("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 Pi(e)){let d=u?zc(l):null;if(d){for(s(),a!==null&&d.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=d.level;)r.pop();r.push(d),/^Scenario\s*:/iu.test(d.text)&&(a=d.level);continue}let f=l.trim();if(!u||a!==null||c()){s();continue}if(f.length===0||Vc(l,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){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(f)){s(),o={parts:[f],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[f],context:r.map(m=>m.text)}:o.parts.push(f)}return s(),Gc(n,"Specification mandatory requirements")}function OS(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||_S(i)||zh.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=zh.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(!CS.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function $S(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=>!ES.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function tp(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=$S(i,n),a=r.acceptance_id;if(typeof a!="string"||!SS.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 OS(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 ip(e){let t=IS(e);if(t.some(({line:l,body:u})=>!u&&(l===Jh||l===Gh)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===Jh?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===Gh?[d]:[]);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(`
164
- `).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=tp(o),c=HS(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function HS(e){let t=tp([...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 np from"node:path";var FS="comet.native.contract.v1",DS="comet.native.acceptance-set.v1",rp=/^[a-f0-9]{64}$/u,qn={maxAcceptanceCriteria:Bn.maxCriteria};function ap(e,t){let i=np.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})||np.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 op(e){return O("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
165
- `))}function MS(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(rp))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(rp))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=ap(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:op(e.markdown)},markdown:e.markdown}}function LS(e,t){return sp(e.id,t.id)}function sp(e,t){return e<t?-1:e>t?1:0}function cp(e){let t=ap(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(MS).sort((d,f)=>sp(d.snapshot.capability,f.snapshot.capability)),n=i.map(({snapshot:d})=>d.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=Qh(e.briefMarkdown,t,qn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Zh(f,d.source,qn.maxAcceptanceCriteria-a.length)),a.push(...ep(f,d.source,qn.maxAcceptanceCriteria-a.length)));if(a.sort(LS),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>qn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${qn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:op(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=O(DS,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:O(FS,u)}}var Ja={maxSpecs:64,maxFileBytes:wn,maxTotalBytes:4*1024*1024};async function Ai(e){if(e.specChanges.length>Ja.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await le({root:e.changeDir,ref:e.briefRef,maxBytes:Ja.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 le({root:e.changeDir,ref:r.source,maxBytes:Ja.maxFileBytes});if(i+=a.size,i>Ja.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:cp({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import BS from"path";var Uc="comet.selection.v2",qS=16*1024;function up(e){return BS.join(e,".comet","current-change.json")}function VS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function lp(e){return e===null||typeof e=="string"}function WS(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(!VS(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&&!lp(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Uc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Uc)throw new Error(`current change selection schema must be ${Uc}`);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(!lp(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 dp(e){let t;try{let n=up(e),{bytes:r}=await mi(n,qS,{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",...WS(t)}}var mj=16*1024;async function fp(e){let t=await dp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Va(t.selection.change),t.selection)}import zS from"path";function Kc(e,t){return zS.resolve(e,...t.split(/[\\/]/u))}async function hp(e,t){let i=[],n=F(e,t.name),r=Kc(n,Ce.stateRef),a;try{a=await Si(n)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:r}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:r}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:r}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:r}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:r}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:r});let o=Kc(n,a.trajectoryRef),s=await Sh(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await qt(n,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Kc(n,a.checkpointRef);try{let u=await ja(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import zE from"path";import{isDeepStrictEqual as Xp}from"util";var JS=/\b(Bearer|Basic)\s+[^\s"']+/giu,GS=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,US=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,KS=/\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,YS=/("(?:[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,XS=/(["'])((?:[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,QS=/\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 He(e){return e.replace(JS,"$1 [REDACTED]").replace(GS,"[REDACTED PRIVATE KEY]").replace(US,"$1[REDACTED]@").replace(KS,"[REDACTED TOKEN]").replace(YS,'$1"[REDACTED]"').replace(XS,"$1$2$1$3$4[REDACTED]$4").replace(QS,"$1$2[REDACTED]")}var xi={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var ZS=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function eE(e,t){return e<t?-1:e>t?1:0}function tE(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"||!ZS.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(eE)}function Yc(e=[]){return tE(e,"Native repair failed check IDs",xi.maxFailedCheckIds,!0)}function pp(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function iE(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:pp(e.failedAcceptanceIds,t.failedAcceptanceIds)&&pp(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Xc(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(iE(n,a))break;i+=1,n=a}return i}import Tp from"node:path";import{createHash as bp}from"node:crypto";import mp from"path";var Qc="comet.native.implementation-scope.v2",kp="comet.native.content-snapshot-projection.v1",Vn="comet.native.content-snapshot-projection.v1",Sp="comet.native.implementation-scope.v2",nE="comet.native.unresolved-scope-id.v1",rE="comet.native.scope-detail-overflow.v1",aE="comet.native.snapshot-projection-overflow.v2",il=/^[a-f0-9]{64}$/u,Xt=1024*1024,oE=128,sE=128;function se(e,t){return e<t?-1:e>t?1:0}function Zc(e){if(!il.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cE(e,t){return e===t?0:e===null?-1:t===null?1:se(e,t)}function Ct(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=mp.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||mp.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Ep(e,t){return e==="."?e:Ct(e,t)}function Ti(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lE(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:Ct(e.path,`${t} path`),hash:e.hash,size:Ti(e.size,`${t} size`),type:"file"}}function uE(e,t){return{path:Ep(e.path,`${t} path`),size:e.size===null?null:Ti(e.size,`${t} size`),type:e.type,reason:e.reason}}function dE(e,t){return se(e.path,t.path)||se(e.hash,t.hash)||e.size-t.size}function fE(e,t){return se(e.path,t.path)||se(e.reason,t.reason)||se(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Wn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
166
- `,"utf8")}function Et(e,t,i){let n=`${t}
167
- ${Ln(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function hE(e){if(Wn(e)<=Xt)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=bp("sha256");a.update(`${aE}
168
- `),e.omissionOverflow&&Et(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,Et(a,"omission",f)},s=f=>{n+=1,r+=1,Et(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,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(;Wn(u)>Xt;){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 d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:r}}}function el(e){let t=Bt(e),i=t.entries.map((r,a)=>lE(r,`Snapshot entry ${a}`));if(i.sort(dE),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)=>uE(r,`Snapshot omission ${a}`));return n.sort(fE),hE({schema:kp,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 Ka(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:Ct(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)=>se(i.path,n.path)||se(i.kind,n.kind))}function Ya(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function vp(e){return e?{hash:e.hash,size:e.size}:null}function Cp(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:se(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:vp(c),after:vp(l)})}}function pE(e,t){return{...e,attributedTo:t.filter(i=>Ya(i,e.path))}}function Qe(e,t){return{id:`scope:${O(nE,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function mE(e,t){let i=t.omitted.map(n=>Qe({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(Qe({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Qe({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 gp(e,t){return mE(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function tl(e,t){return se(e.kind,t.kind)||se(e.source,t.source)||cE(e.path,t.path)||se(e.id,t.id)}function vE(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(tl)}function gE(e){return[...new Set(e.map((t,i)=>Ct(t,`Git path ${i}`)))].sort(se)}function Rp(e){if(typeof e.contractHash!="string"||!il.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Ka(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:gE(e.gitChangedPaths)}}}function wE(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Cp(e,t,d=>{let f=i.some(p=>Ya(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<oE){let p=pE(d,i),m=Wn(p);s+m<=Xt?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function Pp(e,t){return Qe({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 yE(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:Ti(Number(t[1]),"Scope overflow change count"),unresolved:Ti(Number(t[2]),"Scope overflow unresolved count"),unattributed:Ti(Number(t[3]),"Scope overflow unattributed count")},n=Yt(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Pp(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function NE(e){let t=bp("sha256");t.update(`${rE}
169
- `);let i=0;Cp(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){Et(t,"change",r);let a=0;for(let o of e.declaredArtifacts)Ya(o,r.path)&&(a+=1,Et(t,"change-attribution",o));Et(t,"change-end",{attributionCount:a}),a===0&&Et(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&&Et(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function Ap(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=wE(e,t,r,i.gitChangedPaths),s=O(Vn,e),c=O(Vn,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let v of w.omitted){if(l.length>=sE)break;l.push(Qe({kind:"snapshot-omission",source:y,path:v.path,evidence:{reason:v.reason,size:v.size,type:v.type}},`${y} snapshot omitted ${v.path}: ${v.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...gp("baseline",e),...gp("current",t),...o.totalChanges===0&&a===null?[Qe({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(i.gitChangedPaths===void 0)return;let y=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>y.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!y.has(w))}},p=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),v=w.filter(Le=>Le.attributedTo.length===0),E=o.totalChanges-w.length,I=o.totalUnattributed-v.length,J=u-y.detailedOmissionCount,L=I+J,W=[...v.map(Le=>Qe({kind:"unattributed-change",source:"implementation-scope",path:Le.path,evidence:{after:Le.after,before:Le.before,changeKind:Le.kind}},`Changed path is not covered by a declared artifact: ${Le.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||L>0?[Pp(y.overflowHash,{changes:E,unattributed:I,unresolved:L})]:[]],K=vE(W),Me=y.includeGitAdvisory?f():void 0;return{schema:Qc,contractHash:n,baselineProjectionRef:Zc(s),baselineProjectionHash:s,currentProjectionRef:Zc(c),currentProjectionHash:c,complete:K.length===0,declaredArtifacts:r,changes:w,unattributed:v,unresolvedScopes:K,noCodeReason:a,...Me?{gitAdvisory:Me}:{}}},m=o.candidates.length,h=l.length,g=i.gitChangedPaths!==void 0,S="0".repeat(64);for(;;){let y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:g,overflowHash:S});if(Wn({...y,scopeHash:S})<=Xt)break;if(g){g=!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 k=o.totalChanges>m||u>h?NE({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):S,b=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:g,overflowHash:k}),C={...b,scopeHash:O(Sp,b)};if(Wn(C)>Xt)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return C}function nl(e){let t=el(e.baseline),i=el(e.current),n=Rp(e);return{authority:n,baseline:t,current:i,scope:Ap(t,i,n)}}var bE=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Ze(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function et(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 Yt(e,t){if(typeof e!="string"||!il.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wp(e,t,i){let n=Zc(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function Ua(e,t){let i=Ze(e,"Native snapshot projection");if(et(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==kp)throw new Error("Native snapshot projection schema is invalid");let n=Bt({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=el(n);if(O(Vn,i)!==O(Vn,r))throw new Error("Native snapshot projection is not canonical");let a=O(Vn,r);if(t!==void 0&&Yt(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function rl(e,t){let i=Ze(e,`Declared artifact ${t}`);if(et(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Ct(i.path,`Declared artifact ${t} path`),kind:i.kind}}function yp(e,t){if(e===null)return null;let i=Ze(e,t);return et(i,["hash","size"],[],t),{hash:Yt(i.hash,`${t} hash`),size:Ti(i.size,`${t} size`)}}function Np(e,t){let i=Ze(e,`Implementation change ${t}`);if(et(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(rl),r=Ka(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=yp(i.before,`Implementation change ${t} before`),o=yp(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:Ct(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function kE(e,t){let i=Ze(e,`Unresolved scope ${t}`);et(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"?Ep(i.path,`Unresolved scope ${t} path`):Ct(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Ga(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)=>Ct(r,`${t} ${a}`)),n=[...new Set(i)].sort(se);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function Xa(e){let t=Ze(e,"Native implementation scope"),i=[...bE].filter(w=>w!=="gitAdvisory");if(et(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Qc)throw new Error("Native implementation scope schema is invalid");let n=Yt(t.contractHash,"Implementation scope contractHash"),r=Yt(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=wp(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=Yt(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=wp(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(rl);if(JSON.stringify(c)!==JSON.stringify(Ka(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Np),u=[...l].sort((w,v)=>se(w.path,v.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(v=>!d.has(`${v.kind}:${v.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(v=>Ya(v,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Np),p=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(kE),h=m.filter(w=>w.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=h[0]===void 0?null:yE(h[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...p.map(w=>Qe({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&S===null?[Qe({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")]:[]],k=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(tl))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(tl))||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 b;if(t.gitAdvisory!==void 0){let w=Ze(t.gitAdvisory,"Implementation scope Git advisory");if(et(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let v=Ga(w.changedPaths,"Git changed paths"),E=Ga(w.pathsPresentInSnapshotChanges,"Git present paths"),I=Ga(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),J=[...E,...I].sort(se),L=new Set(l.map(W=>W.path));if(JSON.stringify(J)!==JSON.stringify(v)||(g?.changes??0)===0&&E.some(W=>!L.has(W))||I.some(W=>L.has(W)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:v,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:I}}let C={schema:Qc,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...b?{gitAdvisory:b}:{}},y=Yt(t.scopeHash,"Implementation scope scopeHash");if(O(Sp,C)!==y)throw new Error("Implementation scope content hash mismatch");return{...C,scopeHash:y}}function SE(e){let t=Ze(e,"Native implementation scope authority");if(et(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(rl);if(JSON.stringify(i)!==JSON.stringify(Ka(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=Ga(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Rp({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 zn(e){let t=Ze(e,"Native implementation scope bundle");et(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=SE(t.authority),n=Ua(t.baseline),r=Ua(t.current),a=Xa(t.scope),o=Ap(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 xp(e){let t=Xa(e.scope);return zn({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}var _p=/^[a-f0-9]{64}$/u;var EE="comet.native.acceptance-trace.v2",CE="comet.native.partial-allowance.v1",RE="comet.native.verification-evidence.v2";function tt(e,t){if(!_p.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jp(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Op(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 al(e,t,i=2e3){let n=He(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function Jn(e,t){let i=Tp.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})||Tp.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 PE(e,t,i){let n=Jn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Ve(n),a=n.toLowerCase(),o=i?Jn(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 ol(e){let t=Jn(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 Ii(e,t){return e<t?-1:e>t?1:0}function Qa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Za(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 $p(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 Ip(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 AE(e){let t=Qa(e,"Native acceptance trace");if(Za(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"||!_p.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=Jn(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=Qa(o,`Native acceptance trace entry ${s}`);if(Za(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>ol(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ii))||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:Jn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:al(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Ii(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=tt(t.traceHash,"Native acceptance trace hash");if(O(EE,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Hp(e){let t=Qa(e,"Native partial allowance");if(Za(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(Ii))||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:Op(t.change),scopeHash:tt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:al(t.reason,"Partial allowance reason"),confirmedSummary:al(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:jp(t.sourceRevision),confirmedAt:$p(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=tt(t.allowanceHash,"Native partial allowance hash");if(O(CE,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function sl(e){let t=Qa(e,"Native verification evidence");if(Za(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=tt(t.implementationScopeHash,"Native verification implementation scope hash"),n=AE(t.acceptanceTrace),r=tt(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:tt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>ol(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ii)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(Ii);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>ol(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ii)))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:Op(t.change),sourceRevision:jp(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:tt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:Ip(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:PE(t.reportRef,"Native verification report ref"),reportHash:tt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:Ip(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:$p(t.createdAt,"Native verification timestamp")},d=tt(t.envelopeHash,"Native verification envelope hash");if(O(RE,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function cl(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 Fp="repairStagnation",ye={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},TE=/^[a-f0-9]{64}$/u;var IE=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),_E=["data","runId","sequence","timestamp","type"],Dp=["disposition","overrideSummaryHash","signatureHash"],jE=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Mp=12;function ul(e,t){return e<t?-1:e>t?1:0}function Lp(e,t,i){let n=Object.keys(e).sort(ul);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function eo(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 Gn(e,t){if(typeof e!="string"||!TE.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function OE(e){if(!Array.isArray(e)||e.length>xi.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(ul)}function Bp(e){if(typeof e!="string"||e.length===0||e.length>ye.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function ll(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>ye.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>ye.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${n} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>ye.maxTextCharacters&&(!r||e.length>ye.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>ye.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${n} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${n} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>ye.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>ll(s,t+1,i,`${n}[${c}]`));return}let a=eo(e,n),o=Object.keys(a);if(o.length>ye.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>ye.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>ye.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");ll(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function $E(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function HE(e,t,i){let n=eo(e,`Native repair trajectory event ${t+1}`);if(Lp(n,_E,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if($E(n.timestamp),typeof n.type!="string"||!IE.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(Bp(n.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let r={nodes:0,characters:0,ancestors:new Set};return ll(n.data,0,r,"Native trajectory event data"),eo(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function dl(e){let t=eo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(ul),n=i.length===Dp.length&&i.every((l,u)=>l===Dp[u]);n||Lp(t,jE,"Native repair trajectory projection");let r=Gn(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:Gn(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=Gn(t.contractHash,"Native repair trajectory contract hash"),s=OE(t.failedAcceptanceIds),c=Yc(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}}function FE(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function DE(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Mp;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Xc({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<xi.warningAtConsecutiveFailures?"continue":a<xi.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function ME(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Mp;if(n.length>=r)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||n.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function qp(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>ye.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Bp(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],n=null,r=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=HE(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>ye.maxTotalDataNodes||c>ye.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Gn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Gn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Fp)){if(n?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&r!==null&&p!==r||p===null&&(n?.disposition==="manual-stop"||n?.disposition==="hard-stop"))){i.length=0,n=null,r=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=dl(f[Fp]);if(FE(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&p!==null&&r!==null&&p!==r&&(i.length=0,o=0),p!==null&&(r=p),DE(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(n?.contractHash===null&&p!==null&&r!==null&&p!==r)throw new Error("Native repair override cannot cross implementation scope progress");ME(m,i,n);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(n=m,i.length>xi.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function Vp(e){return qp(e).history}function Wp(e){let t=qp(e).latestProjection;return t?{...t}:null}var _i={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:[]},fl=U("comet-native-runtime:v3:semantic-repair-budget"),LE=[{skillVersion:"2",skillHash:U("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:U("comet-native-runtime:v1")}];function zp(e){return e.skillVersion===_i.definition.metadata.version&&e.skillHash===fl||LE.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Jp(e){return U(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 Qp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],JE=new Set(Qp),Zp=new Set([...Qp,"minimum_runtime_version","revision"]),GE=new Set([...Zp,"operation"]),UE=512*1024,hl=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),KE=new Set([...hl,"implementationScopeHash","repairScopeHash","repairStagnation"]),pl=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 vl(e,t){return zE.join(F(e,t),"runtime","transition.json")}function io(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function gl(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 to(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ml(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=>!KE.has(u)),a=[...hl].find(u=>!Object.hasOwn(i,u)),o=hl.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(cl(i.summary,"Native transition journal event summary"),He(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&&(cl(i.noCodeReason,"Native transition journal event no-code reason"),He(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")?dl(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 YE(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 ml({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return ml(e,t)}function wl(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?YE(e.eventData,e.evidenceHash):ml(e.eventData,e.evidenceHash),r=Ac(e.nextRun),a=e.previousRun===null?null:Ac(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function Gp(e,t,i=!1){if(e.skill!==_i.definition.metadata.name||(i?!zp(e):e.skillVersion!==_i.definition.metadata.version||e.skillHash!==fl)||e.orchestration!==_i.definition.orchestration.mode||e.pendingRef!==Ce.pendingRef||e.trajectoryRef!==Ce.trajectoryRef||e.contextRef!==Ce.contextRef||e.artifactsRef!==Ce.artifactsRef||e.checkpointRef!==Ce.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Up(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 Kp(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 yl(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Gp(a,"next Run",n||r!==null),Kp(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(Gp(r,"previous Run",!0),Kp(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(!Xp(Up(r),Up(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function XE(e,t,i){return U(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function em(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Yp(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Nl(e,t,i,n,r=!1){let a=i.eventData,o=Yp(e),s=Yp(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&&Xp(e.spec_changes,t.spec_changes),l=Jp({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=XE(e.name,a.summary,t.spec_changes),l=U(`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 QE(e,t){let i=io(e);if(gl(i,GE),i.schema!==Ci)throw new Error(`Expected Native transition schema ${Ci}`);let n=to(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 ${Ci} minimum_runtime_version must be ${3}`);let r=to(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=wl(i,t),o=Kt(i.previousState),s=Kt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Nl(o,s,a,i.operation),yl(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Ci,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 ZE(e,t){let i=io(e);if(gl(i,JE),i.schema!==On)throw new Error(`Expected Native transition schema ${On}`);let n=wl(i,t,!0),r=Fn(i.previousState),a=Fn(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Nl(r,a,n,em(r,a,n.eventData),!0),yl(r,a,n,!0),{schema:On,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 eC(e,t){let i=io(e);if(gl(i,Zp),i.schema!==Ri)throw new Error(`Expected Native transition schema ${Ri}`);if(to(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ri} minimum_runtime_version must be 2`);let r=to(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=wl(i,t,!0),o=Dn(i.previousState),s=Dn(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Nl(o,s,a,em(o,s,a.eventData),!0),yl(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ri,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 tC(e,t){let i=io(e);if(i.schema===Ci)return{status:"current",journal:QE(i,t)};if(i.schema===On)return{status:"migration-required",journal:ZE(i,t)};if(i.schema===Ri)return{status:"migration-required",journal:eC(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function iC(e,t){let i=vl(e,t);await G(e.nativeRoot,i);try{let n=await Ye({root:e.nativeRoot,file:i,maxBytes:UE,label:`Native transition journal ${t}`});return tC(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function tm(e,t){let i=await iC(e,t);if(!i)return null;if(i.status==="migration-required")throw new pl(t);return i.journal}var nC=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rC(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 im(e){let i=(e.findings??[]).filter(u=>!Ei(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||nC.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:rC(e.state)}}import Un from"path";var nm=8,aC={"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function oC(e){let t=aC[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Ei(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function sC(e,t,i){if(!i.path)return null;let n;if(Un.isAbsolute(i.path)?n=Un.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=Un.resolve(F(e,t.name),...i.path.split(/[\\/]/u)):n=Un.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,n))return null;let r=Un.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function cC(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function rm(e){return e.findings.map(t=>{let i=oC(t.code);return{code:t.code,message:t.message,severity:i.severity,path:sC(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:cC(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let n={error:0,warning:1,info:2};return n[t.severity]-n[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function am(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,nm),truncated:t.length>nm}}import hm from"path";import ji from"path";var Pt={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Oi=/^[a-f0-9]{64}$/u;function no(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ro(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 Rt(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 om(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function bl(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function lC(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||ji.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=ji.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function sm(e,t){return ji.join(F(e,t),"runtime","checkpoints","progress.json")}function Kn(e,t){return ji.join(F(e,t),"runtime","checkpoint-journal.json")}function cm(e,t,i){if(!Oi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return ji.join(F(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function uC(e){if(!Oi.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function kl(e,t,i){let n=await Ye({root:e,file:t,maxBytes:Pt.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function dC(e,t){let i=no(e,`checkpoint manifest artifact ${t}`);ro(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=lC(Rt(i.path,`checkpoint artifact ${t} path`,4096)),r=Ve(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Oi.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:bl(i.size,`checkpoint artifact ${t} size`)}}function Sl(e,t){let i=no(e,"Native checkpoint manifest");if(ro(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>Pt.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(dC),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=bl(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>Pt.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 lm(e){return U(JSON.stringify(Sl(e,e.change)))}function um(e,t){let i=no(e,"Native progress checkpoint");if(ro(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=om(i.previousRevision,"Native checkpoint previousRevision"),a=om(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Rt(i.manifestHash,"Native checkpoint manifestHash",64);if(!Oi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=uC(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Rt(i.inputHash,"Native checkpoint inputHash",64);if(!Oi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Rt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=bl(i.artifactCount,"Native checkpoint artifactCount");if(u>Pt.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Rt(i.summary,"Native checkpoint summary"),f=Rt(i.nextAction,"Native checkpoint nextAction");if(He(d)!==d||He(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Rt(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function fC(e,t){let i=no(e,"Native checkpoint journal");if(ro(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=Kt(i.previousState),r=Kt(i.nextState),a=um(i.checkpoint,t),o=Sl(i.manifest,t),s=Rt(i.inputHash,"Native checkpoint journal inputHash",64),c=U(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Oi.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!==lm(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 hC(e,t,i){let n=ji.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,n)||V(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=Qs(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await Ye({root:e.projectRoot,file:n,maxBytes:Pt.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function pC(e,t){let i=sm(e,t);await G(e.nativeRoot,i);try{return um(await kl(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function mC(e,t,i){let n=cm(e,t,i);await G(e.nativeRoot,n);let r=await kl(e.nativeRoot,n,"Native checkpoint manifest"),a=Sl(r,t);if(dm(e,a),lm(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function El(e,t){let i=Kn(e,t);await G(e.nativeRoot,i);try{let n=fC(await kl(e.nativeRoot,i,"Native checkpoint journal"),t);return dm(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function dm(e,t){for(let i of t.artifacts){let n=Qs(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function fm(e){let t;try{t=await pC(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:sm(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],n=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let r=null;try{r=await mC(e.paths,e.name,t.manifestHash);let a=U(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:r.artifacts}));if(t.inputHash!==a||t.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of r.artifacts)try{let s=await hC(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),n.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:cm(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}var pm=240,mm=8,ao=50;function vm(e){let t=Array.from(e);return t.length<=pm?e:`${t.slice(0,pm-1).join("")}…`}function vC(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function gC(e){let t=[...new Set(e.map(vC))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,mm),reasonCount:e.length,codesTruncated:t.length>mm};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,ao),reasonsTruncated:e.length>ao}}}async function gm(e){let t=null;try{let s=await El(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Kn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Kn(e.paths,e.state.name)}}let i=await fm({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=gC(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Pt.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:vm(i.checkpoint.summary),nextAction:vm(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:hm.relative(e.paths.projectRoot,hm.join(F(e.paths,e.state.name),...i.checkpoint.manifestRef.split("/"))).replaceAll("\\","/"),artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Pt.maxArtifacts}}import{promises as nP}from"node:fs";import Xm from"node:path";import wm from"node:path";var wC="comet.native.archive-preflight.v1",yC="comet.native.archive-preflight.v1",NC="comet.native.archive-operation.v1",bC=/^[a-f0-9]{64}$/u,ym=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function oo(e,t){return e<t?-1:e>t?1:0}function SC(e,t){if(typeof e!="string"||!bC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function it(e,t){return e===null?null:SC(e,t)}function EC(e,t){let i=wm.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||wm.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 CC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function RC(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 PC(e,t){if(!ym.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=it(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=it(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=it(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 AC(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:it(e.contractHash,"Native archive contract hash"),acceptanceHash:it(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:it(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:it(e.reportHash,"Native archive report hash"),envelopeHash:it(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:it(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 xC(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!kC.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(oo);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function TC(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(oo)}function Nm(e){if(!ym.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(PC).sort((l,u)=>oo(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:O(NC,l)})),n=AC(e.evidence),r=RC(e.workspace),a=[...new Set([...xC(e.findingCodes??[]),...TC({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(oo),o=CC(e.revision),s=EC(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:wC,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:O(yC,c)}}import{createHash as IC}from"node:crypto";import bm from"node:path";var _C="comet.native.conflict-radar.v1",pe=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}),jC="comet.native.conflict-radar.v1",OC="comet.native.conflict-radar-signals.v1",$C=/^[a-f0-9]{64}$/u,Em=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,HC=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),FC=new Set(["capability","operation","baseHash"]),DC=new Set(["path","kind"]);function $i(e,t){return e<t?-1:e>t?1:0}function Cl(e){return Buffer.byteLength(e,"utf8")}function Rl(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 Pl(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(Cl(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function MC(e,t){let i=Pl(e,t,pe.maxArtifactPathBytes),n=bm.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)||bm.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 Cm(e,t){if(typeof e!="string"||!$C.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function LC(e,t){let i=Rl(e,FC,t),n=Pl(i.capability,`${t} capability`,pe.maxCapabilityBytes);if(!Em.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:Cm(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 BC(e,t){let i=Rl(e,DC,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:MC(i.path,`${t} path`),kind:i.kind}}function qC(e,t){let i=Rl(e,HC,`Conflict radar change ${t}`),n=Pl(i.name,`Conflict radar change ${t} name`,pe.maxNameBytes);if(!Em.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>pe.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>pe.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>LC(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>$i(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)=>BC(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>$i(c.path,l.path)||$i(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:Cm(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function VC(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>pe.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(qC).sort((r,a)=>$i(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)>pe.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>pe.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function WC(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 zC(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 JC(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function GC(e,t){let i=[],n=IC("sha256").update(`${OC}
170
- [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Ln(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<pe.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(WC(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=zC(l,u);d&&o(d)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:JC(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function km(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function UC(e,t){return km(e.classification)-km(t.classification)||$i(e.left,t.left)||$i(e.right,t.right)}function Sm(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:_C,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 Rm(e){let t=VC(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(GC(t[s],t[c]));i.sort(UC);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=O(jC,{changes:t,relationships:n}),a=i.slice(0,pe.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Sm(t,i,a,r);for(;a.length>0&&Cl(JSON.stringify(o))>pe.maxSerializedBytes;)a=a.slice(0,-1),o=Sm(t,i,a,r);if(Cl(JSON.stringify(o))>pe.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as RR}from"node:crypto";import{promises as De}from"node:fs";import Ge from"node:path";import Pm from"node:path";var Am="comet.native.check-receipt.v1",KC="comet.native.check-receipt.v1",Hi="scoped-text-safety",Al=1,Re=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),YC=/^[a-f0-9]{64}$/u,XC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QC="comet.native.checker-policy.v1",ZC="comet.native.check-input.v1",eR=2048,xm=O(QC,{policy:Hi,version:Al,limits:Re,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),tR=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Tm=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],_m=["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"],iR=new Set(_m);function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ei(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 nt(e,t){if(typeof e!="string"||!YC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Qt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function jm(e,t){let i=Qt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Im(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 nR(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>eR||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=Pm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Pm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function rR(e){let t=Zt(e,"Native check receipt checker");ei(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Zt(t.limits,"Native check receipt limits");if(ei(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Hi||t.version!==Al||t.hash!==xm||i.maxFiles!==Re.maxFiles||i.maxFileBytes!==Re.maxFileBytes||i.maxTotalBytes!==Re.maxTotalBytes||i.maxIssues!==Re.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Hi,version:Al,hash:xm,limits:{...Re}}}function aR(e){let t=Zt(e,"Native check receipt contract");return ei(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:nt(t.expectedHash,"Native check expected contract hash"),beforeHash:nt(t.beforeHash,"Native check before contract hash"),afterHash:nt(t.afterHash,"Native check after contract hash")}}function oR(e){let t=Zt(e,"Native check receipt implementation");return ei(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:nt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:nt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:nt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:nt(t.afterSnapshotHash,"Native check after snapshot hash")}}function sR(e){let t=Zt(e,"Native check receipt counts");ei(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:Qt(t.filesSelected,"Native check filesSelected"),filesScanned:Qt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Qt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Qt(t.bytesScanned,"Native check bytesScanned"),issueCount:Qt(t.issueCount,"Native check issueCount"),recordedIssueCount:Qt(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Re.maxFiles||i.bytesScanned>Re.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Re.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function cR(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Tm.indexOf(e.kind)-Tm.indexOf(t.kind)}function lR(e){if(!Array.isArray(e)||e.length>Re.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=Zt(n,`Native check issue ${r}`);if(ei(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!tR.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:nR(a.path,`Native check issue ${r} path`),line:jm(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(cR);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function uR(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!iR.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=_m.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 dR(e){return O(ZC,e)}function Om(e){let t=Zt(e,"Native check receipt");if(ei(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Am)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!XC.test(t.change))throw new Error("Native check receipt change name is invalid");let i=jm(t.sourceRevision,"Native check source revision"),n=rR(t.checker),r=aR(t.contract),a=oR(t.implementation),o=dR({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(nt(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=Im(t.startedAt,"Native check receipt startedAt"),c=Im(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=sR(t.counts),u=lR(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=uR(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Re.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Re.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:Am,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:d},m=nt(t.receiptHash,"Native check receipt content hash");if(O(KC,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var Tl="comet.native.verification-receipt.v3",fR=Tl,hR="comet.native.declared-artifacts.v1",pR=/^[a-f0-9]{64}$/u,mR=/^acceptance-[a-f0-9]{64}$/u,vR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gR=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,wR=4096,yR=256,NR=1024;function Fi(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 At(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 rt(e,t){if(typeof e!="string"||!pR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Fe(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=He(e).trim();if(!i||i.length>wR||i!==e.trim())throw new Error(`${t} is invalid`);return i}function xl(e,t){let i=Fe(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 Yn(e,t,i=Fe,n=!1,r=yR){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 bR(e,t){if(typeof e!="string"||!mR.test(e))throw new Error(`${t} is invalid`);return e}function kR(e){let t=Fi(e,"Native verification receipt bindings");if(At(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!vR.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:rt(t.contractHash,"Native verification receipt contract hash"),scopeHash:rt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:rt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:rt(t.artifactHash,"Native verification receipt artifact hash")}}function SR(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=gR.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function ER(e,t,i,n){let r=Fi(t,`Native ${e} evidence`);if(e==="automated-check"){if(At(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=xl(r.startedAt,"Native automated-check start time"),o=xl(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=Fi(r.worktree,"Native automated-check worktree");if(At(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=Fi(r.afterFence,"Native automated-check after fence");if(At(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:Fe(r.executable,"Native automated-check executable"),args:Yn(r.args,"Native automated-check arguments",Fe,!0),cwd:Fe(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:Fe(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:rt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:rt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:rt(r.outputHash,"Native automated-check output hash"),outputSummary:Fe(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){At(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=SR(r.checkReceiptRef);if(rt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Yn(r.subjects,"Native static inspection subjects",Fe,n==="required-check"),rule:Fe(r.rule,"Native static inspection rule"),resultSummary:Fe(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return At(r,["steps","observations"],"Native manual-evidence evidence"),{steps:Yn(r.steps,"Native manual evidence steps"),observations:Yn(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function CR(e){let t=Fi(e,"Native verification receipt");if(At(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=Fe(t.actor,"Native verification receipt actor"),o=Yn(t.acceptanceIds,"Native receipt acceptance IDs",bR,n==="required-check",NR).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:Tl,kind:i,role:n,status:r,bindings:kR(t.bindings),acceptanceIds:o,actor:a,issuedAt:xl(t.issuedAt,"Native verification receipt issue time"),evidence:ER(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Hi||s.actor!==`native-runtime:${Hi}`))throw new Error("Native required check policy identity is invalid");return s}function $m(e){let t=Fi(e,"Native verification receipt");if(At(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Tl)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=CR(n),a=rt(t.receiptHash,"Native verification receipt hash");if(O(fR,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function Il(e){return O(hR,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Mm=/^[a-f0-9]{64}$/u,Di=Xt,h0=3*Di;function _l(e,t){let i=Ge.relative(e,t);return i===""||!Ge.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ge.sep}`)}function PR(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function so(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return fe(i,n)?q(i,n):q(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Hm(e){let t=await De.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await De.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function AR(e,t){let i=Ge.resolve(e),n=Ge.resolve(t);if(!_l(i,n))throw new Error("Native evidence path is outside its change");let r=[await Hm(i)],a=i;for(let o of Ge.relative(i,n).split(Ge.sep).filter(Boolean)){a=Ge.join(a,o);let s=await Hm(a);if(!_l(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Fm(e){for(let t of e){let i=await De.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!PR(t,i)||await De.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function xR(e,t,i={}){let n=await AR(t,Ge.dirname(e));await i.afterParentChainCaptured?.();let r=await De.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await De.realpath(e);if(!_l(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await De.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),De.lstat(e),De.realpath(e)]);if(await Fm(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!so(s,r)||!so(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Di)throw new Error(`Native evidence document exceeds ${Di} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let g=Di+1-d,S=await o.read(f,0,Math.min(f.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Di)throw new Error(`Native evidence document exceeds ${Di} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),De.lstat(e),De.realpath(e)]);if(await Fm(n),!m.isFile()||m.isSymbolicLink()||h!==a||!so(s,p)||!so(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Lm(e,t){if(!Mm.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function TR(e,t,i,n,r){if(!Mm.test(i))throw new Error("Native report evidence hash is invalid");let a=await ti({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"||RR("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 Mi(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 IR(e,t,i,n,r){return Ge.join(r??F(e,t),...Lm(i,n).split("/"))}async function ti(e){let t=e.changeDir??F(e.paths,e.name),i=IR(e.paths,e.name,e.kind,e.hash,t);return await G(e.paths.nativeRoot,i),xR(i,t,e.hooks)}function Dm(e,t){return Ua(e,t)}function _R(e,t){let i=Xa(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function jR(e,t,i){let n=Hp(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function OR(e,t,i){let n=sl(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function $R(e,t,i,n=!1,r){let a=await jl(e,t,i.implementationScopeRef,void 0,r);if(n&&await TR(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 Bm(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 Xn(e,t,i,n,r){let a=Mi(i,"scopes"),o=_R(await ti({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Mi(o.baselineProjectionRef,"snapshots"),c=Mi(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ti({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>Dm(d,s)),ti({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>Dm(d,c))]);return xp({baseline:l,current:u,scope:o})}async function jl(e,t,i,n,r){return(await Xn(e,t,i,n,r)).scope}async function Bm(e,t,i,n,r){let a=Mi(i,"allowances");return jR(await ti({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function co(e,t,i,n,r){let a=Mi(i,"receipts"),o=$m(await ti({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 Qn(e,t,i,n,r){let a=Mi(i,"verifications"),o=OR(await ti({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await $R(e,t,o,!1,r),o}var HR=4096;async function FR(e,t=pe.maxChanges){try{let i=await Pn({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 qm(e,t){let i=await St(e,t),[n,r]=await Promise.all([i.implementation_scope?jl(e,t,i.implementation_scope):null,bt(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 lo(e,t,i={}){let r=(await FR(e,HR)).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 qm(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await qm(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Rm([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{execFile as UR,spawn as U0}from"node:child_process";import{promisify as KR}from"node:util";import{constants as Ol,promises as Pe}from"node:fs";import ii from"node:path";var MR=/^[a-f0-9]{64}$/u,LR=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Zn=512*1024;function BR(e,t){return q({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function uo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return fe(i,n)?q(i,n):q(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function qR(e,t){let i=ii.resolve(e),n=ii.resolve(t);if(!V(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...ii.relative(i,n).split(ii.sep).filter(Boolean)]){o&&(a=ii.join(a,o));let s=await Pe.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Pe.realpath(a);if(r.length>0&&!V(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 Wm(e){for(let t of e){let i=await Pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!BR(t,i)||await Pe.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function VR(e){if(!MR.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function WR(e){let t=LR.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function zR(e,t,i){return ii.join(F(e,t),...VR(i).split("/"))}async function JR(e,t,i){let n=await qR(i,ii.dirname(e)),r=await Pe.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>Zn)throw new Error(`Native check receipt exceeds ${Zn} bytes`);let[a,o]=await Promise.all([Pe.realpath(t),Pe.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Ol.O_RDONLY|Ol.O_NOFOLLOW|Ol.O_NONBLOCK,c=await Pe.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Pe.lstat(e),Pe.realpath(e)]);if(await Wm(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!uo(r,l)||!uo(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=Zn+1-p,k=await c.read(m,0,Math.min(m.length,N),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>Zn)throw new Error(`Native check receipt exceeds ${Zn} bytes`);f.push(Buffer.from(m.subarray(0,k.bytesRead)))}let[h,g,S]=await Promise.all([c.stat(),Pe.lstat(e),Pe.realpath(e)]);if(await Wm(n),!g.isFile()||g.isSymbolicLink()||S!==o||!V(a,S)||!uo(l,h)||!uo(l,g))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function zm(e,t,i){let n=WR(i),r=F(e,t),a=zR(e,t,n);await G(e.nativeRoot,a);let o=Om(await JR(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var er=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var l$=64*1024;var u$=3600*1e3;var d$=KR(UR);var f$=["$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 YR=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Jm(e,t){let i=[];for(let n of YR){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 Gm(e){if(e.receipt.kind!=="static-inspection")return null;let t=await zm(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 xt=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 XR(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 QR(e){let t=XR(e.bundle.baseline),i=await Rc(e.paths,t,{origin:"explicit",now:e.now});return nl({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function Km(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Xn(e.paths,e.state.name,e.state.implementation_scope),i=await Ai({changeDir:F(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await QR({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 Ym(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Km(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function ZR(e){let t=await le({root:F(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:ip(t.text)}}function eP(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 tP(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:Il(e.implementationScope.scope.declaredArtifacts)}}async function Um(e){let t=await co(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Jm(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 xt([{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 Gm({paths:e.paths,state:e.state,receipt:t});if(r){let a=eP({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 iP(e){let t=tP({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Um({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof xt)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 Um({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof xt)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 xt(i)}function $l(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Hl(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:$l(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Km(e),Qn(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:$l(e.state.verification_result,"stale"),envelope:null};let n=await ZR({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 iP({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:$l(e.state.verification_result,"invalid"),envelope:null}}}function rP(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Qm(e){try{return await nP.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function aP(e,t){try{return(await le({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function oP(e,t,i){let n=za(e,i.capability);if(!V(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=Xm.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await aP(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await le({root:F(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 sP(e,t){return Qm(vl(e,t))}async function Fl(e){let t=e.now??new Date,i=await St(e.paths,e.name),n=await bt(e.paths,e.name),r=await Mt(e.paths.projectRoot),a=rP(i.name,t),o=Xm.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(m=>oP(e.paths,i.name,m))),Hl({paths:e.paths,state:i,now:t}),lo(e.paths,i.name),Wa(e.paths,i.name),Mh(e.paths,i.name),sP(e.paths,i.name),Qm(o)]);return Nm({change:i.name,archiveConfirmation:r?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,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]})}async function cP(e,t){let i=F(e,t.name),n=await Si(i);if(!n||!t.run_id||n.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let r=await ja(i,n.checkpointRef);if(!r||r.runId!==n.runId||r.stateVersion!==n.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await qt(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function lP(e,t){let i=await cP(e,t);return{committed:i,latest:Wp(i),history:Vp(i)}}async function Zm(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await lP(e,t),r=n.latest;if(!r)return null;let a=n.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=r.disposition==="hard-stop"&&!o?"continue":r.disposition;return{disposition:o?"hard-stop":s,signatureHash:r.signatureHash,overrideRecorded:n.history.some(c=>c.kind==="override"&&c.signatureHash===r.signatureHash),failedAcceptanceIds:[...r.failedAcceptanceIds],failedCheckIds:[...r.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var dP=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Li=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function fP(e){return(await fp(e))?.change??null}function hP(e,t,i=!1,n){return e.phase==="archive"?t?`comet native archive ${e.name} --dry-run`:i?`comet native next ${e.name} --summary "<summary>"`:null:`comet native next ${e.name} --summary "<summary>"${e.phase==="shape"||e.phase==="build"&&e.approval!=="confirmed"?" --confirmed":""}`}async function pP(e,t){let i=F(e,t.name),n=[...(await Lc(i,t.brief)).findings,...(await Wh(e,t)).findings,...await hp(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await Pa(e,t.name);if(r===null)n.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await mh(e,r);a.complete||n.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(r){n.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${r.message}`})}if(t.phase==="build")try{let r=await Ai({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==r.contract.contractHash&&n.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(r){n.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${r.message}`})}try{await tm(e,t.name)&&n.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(r){n.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${r.message}`})}return t.verification_report?n.push(...(await Bc(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&n.push({code:"verification-report-missing",message:"Native change has no verification report"}),n}async function Dl(e,t,i){let n=await fP(e)===t,r;try{let w=await Dc(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};r=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,error:w.message}}let a=await gm({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await Zm(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let w=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:w,message:`Native repair is stopped at failure signature: ${o.signatureHash}`})}}catch{s.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let c;if(i?.details&&(r.phase==="build"||r.phase==="verify"||r.phase==="archive"))try{let w=await Ai({changeDir:F(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),v=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let E=await Qn(e,r.name,r.verification_evidence);for(let I of E.acceptanceTrace.entries)v.set(I.acceptanceId,I.status==="failed"?"failed":I.status==="missing"?"missing":"satisfied")}c=Xh({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:v,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(w){if(i.acceptanceCursor)throw w;c=void 0}let l=[];if(i?.includeConflictFindings!==!1)try{let w=await lo(e,r.name,{tolerateInvalidSiblings:!0});l.push(...w.findingCodes.map(v=>({code:v,message:`Native change overlap is visible in the current root: ${v}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let w=await bt(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let v=await Da({paths:e,identity:w});v.state==="drifted"&&v.code&&u.push({code:v.code,message:v.message??"Native workspace binding is no longer valid"})}else{let v=await Fa({paths:e,identity:w});u.push(...v.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${v.driftComponents.join(", ")||"no-component"})`})))}}catch{u.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let d=[],f=!1;if(r.phase==="verify"){let w=await Ym({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.findingCodes.map(v=>({code:v,message:`Native Verify implementation scope is not current: ${v}`})))}let p=null,m=[];if(r.phase==="archive")try{p=await Fl({paths:e,name:r.name}),m.push(...p.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let h=[...await pP(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,v,E)=>E.findIndex(I=>I.code===w.code&&I.path===w.path)===v),g=rm({paths:e,state:r,findings:h}),S=g.filter(w=>!Ei(w.code)),N=r.phase==="archive"&&p?.ready===!0&&S.length===0,k=f||r.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),C=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=g.find(w=>w.severity==="error");return{name:r.name,phase:r.phase,revision:r.revision,approval:r.approval,verificationResult:r.verification_result,specChanges:r.spec_changes.length,selected:n,nextCommand:b||C?null:hP(r,N,k,i?.clarificationMode),archiveReady:N,inspection:a.inspection,findingSummary:am(g),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:im({state:r,findings:g,archiveReady:N,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:g.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:ao,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}async function mP(e){let t;try{t=await mc({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await uP.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>Li.maxChanges))throw new Error(`Native status exceeds ${Li.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function ev(e,t){let i=t.toString(36),n=O("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function vP(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=dP.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let n=O("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==n)throw new Error("Native status cursor integrity check failed");return i}async function tv(e,t){let i=await mP(e),n=O("comet.native.status-names.v1",i),r=vP({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+Li.maxItems).map(c=>Dl(e,c,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let c of a){let l=[...o,c],u=r+l.length,d={schema:"comet.native.status-page.v1",total:i.length,offset:r,items:l,nextCursor:u<i.length?ev(n,u):null,limits:{...Li}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Li.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(c)}let s=r+o.length;return{schema:"comet.native.status-page.v1",total:i.length,offset:r,items:o,nextCursor:s<i.length?ev(n,s):null,limits:{...Li}}}import NP from"path";var _H={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var VH=16*1024*1024,WH=256*1024,zH=16*1024;var x1=16*1024*1024,fo=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"},ho=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"};var M1=10*1024*1024,Ne=class extends Error{};function po(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new Ne(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function tr(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ne(`${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 Ne(`${t} requires a value`);return e.splice(n,2),r}function iv(e){if(e.length>0)throw new Ne(`Unexpected argument: ${e[0]}`)}async function nv(e){return e?NP.resolve(e):ma(process.cwd())}async function rv(e){let t=await Bf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function av(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
171
- `}}function ov(e,t){if(t instanceof Ne)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof fo)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 ho)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof La)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Ba)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof qa)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 xt)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof er)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 sv(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}})+`
172
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function cv(e,t){let i=po(e,"--details"),n=tr(e,"--cursor"),r=tr(e,"--acceptance-cursor"),a=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!a)throw new Ne("status --details requires a change name");if(n&&a)throw new Ne("--cursor is only valid for status lists");if(n&&i)throw new Ne("--cursor cannot be combined with --details");if(r&&!i)throw new Ne("--acceptance-cursor requires status --details");if(r&&!a)throw new Ne("--acceptance-cursor requires a change name");iv(e);let{config:o,paths:s}=await rv(t),c=a?await Dl(s,a,{details:i,...r?{acceptanceCursor:r}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures}):await tv(s,{...n?{cursor:n}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures});return av("status",c)}function bP(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}})+`
173
- `}}async function lv(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{po(r,"--json"),s=tr(r,"--project-root");let u=[...r,...a],d=await nv(s);c=await t(u,d)}catch(u){c=ov(e,u)}let l=o?bP(c):sv(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
155
+ ${Buffer.byteLength(r)}:${r}`)}function hl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function to(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!hl(i))return e.splice(t,1),i}return null}function Gt(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ye(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function xE(e,t,i,r){if(!j(r))return{status:"budget-exhausted"};let n;try{n=await Y.open(e,"r")}catch(c){if(!j(r))return{status:"budget-exhausted"};throw c}if(!j(r))return await n.close(),{status:"budget-exhausted"};let a=io("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!j(r))return{status:"budget-exhausted"};let c=await n.stat();if(!j(r))return{status:"budget-exhausted"};if(!c.isFile()||!Gt(i,c))return{status:"changed"};for(;;){if(!j(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!j(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!j(r))return{status:"budget-exhausted"};let d=await n.stat();return j(r)?!d.isFile()||!Gt(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Ie(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function je(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Ki(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 Ah(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 CE(e,t){let i=Ie(e,`Native snapshot entry ${t}`);je(i,eE,`Native snapshot entry ${t}`);let r=Ah(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!ro.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 n={path:r,hash:i.hash,size:ct(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!yh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function RE(e,t){let i=Ie(e,`Native snapshot omission ${t}`);if(je(i,tE,`Native snapshot omission ${t}`),!nE.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!aE.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Ah(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 AE(e){let t=Ie(e,"Native snapshot omission overflow");if(je(t,iE,"Native snapshot omission overflow"),typeof t.hash!="string"||!ro.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:Ki(t.count,"Native snapshot omission overflow count")}}function Ui(e,t){let i=Ie(e,t);if(je(i,XS,t),typeof i.hash!="string"||!ro.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ct(i.recordCount,`${t} recordCount`),n=ct(i.storedRecordCount,`${t} storedRecordCount`),a=ct(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function vh(e){let t=Ie(e,"Native Git selection evidence");if(je(t,YS,"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=Ui(t.stageBefore,"Native Git selection stageBefore"),r=Ui(t.combined,"Native Git selection combined"),n=Ui(t.stageAfter,"Native Git selection stageAfter"),a=Ui(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Ui(t.finalCombined,"Native Git selection finalCombined"),s=Ui(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Ut(i,n)||!Ut(n,a)||!Ut(r,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:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function gh(e,t){let i=Ie(e,t);if(je(i,ZS,t),typeof i.hash!="string"||!ro.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 r=ct(i.visitedNodeCount,`${t} visitedNodeCount`),n=ct(i.recordCount,`${t} recordCount`),a=ct(i.storedRecordCount,`${t} storedRecordCount`),o=ct(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function _E(e){let t=Ie(e,"Native physical selection evidence");if(je(t,QS,"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=gh(t.before,"Native physical selection before"),r=gh(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!xh(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function mi(e){let t=Ie(e,"Native content snapshot manifest");if(je(t,zS,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!rE.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=Ie(t.capture,"Native content snapshot capture");if(je(y,US,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=y.gitSelection===void 0?void 0:vh(y.gitSelection),w=y.physicalSelection===void 0?void 0:_E(y.physicalSelection),g=null;if(y.projection!==void 0){let S=Ie(y.projection,"Native content snapshot projection");if(je(S,KS,"Native content snapshot projection"),S.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...S.selection===void 0?{}:{selection:vh(S.selection)}}}if(y.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&g)throw new Error("Native physical-tree capture cannot combine selection and projection");i=g?{provider:"physical-tree",projection:g}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}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 r=Ie(t.limits,"Native content snapshot limits");je(r,JS,"Native content snapshot limits");let n={maxFiles:Ki(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Ki(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Ki(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Ki(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Ki(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=Ie(t.policy,"Native snapshot policy");if(je(y,GS,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Rh({include:y.include,exclude:y.exclude,hash:y.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(CE),s=t.omitted.map(RE),c=ct(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:AE(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>n.maxFileBytes)||o.reduce((y,x)=>y+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>ml||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(y=>y.reason==="physical-enumeration-limit"),b=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...m,...b])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,P=N?.status==="overflow"||N?.status==="overflow-and-changed",k=N?.status==="changed"||N?.status==="overflow-and-changed";if(P!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(b.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:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(wl(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function _h(e,t,i={}){let r=mi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=H.resolve(e.projectRoot),a=Nh(i),o=bh(i.gitSelectionLimits),s=await Eh(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Ch(s).filter(w=>sn(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>sn(e,w)),d=(w,g)=>g.some(S=>w===S||w.startsWith(`${S}/`)),f=w=>d(w,l),h=w=>d(w,u),v=[...r.entries.map(w=>w.path),...r.omitted.flatMap(w=>w.type==="directory"?[w.path,`${w.path}/`]:[w.path])].filter(w=>!c.has(w)&&!f(w)&&!h(w)),p=await pE(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!h(w.path)&&sn(e,w.path)&&(c.has(w.path)||!p.has(w.path)));await Ph(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let w of l)b.push({path:w,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((w,g)=>w.path.localeCompare(g.path,"en"));let N=r.omitted.filter(w=>f(w.path)||h(w.path)||!sn(e,w.path)?!1:p.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of b)N.some(g=>g.path===w.path&&g.reason===w.reason)||N.push(w);N.sort((w,g)=>w.path.localeCompare(g.path,"en"));let P=r.omissionOverflow?.count??0,k=r.omissionOverflow?.hash??U("comet.native.snapshot-omission-overflow.v1");s.overflow&&(P+=s.overflow.count,k=ln(k,"git-selection",{source:"git-selection",...s.overflow}));let E=w=>{P+=1,k=ln(k,"omission",w)};for(;N.length>ml;){let w=to(N);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(w)}let y=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:N.length+P===0,entries:m,omitted:N,omittedCount:N.length+P,...P>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:P}}:{}}),x=y();for(;wl(x)>r.limits.maxManifestBytes;){let w=to(N);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(w),x=y()}return mi(x)}function TE(e,t){if(!WS.test(t))throw new Error(`Invalid Native change name: ${t}`);return H.join(G(e,t),"baseline-manifest.json")}async function Th(e,t={}){let i={maxFiles:t.limits?.maxFiles??Qa.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Qa.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Qa.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Qa.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Rh(t.policy),n=Nh({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=bh(t.gitSelectionLimits),o=dE(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 Y.realpath(s),l=H.resolve(e.nativeRoot),u=await Y.realpath(l),d=H.resolve(e.runtimeDir),f=H.resolve(e.configFile),h=H.join(s,".comet","current-change.json"),v=kE(s,t.denylist??[]),p=[],m=[],b=new Map,N=new Map,P=0,k=0,E=U("comet.native.snapshot-omission-overflow.v1"),y=0,x=!1,w=null,g=_=>{k+=1,E=ln(E,"omission",_)},S=_=>{if(P+=1,m.length<ml){m.push(_);return}if(hl(_)){let A=to(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),m.push(_);return}g(_)},D=_=>{P+=_.count,k+=_.count,E=ln(E,"git-selection",{source:"git-selection",..._})},I=_=>{k+=1,E=ln(E,"manifest-entry",{reason:"manifest-size",entry:_})},de=async(_,A)=>{p.push(_),y+=_.size,b.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},X=(_,A)=>{let T=p.findIndex(K=>K.path===_);if(T<0)return;let[B]=p.splice(T,1);y-=B.size,b.delete(_),S(A)},J=async(_,A,T,B)=>{if(!T.isFile()||T.isSymbolicLink()||!j(n))return;let K;try{K=await Y.realpath(_)}catch(R){if(!j(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:T.size,type:"file",reason:re(R)?"changed-during-read":"unreadable"});return}if(!j(n)||!F(c,K)||Ke(u,K))return;if(p.length>=i.maxFiles){S({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){S({path:A,size:T.size,type:"file",reason:"file-size"});return}if(y+T.size>i.maxTotalBytes){S({path:A,size:T.size,type:"file",reason:"total-size"});return}let M,$,Z;try{if(M=await xE(K,T.size,T,n),M.status==="budget-exhausted"||!j(n))return;if(M.status==="changed"){S({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!j(n)||(Z=await Y.realpath(_),!j(n)))return;$=await Y.lstat(_)}catch(R){if(!j(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:T.size,type:"file",reason:re(R)?"changed-during-read":"unreadable"});return}if(j(n)){if(M.bytes!==T.size||Z!==K||!Gt(T,M.finalStat)||!Gt(M.finalStat,$)||!$.isFile()||$.isSymbolicLink()||$.size!==T.size||$.mtimeMs!==T.mtimeMs||$.ctimeMs!==T.ctimeMs){S({path:A,size:$.isFile()?$.size:null,type:$.isFile()?"file":"other",reason:"changed-during-read"});return}j(n)&&await de({path:A,hash:M.hash,size:$.size,type:"file",...B===void 0?{}:{gitObjectId:B}},{kind:"file",target:_,realTarget:K,stat:$})}},tt=async(_,A,T)=>{if(!j(n))return;let B,K,M;try{if(B=await Y.readlink(_,{encoding:"buffer"}),!j(n)||(M=await Y.lstat(_),!j(n)))return;K=await Y.readlink(_,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!ne(R)&&!re(R))throw R;S({path:A,size:null,type:"other",reason:re(R)?"changed-during-read":"unreadable"});return}if(!j(n))return;if(!M.isSymbolicLink()||!Gt(T,M)||M.mtimeMs!==T.mtimeMs||M.ctimeMs!==T.ctimeMs||!B.equals(K)){S({path:A,size:null,type:"other",reason:"changed-during-read"});return}let $=B.byteLength;if(p.length>=i.maxFiles){S({path:A,size:$,type:"other",reason:"file-count"});return}if($>i.maxFileBytes){S({path:A,size:$,type:"other",reason:"file-size"});return}if(y+$>i.maxTotalBytes){S({path:A,size:$,type:"other",reason:"total-size"});return}let Z=io("sha256").update("symlink\0").update(B).digest("hex");j(n)&&await de({path:A,hash:Z,size:$,type:"file"},{kind:"symlink",target:_,rawTarget:B,stat:M})},Be=async()=>{for(let[_,A]of[...b]){if(!j(n))return;if(A.kind==="file"){let $,Z;try{if($=await Y.realpath(A.target),!j(n))return;Z=await Y.lstat(A.target)}catch(R){if(!j(n))return;if(!ne(R)&&!re(R))throw R;X(_,{path:_,size:null,type:"file",reason:ne(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;($!==A.realTarget||!Z.isFile()||Z.isSymbolicLink()||!Gt(A.stat,Z)||Z.size!==A.stat.size||Z.mtimeMs!==A.stat.mtimeMs||Z.ctimeMs!==A.stat.ctimeMs)&&X(_,{path:_,size:Z.isFile()?Z.size:null,type:Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let $,Z;try{if($=await Y.lstat(A.target),!j(n))return;Z=await Y.readlink(A.target,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!ne(R)&&!re(R))throw R;X(_,{path:_,size:null,type:"other",reason:ne(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(!$.isSymbolicLink()||!Gt(A.stat,$)||$.mtimeMs!==A.stat.mtimeMs||$.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Z))&&X(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let T,B;try{if(T=await Y.realpath(A.target),!j(n))return;B=await Y.lstat(A.target)}catch{if(!j(n))return;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;if(!(T===A.realTarget&&B.isDirectory()&&!B.isSymbolicLink()&&Gt(A.stat,B)&&F(c,T)&&!Ke(u,T))){X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!j(n))return;M=await ph(n,T)}catch($){if(Yi($))throw $;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;M.dirty?X(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of N){if(!j(n))return;try{let T=await Y.lstat(A);if(!j(n))return;S({path:_,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!j(n))return;if(re(T))continue;if(!ne(T))throw T;S({path:_,size:null,type:"file",reason:"unreadable"})}}},Ee=await Eh(n,e,a,t.gitSelectionHooks);if(Ee===null){let _=await dh({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let B of _.records){if(B.type!=="file"&&B.type!=="symlink"||b.has(B.path))continue;if(Ue(n)<1)break;if(!mh(r,B.path,n))continue;if(Ue(n)<1)break;let K=H.resolve(s,...B.path.split("/")),M;try{M=await Y.lstat(K)}catch($){if(!j(n))break;if(!ne($)&&!re($))throw $;S({path:B.path,size:null,type:"file",reason:re($)?"changed-during-read":"unreadable"});continue}if(Ue(n)<1)break;if(B.type==="symlink"&&M.isSymbolicLink()){if(await tt(K,B.path,M),Ue(n)<1)break;continue}if(B.type!=="file"||!M.isFile()||M.isSymbolicLink()){S({path:B.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(K,B.path,M),Ue(n)<1)break}Ue(n)>=1&&await Be();let A=await dh({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),T=NE(_.evidence,A.evidence);w=T.evidence;for(let B of[..._.omissions,...A.omissions,...T.omissions])m.some(K=>K.path===B.path&&K.reason===B.reason)||S(B)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,T=!1;if(_){let R=mi(_);for(let Q of R.entries)Q.gitObjectId!==void 0&&A.set(Q.path,Q);T=A.size>0}let B=new Set,K=!0;try{let R=await cn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)T=!1,K=!1,A.clear();else for(let Q of R.records){let ee=eo(Q),ve=ee.indexOf(" "),fe=ve<0?null:Xi(ee.slice(ve+1));if(ve!==1||fe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&B.add(fe)}}catch(R){if(Yi(R))throw R;T=!1,K=!1,A.clear()}let M=new Set;try{let R=await Za(n,s,["ls-files","--modified","-z"],pl);for(let Q of R.toString("utf8").split("\0")){let ee=Xi(Q);ee!==null&&M.add(ee)}}catch{T=!1,K=!1,A.clear()}let $=new Set,Z=new Set;for(let R of Ch(Ee)){if(b.has(R)||!sn(e,R))continue;if(Ue(n)<1)break;if(!mh(r,R,n))continue;if(Ue(n)<1)break;let Q=H.resolve(s,...R.split("/"));if(Q===f||Q===h||Ke(d,Q)||v.some(Pe=>Ke(Pe,Q)))continue;if(Ee.gitlinks.has(R)){if(p.length>=i.maxFiles){S({path:R,size:0,type:"file",reason:"file-count"});continue}let Pe,$n;try{[Pe,$n]=await Promise.all([Y.realpath(Q),Y.lstat(Q)])}catch{S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if($n.isSymbolicLink()||!$n.isDirectory()||!F(c,Pe)||Ke(u,Pe)){S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let bi=await ph(n,Pe);if(bi.dirty){S({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await de({path:R,hash:bi.hash,size:0,type:"file"},{kind:"gitlink",target:Q,realTarget:Pe,stat:$n,hash:bi.hash})}catch(bi){if(Yi(bi))throw bi;S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await Y.lstat(Q)}catch(Pe){if(re(Pe)&&Ee.tracked.has(R)){N.set(R,Q);continue}if(!ne(Pe)&&!re(Pe))throw Pe;S({path:R,size:null,type:"file",reason:re(Pe)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await tt(Q,R,ee);continue}if(!ee.isFile()){Ee.nestedRepositories.has(R)||S({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let ve=Ee.trackedObjectIds.get(R),fe=ve?A.get(R):void 0;if(T&&fe?.gitObjectId!==void 0&&fe.gitObjectId===ve&&!B.has(R)&&!M.has(R)){if(p.length>=i.maxFiles){S({path:R,size:fe.size,type:"file",reason:"file-count"});continue}if(fe.size>i.maxFileBytes){S({path:R,size:fe.size,type:"file",reason:"file-size"});continue}if(y+fe.size>i.maxTotalBytes){S({path:R,size:fe.size,type:"file",reason:"total-size"});continue}p.push({...fe}),y+=fe.size,$.add(R);continue}let Bu=K&&!B.has(R)&&!M.has(R)?ve:void 0;await J(Q,R,ee,Bu),Bu!==void 0&&Z.add(R)}if(await Be(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Ph(n,e,a,Ee,t.gitSelectionHooks?.outputChunkBytes),$.size>0||T&&Z.size>0){let R=await Za(n,s,["ls-files","--modified","-z"],pl),Q=new Set;for(let ee of R.toString("utf8").split("\0")){let ve=Xi(ee);ve!==null&&Q.add(ve)}for(let ee of $){if(!Q.has(ee))continue;let ve=p.find(fe=>fe.path===ee);X(ee,{path:ee,size:ve?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Z){if(!Q.has(ee))continue;let ve=p.find(fe=>fe.path===ee);ve&&delete ve.gitObjectId}}for(let R of Ee.omissions)S(R);Ee.overflow&&D(Ee.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let Ig=Ee===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Ee.evidence?{gitSelection:Ee.evidence}:{}},Du=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Ig,createdAt:(t.now??new Date).toISOString(),complete:P===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:m,omittedCount:P,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:k}}:{}}),Uo=Du();for(;wl(Uo)>i.maxManifestBytes;){if(m.filter(A=>!hl(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T=0;T<A;T+=1){let B=to(m);if(B===null)break;g(B)}}else if(p.length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let T of p.splice(-A))P+=1,I(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Uo=Du()}return Uo}async function yl(e,t,i={}){let n=(await ze(e.projectRoot))?.native.snapshot??Uc;return Th(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function no(e,t){let i=TE(e,t),r=oe(e,i);await z(r,i);try{let n=await nh({root:r,file:i,maxBytes:VS,label:"Native baseline snapshot manifest"});return mi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as UE}from"crypto";import KE from"path";var $e=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 ao,promises as Ye}from"node:fs";import Xe from"node:path";import{TextDecoder as VE}from"node:util";import FE from"path";var DE=Hn(Ur(),1);var Uj=4*1024*1024;var Ih=(e,t)=>{let i=e[t];return i==null?null:String(i)};function dn(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 un(e,t){let i=dn(e,t);if(FE.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 LE(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function jh(e){if(!e.run_id)return null;let t=dn(e,"run_id"),i=dn(e,"skill"),r=dn(e,"skill_version"),n=dn(e,"skill_hash"),a=un(e,"pending_ref"),o=un(e,"trajectory_ref"),s=un(e,"context_ref"),c=un(e,"artifacts_ref"),l=un(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:r,skillHash:n,orchestration:e.orchestration,currentStep:Ih(e,"current_step"),iteration:u,pending:Ih(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:LE(e)}}var V$=256*1024;var ME=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function qE(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=jh(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Nl(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(r=>!ME.has(r));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 qE(t)}var Zi={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 so(e,t){let i=Xe.relative(e,t);return i===""||!Xe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xe.sep}`)}function WE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function oo(e,t){return W({...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 zE(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function co(e,t,i){let r=$e[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Xe.resolve(e),a=Xe.resolve(n,...r.slice(8).split("/"));if(!so(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function $h(e){let t=await Ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function JE(e,t){let i=Xe.resolve(e),r=Xe.resolve(t);if(!so(i,r))throw new Error("Native Run path is outside its change");let n=[await $h(i)],a=i;for(let o of Xe.relative(i,r).split(Xe.sep).filter(Boolean)){a=Xe.join(a,o);let s;try{s=await $h(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!so(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Oh(e){for(let t of e){let i=await Ye.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!zE(t,i)||await Ye.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function GE(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 lo(e,t,i,r,n){let a=await JE(e,Xe.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Ye.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=WE(o),c=await Ye.realpath(t);if(!so(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?ao.O_RDONLY:ao.O_RDONLY|ao.O_NOFOLLOW|ao.O_NONBLOCK,u;try{u=await Ye.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Oh(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!oo(s,d)||!oo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await GE(u,i,r);await n?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Oh(a),!m.isFile()||m.isSymbolicLink()||b!==c||!oo(s,p)||!oo(s,m))throw new Error(`${r} changed while reading`);let N;try{N=new VE("utf-8",{fatal:!0}).decode(v)}catch(P){throw new Error(`${r} is not valid UTF-8`,{cause:P})}return{text:N,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Hh(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function bl(e){return Nl(e)}async function er(e,t){let i=co(e,"stateRef"),r=await lo(e,i,Zi.runStateBytes,"Native Run state",t);return r?Nl(Hh(r.text,"Native Run state")):null}async function vi(e,t,i){let r=co(e,"trajectoryRef",t),n=await lo(e,r,Zi.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Zi.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Zi.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 Dh(e,t,i){return(await lo(e,co(e,"trajectoryRef",t),Zi.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function uo(e,t,i){let r=await lo(e,co(e,"checkpointRef",t),Zi.checkpointBytes,"Native Run checkpoint",i);return r?Hh(r.text,"Native Run checkpoint"):null}var YE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function kl(e){return UE("sha256").update(e).digest("hex")}function XE(e,t){if(!YE.test(t))throw new Error(`Invalid Native change name: ${t}`);return KE.join(G(e,t),"trajectory.jsonl")}function QE(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function ZE(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 eP(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=QE(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
156
+ `)])}catch(d){if(!ZE(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:kl(t),targetHash:kl(l),tailHash:kl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function tP(e,t){let i=XE(e,t);await z(oe(e,i),i);let r=G(e,t),n=await Dh(r,$e.trajectoryRef);return n===null?{status:"clean",file:i}:eP(i,Buffer.from(n))}async function Bh(e,t){let i=await tP(e,t);return"inspection"in i?i.inspection:i}import{createHash as rP}from"node:crypto";import{promises as fo}from"node:fs";import gt from"node:path";var fn=/^[a-f0-9]{64}$/u,Fh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,nP=16*1024,El=process.platform,aP=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function tr(e){return aP.has(e)}function qh(e,t){let i=gt.relative(e,t);return gt.isAbsolute(i)||i===".."||i.startsWith(`..${gt.sep}`)?null:i.replaceAll("\\","/")||"."}function Vh(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wh(e,t){if(e.length===0||Vh(e)||e.includes("\\")||gt.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=gt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Pl(e,t){return rP("sha256").update(`${e}
157
+ ${t}`).digest("hex")}async function Lh(e,t){let i=await fo.realpath(t),r=await fo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=El==="win32"?gt.normalize(i).toLowerCase():i;return Pl(e,`${n}
158
+ ${r.dev}
159
+ ${r.ino}
160
+ ${r.birthtimeMs}`)}async function Mh(e,t){let i=await fo.realpath(t),r=await fo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=El==="win32"?gt.normalize(i).toLowerCase():i;return Pl(e,n)}function oP(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 Sl(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Vh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function zh(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Sl(e.changeBranch,"Native workspace change branch"),Sl(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 sP(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"||!Fh.test(t.baseCommit)||typeof t.targetCommit!="string"||!Fh.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Sl(t.targetBranch,"Native workspace Git target branch")}function po(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"||!fn.test(String(t.projectRootId))||!fn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");oP(t.capturedAt),Wh(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&&!fn.test(String(t.projectRootPathId))||a&&!fn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!fn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&sP(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(zh(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 cP(e,t){return gt.join(G(e,t),"workspace.json")}function lP(e,t){let i=cP(e,t),r=oe(e,i),n=qh(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Wh(n,"Native workspace file ref")}}async function uP(e,t){try{let i=lP(e,t),r=await ce({root:i.root,ref:i.ref,maxBytes:nP});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ho(e,t){let i=Fe(e.projectRoot),r={projectRoot:gt.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await wt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await pn({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function dP(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=qh(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Fe(e.paths.projectRoot),r=i.isGitWorktree?Ko(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Ko(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Lh("comet.native.workspace-project-root.v2",e.paths.projectRoot),Lh("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Mh("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Mh("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&zh(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Pl("comet.native.workspace-session.v2",`${s}
161
+ ${c}
162
+ ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return po(h),h}async function wt(e,t){let i=await uP(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(po(i),i)}async function mo(e){po(e.identity);let t=await dP({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];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")),El==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function pn(e){if(po(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 mo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Fe(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 Jh(e,t){let i=await wt(e,t);if(i===null)return null;let r=await pn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Kh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],pP=new Set(Kh),Yh=new Set([...Kh,"minimum_runtime_version","revision"]),hP=new Set([...Yh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),mP=new Set(["capability","operation","source","base_hash"]),vP=new Set(["shape","build","verify","archive"]),gP=new Set(["implicit","confirmed"]),wP=new Set(["pending","pass","fail"]),Yt="comet-state.yaml",Cl=/^[a-f0-9]{64}$/u,Xh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yP=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,vo=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"},gi=class extends Error{constructor(i,r){super(i!==qt||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"},go=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"},hn=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"},wo=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"},LO=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
163
+ `);function vn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Qh(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 yo(e){if(!Xh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function NP(e){if(!Xh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Zh(e,t){if(e.length===0||yt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function bP(e,t){let i=vn(e,`spec_changes[${t}]`);if(Qh(i,mP,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(NP(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"&&Zh(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"||!Cl.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"||!Cl.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 kP(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 Al(e,t){if(Qh(e,t,Yt),typeof e.name!="string")throw new Error("Native change name is required");if(yo(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"||!vP.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&&!gP.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(bP),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"||!wP.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"&&Zh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!kP(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 Ji(e){let t=vn(e,Yt);if(t.schema!==Wt)throw new Error(`Expected ${Wt}`);return{schema:Wt,...Al(t,pP)}}function mn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xl(e,t,i){if(e===null)return null;let r=typeof e=="string"?yP.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 SP(e){if(e==null)return null;if(typeof e!="string"||!Cl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function EP(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Gi(e){let t=vn(e,Yt);if(t.schema!==Vt)throw new Error(`Expected ${Vt}`);if(mn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Vt} minimum_runtime_version must be 2`);return{schema:Vt,minimum_runtime_version:2,revision:mn(t.revision,"Native v2 revision"),...Al(t,Yh)}}function zt(e){let t=vn(e,Yt);if(t.schema!==qt){if(t.schema===Wt||t.schema===Vt){let o=t.schema===Wt?Ji(t):Gi(t);throw new vo(o.name,o.schema)}throw new gi(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=mn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new gi(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=mn(t.revision,"Native revision"),n=Al(t,hP),a=SP(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:qt,minimum_runtime_version:3,revision:r,verification_protocol:EP(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:xl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:xl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:xl(t.partial_allowance,"Native partial_allowance","allowances")}}function em(e){let t=vn(e,Yt);if(t.schema===Wt){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${qt}`}}if(t.schema===Vt){let n=Gi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${qt}`}}if(t.schema!==qt){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 gi(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=mn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new gi(t.schema,i).message};let r=zt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function ue(e,t){yo(t);let i=yt.join(e.changesDir,t);if(!F(e.changesDir,i))throw new Error("Native change path escaped");return i}async function No(e,t){let i=G(e,t),r=yt.join(i,"schema-migration.json");await z(F(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Uh.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function tm(e,t){let i=G(e,t),r=yt.join(i,"checkpoint-journal.json");await z(F(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Uh.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var PP=256*1024;async function im(e,t=yt.dirname(e)){let i=yt.relative(t,e).split(yt.sep).join("/"),r=await ce({root:t,ref:i,maxBytes:PP}),n=(0,Rl.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 _l(e,t){let i=yt.join(ue(e,t),Yt);await z(e.nativeRoot,i);let r=em(await im(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await No(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await xP(e,r.state),r)}async function rm(e,t){let i=yt.join(ue(e,t),Yt);await z(e.nativeRoot,i);let r=em(await im(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function xP(e,t){if(await no(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Nt(e,t){let i=await _l(e,t);if(i.status==="migration-required")throw new vo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new gi(i.schema,i.minimumRuntimeVersion);return await Jh(e,t),i.state}import{promises as bA}from"fs";import{promises as Tl}from"fs";import nm from"path";var am=["Outcome","Scope","Non-goals","Acceptance examples"],CP=[...am,"Constraints and invariants","Decisions","Open questions","Verification expectations"],RP=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],om={maxFileBytes:Kr};function sm(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
164
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function AP(e,t){let i=nm.resolve(e,...t.split(/[\\/]/u));if(!F(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await Tl.realpath(e),n=await Tl.realpath(i);if(!F(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Tl.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function gn(e){return{valid:e.length===0,findings:e}}async function Il(e,t){let i=[],r;try{r=(await ce({root:e,ref:t,maxBytes:om.maxFileBytes})).text}catch(o){return gn([{code:"brief-missing",message:o.message,path:t}])}let n=sm(r);for(let o of CP)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of am)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.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}),gn(i)}async function jl(e,t){let i=[],r;try{r=(await ce({root:e,ref:t,maxBytes:om.maxFileBytes})).text}catch(a){return gn([{code:"verification-missing",message:a.message,path:t}])}let n=sm(r);for(let a of RP)n.has(a)?(n.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 gn(i)}function bo(e,t){return nm.join(e.specsDir,t,"spec.md")}async function cm(e,t){let i=[],r=ue(e,t.name);for(let n of t.spec_changes){let a=bo(e,n.capability),o=null;try{await z(e.nativeRoot,a),o=await ll(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await AP(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return gn(i)}import lm from"node:path";var _P="comet.native.contract.v1",TP="comet.native.acceptance-set.v1",um=/^[a-f0-9]{64}$/u,wn={maxAcceptanceCriteria:rn.maxCriteria};function dm(e,t){let i=lm.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||lm.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 fm(e){return O("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
165
+ `))}function IP(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(um))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(um))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=dm(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:fm(e.markdown)},markdown:e.markdown}}function jP(e,t){return pm(e.id,t.id)}function pm(e,t){return e<t?-1:e>t?1:0}function hm(e){let t=dm(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(IP).sort((d,f)=>pm(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Zc(e.briefMarkdown,t,wn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...el(f,d.source,wn.maxAcceptanceCriteria-a.length)),a.push(...tl(f,d.source,wn.maxAcceptanceCriteria-a.length)));if(a.sort(jP),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>wn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${wn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:fm(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=O(TP,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:O(_P,u)}}var ko={maxSpecs:64,maxFileBytes:Kr,maxTotalBytes:4*1024*1024};async function ir(e){if(e.specChanges.length>ko.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ce({root:e.changeDir,ref:e.briefRef,maxBytes:ko.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ce({root:e.changeDir,ref:n.source,maxBytes:ko.maxFileBytes});if(i+=a.size,i>ko.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:hm({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import $P from"path";var $l="comet.selection.v2",OP=16*1024;function vm(e){return $P.join(e,".comet","current-change.json")}function HP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mm(e){return e===null||typeof e=="string"}function DP(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(!HP(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&&!mm(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:$l,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==$l)throw new Error(`current change selection schema must be ${$l}`);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(!mm(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 gm(e){let t;try{let r=vm(e),{bytes:n}=await Oi(r,OP,{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",...DP(t)}}import{promises as tx}from"node:fs";import Dl from"node:path";var a0=["$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 BP=/\b(Bearer|Basic)\s+[^\s"']+/giu,FP=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,LP=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,MP=/\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,qP=/("(?:[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,VP=/(["'])((?:[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,WP=/\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 Oe(e){return e.replace(BP,"$1 [REDACTED]").replace(FP,"[REDACTED PRIVATE KEY]").replace(LP,"$1[REDACTED]@").replace(MP,"[REDACTED TOKEN]").replace(qP,'$1"[REDACTED]"').replace(VP,"$1$2$1$3$4[REDACTED]$4").replace(WP,"$1$2[REDACTED]")}import{promises as YP}from"node:fs";import wm from"node:path";function So(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Eo(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 lt(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 ym(e,t){return e===null?null:lt(e,t)}function xo(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 XP(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 QP(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Po(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Ol(e,t){if(e===null)return null;let i=lt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Hl(e,t){let i=lt(e,t);if(!wm.isAbsolute(i))throw new Error(`${t} must be absolute`);return wm.resolve(i)}function ZP(e,t){let i=`Native local checks[${t}]`,r=So(e,i);if(Eo(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,u)=>lt(l,`${i}.argv[${u}]`,!0)),a=Po(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Ol(r.startedAt,`${i}.startedAt`),s=Ol(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=xo(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:lt(r.id,`${i}.id`),name:lt(r.name,`${i}.name`),operationId:lt(r.operationId,`${i}.operationId`),status:a,repeatable:QP(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:xo(r.executionCount,`${i}.executionCount`),argv:n,cwd:Hl(r.cwd,`${i}.cwd`),exitCode:XP(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:lt(r.log,`${i}.log`)}}function ex(e){let t="Native local execution state",i=So(e,t);if(Eo(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ga)throw new Error(`Native local execution schema must be ${Ga}`);let r=So(i.workspace,"Native local workspace");Eo(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=So(i.execution,"Native local execution");Eo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Ol(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:lt(o.operationId,"Native local execution.operationId"),stage:Po(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Po(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ym(o.executionId,"Native local execution.executionId"),status:Po(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:xo(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(ZP);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:Ga,change:lt(i.change,"Native local change"),basedOnStateVersion:xo(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Hl(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Hl(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ym(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Nm(e){let t;try{t=await YP.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 ex(i)}var ix=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rx="comet-state.yaml",nx="state.json";function bm(e,t){if(!ix.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Dl.join(e.changesDir,t);if(!F(e.changesDir,i))throw new Error("Native change path escaped");return i}function km(e,t){return Dl.join(bm(e,t),rx)}function ax(e,t){return Dl.join(Li(e,t),nx)}async function Bl(e,t){try{let i=await tx.readFile(km(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Sm(e,t){return eh(km(e,t))}async function Em(e){let t=await Sm(e.paths,e.name),i=ax(e.paths,e.name);try{let r=await Nm(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var $H=16*1024;async function Pm(e){let t=await gm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(yo(t.selection.change),t.selection)}async function xm(e,t){let i=[],r=G(e,t.name),n=Mt(r,$e.stateRef),a;try{a=await er(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Mt(r,a.trajectoryRef),s=await Bh(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await vi(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Mt(r,a.checkpointRef);try{let u=await uo(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import Xx from"path";import{isDeepStrictEqual as nu}from"util";var rr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var ox=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function sx(e,t){return e<t?-1:e>t?1:0}function cx(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!ox.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(sx)}function Fl(e=[]){return cx(e,"Native repair failed check IDs",rr.maxFailedCheckIds,!0)}function Cm(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function lx(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Cm(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Cm(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ll(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(lx(r,a))break;i+=1,r=a}return i}import Gm from"node:path";import{createHash as Om}from"node:crypto";import Rm from"path";var Ml="comet.native.implementation-scope.v2",Hm="comet.native.content-snapshot-projection.v1",yn="comet.native.content-snapshot-projection.v1",Dm="comet.native.implementation-scope.v2",ux="comet.native.unresolved-scope-id.v1",dx="comet.native.scope-detail-overflow.v1",fx="comet.native.snapshot-projection-overflow.v2",zl=/^[a-f0-9]{64}$/u,yi=1024*1024,px=128,hx=128;function he(e,t){return e<t?-1:e>t?1:0}function ql(e){if(!zl.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function mx(e,t){return e===t?0:e===null?-1:t===null?1:he(e,t)}function Qt(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=Rm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Rm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Bm(e,t){return e==="."?e:Qt(e,t)}function nr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function vx(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:Qt(e.path,`${t} path`),hash:e.hash,size:nr(e.size,`${t} size`),type:"file"}}function gx(e,t){return{path:Bm(e.path,`${t} path`),size:e.size===null?null:nr(e.size,`${t} size`),type:e.type,reason:e.reason}}function wx(e,t){return he(e.path,t.path)||he(e.hash,t.hash)||e.size-t.size}function yx(e,t){return he(e.path,t.path)||he(e.reason,t.reason)||he(e.type,t.type)||(e.size??-1)-(t.size??-1)}function bn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
166
+ `,"utf8")}function Xt(e,t,i){let r=`${t}
167
+ ${gr(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function Nx(e){if(bn(e)<=yi)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Om("sha256");a.update(`${fx}
168
+ `),e.omissionOverflow&&Xt(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Xt(a,"omission",f)},s=f=>{r+=1,n+=1,Xt(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;bn(u)>yi;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<h;v+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function Vl(e){let t=mi(e),i=t.entries.map((n,a)=>vx(n,`Snapshot entry ${a}`));if(i.sort(wx),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>gx(n,`Snapshot omission ${a}`));return r.sort(yx),Nx({schema:Hm,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:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function kn(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:Qt(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>he(i.path,r.path)||he(i.kind,r.kind))}function Sn(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Am(e){return e?{hash:e.hash,size:e.size}:null}function Jl(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:he(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Am(c),after:Am(l)})}}function Fm(e,t){return{...e,attributedTo:t.filter(i=>Sn(i,e.path))}}function Gl(e){let t=kn(e.declaredArtifacts),i=[];return Jl(e.baseline,e.current,r=>{i.push(Fm(r,t))}),i}function bt(e,t){return{id:`scope:${O(ux,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function bx(e,t){let i=t.omitted.map(r=>bt({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(bt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(bt({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 _m(e,t){return bx(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Wl(e,t){return he(e.kind,t.kind)||he(e.source,t.source)||mx(e.path,t.path)||he(e.id,t.id)}function kx(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Wl)}function Lm(e){return[...new Set(e.map((t,i)=>Qt(t,`Git path ${i}`)))].sort(he)}function Tm(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function Sx(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Mm(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Lm(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Tm(e.baseCommit,"Native external drift base commit"),targetBranch:Sx(e.targetBranch,"Native external drift target branch"),targetCommit:Tm(e.targetCommit,"Native external drift target commit"),paths:t}}function qm(e){if(typeof e.contractHash!="string"||!zl.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:kn(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Lm(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Mm(e.externalDrift)}}}function Ex(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Jl(e,t,h=>{let v=i.some(p=>Sn(p,h.path));if(d+=1,c.push(h.path),!v&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<px){let p=Fm(h,i),m=bn(p);l+m<=yi?(a.push(p),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Vm(e,t){return bt({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 Px(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:nr(Number(t[1]),"Scope overflow change count"),unresolved:nr(Number(t[2]),"Scope overflow unresolved count"),unattributed:nr(Number(t[3]),"Scope overflow unattributed count")},r=wi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Vm(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function xx(e){let t=Om("sha256");t.update(`${dx}
169
+ `);let i=0;Jl(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Xt(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Sn(o,n.path)&&(a+=1,Xt(t,"change-attribution",o));Xt(t,"change-end",{attributionCount:a}),a===0&&Xt(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Xt(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Wm(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=Ex(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(S=>!w.has(S)||n.some(D=>Sn(D,S)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=O(yn,e),c=O(yn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=hx)break;l.push(bt({kind:"snapshot-omission",source:x,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${x} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[..._m("baseline",e),..._m("current",t),...o.totalChanges===0&&a===null?[bt({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")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>x.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!x.has(w))}},v=x=>{let w=o.candidates.slice(0,x.detailedChangeCount),g=w.filter(Be=>Be.attributedTo.length===0&&!u.has(Be.path)),S=o.totalChanges-w.length,D=o.totalUnattributed-g.length,I=d-x.detailedOmissionCount,de=D+I,X=[...g.map(Be=>bt({kind:"unattributed-change",source:"implementation-scope",path:Be.path,evidence:{after:Be.after,before:Be.before,changeKind:Be.kind}},`Changed path is not covered by a declared artifact: ${Be.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...de>0?[Vm(x.overflowHash,{changes:S,unattributed:D,unresolved:de})]:[]],J=kx(X),tt=x.includeGitAdvisory?h():void 0;return{schema:Ml,contractHash:r,baselineProjectionRef:ql(s),baselineProjectionHash:s,currentProjectionRef:ql(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:J,noCodeReason:a,...tt?{gitAdvisory:tt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,m=l.length,b=i.gitChangedPaths!==void 0,N="0".repeat(64);for(;;){let x=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:N});if(bn({...x,scopeHash:N})<=yi)break;if(b){b=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>p||d>m?xx({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:m}):N,E=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:k}),y={...E,scopeHash:O(Dm,E)};if(bn(y)>yi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return y}function Ul(e){let t=Vl(e.baseline),i=Vl(e.current),r=qm(e);return{authority:r,baseline:t,current:i,scope:Wm(t,i,r)}}var Cx=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function dt(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function wi(e,t){if(typeof e!="string"||!zl.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Im(e,t,i){let r=ql(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Co(e,t){let i=ut(e,"Native snapshot projection");if(dt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Hm)throw new Error("Native snapshot projection schema is invalid");let r=mi({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}}),n=Vl(r);if(O(yn,i)!==O(yn,n))throw new Error("Native snapshot projection is not canonical");let a=O(yn,n);if(t!==void 0&&wi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Kl(e,t){let i=ut(e,`Declared artifact ${t}`);if(dt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Qt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function jm(e,t){if(e===null)return null;let i=ut(e,t);return dt(i,["hash","size"],[],t),{hash:wi(i.hash,`${t} hash`),size:nr(i.size,`${t} size`)}}function $m(e,t){let i=ut(e,`Implementation change ${t}`);if(dt(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 r=i.attributedTo.map(Kl),n=kn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=jm(i.before,`Implementation change ${t} before`),o=jm(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:Qt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function Rx(e,t){let i=ut(e,`Unresolved scope ${t}`);dt(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.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"?Bm(i.path,`Unresolved scope ${t} path`):Qt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Nn(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>Qt(n,`${t} ${a}`)),r=[...new Set(i)].sort(he);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function zm(e){let t=ut(e,"Native implementation external drift");if(dt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Nn(t.paths,"Native external drift paths");return Mm({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function Ro(e){let t=ut(e,"Native implementation scope"),i=[...Cx].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(dt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Ml)throw new Error("Native implementation scope schema is invalid");let r=wi(t.contractHash,"Implementation scope contractHash"),n=wi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Im(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=wi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Im(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(Kl);if(JSON.stringify(c)!==JSON.stringify(kn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map($m),u=[...l].sort((g,S)=>he(g.path,S.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(g=>g.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(g=>`${g.kind}:${g.path}`));if(l.some(g=>g.attributedTo.some(S=>!d.has(`${S.kind}:${S.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(S=>Sn(S,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map($m),h=t.externalDrift===void 0?void 0:zm(t.externalDrift),v=new Set(h?.paths??[]),p=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(Rx),b=m.filter(g=>g.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let N=b[0]===void 0?null:Px(b[0]);if(N&&(N.changes+N.unresolved===0||N.unattributed>N.changes||N.unattributed>N.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let P=t.noCodeReason,k=[...p.map(g=>bt({kind:"unattributed-change",source:"implementation-scope",path:g.path,evidence:{after:g.after,before:g.before,changeKind:g.kind}},`Changed path is not covered by a declared artifact: ${g.path}`)),...l.length+(N?.changes??0)===0&&P===null?[bt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Wl))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(k.sort(Wl))||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 y;if(t.gitAdvisory!==void 0){let g=ut(t.gitAdvisory,"Implementation scope Git advisory");if(dt(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let S=Nn(g.changedPaths,"Git changed paths"),D=Nn(g.pathsPresentInSnapshotChanges,"Git present paths"),I=Nn(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),de=[...D,...I].sort(he);if(JSON.stringify(de)!==JSON.stringify(S)||I.some(X=>l.some(J=>J.path===X)))throw new Error("Implementation scope Git advisory partition is invalid");y={advisoryOnly:!0,changedPaths:S,pathsPresentInSnapshotChanges:D,pathsAbsentFromSnapshotChanges:I}}let x={schema:Ml,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:P,...y?{gitAdvisory:y}:{},...h?{externalDrift:h}:{}},w=wi(t.scopeHash,"Implementation scope scopeHash");if(O(Dm,x)!==w)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:w}}function Ax(e){let t=ut(e,"Native implementation scope authority");if(dt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Kl);if(JSON.stringify(i)!==JSON.stringify(kn(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 r;t.gitChangedPaths!==void 0&&(r=Nn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:zm(t.externalDrift),a=qm({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function En(e){let t=ut(e,"Native implementation scope bundle");dt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Ax(t.authority),r=Co(t.baseline),n=Co(t.current),a=Ro(t.scope),o=Wm(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function Jm(e){let t=Ro(e.scope);return En({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var Km=/^[a-f0-9]{64}$/u;var _x="comet.native.acceptance-trace.v2",Tx="comet.native.partial-allowance.v1",Ix="comet.native.verification-evidence.v2";function kt(e,t){if(!Km.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ym(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Xm(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 Yl(e,t,i=2e3){let r=Oe(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Pn(e,t){let i=Gm.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Gm.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 jx(e,t,i){let r=Pn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=nt(r),a=r.toLowerCase(),o=i?Pn(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Xl(e){let t=Pn(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 ar(e,t){return e<t?-1:e>t?1:0}function Ao(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _o(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Qm(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 Um(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function $x(e){let t=Ao(e,"Native acceptance trace");if(_o(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"||!Km.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=Pn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Ao(o,`Native acceptance trace entry ${s}`);if(_o(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Xl(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ar))||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:Pn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Yl(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>ar(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=kt(t.traceHash,"Native acceptance trace hash");if(O(_x,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Zm(e){let t=Ao(e,"Native partial allowance");if(_o(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(ar))||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:Xm(t.change),scopeHash:kt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Yl(t.reason,"Partial allowance reason"),confirmedSummary:Yl(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ym(t.sourceRevision),confirmedAt:Qm(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 r=kt(t.allowanceHash,"Native partial allowance hash");if(O(Tx,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Ql(e){let t=Ao(e,"Native verification evidence");if(_o(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=kt(t.implementationScopeHash,"Native verification implementation scope hash"),r=$x(t.acceptanceTrace),n=kt(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:kt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Xl(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ar)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(ar);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Xl(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ar)))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:Xm(t.change),sourceRevision:Ym(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:kt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Um(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:jx(t.reportRef,"Native verification report ref"),reportHash:kt(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Um(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Qm(t.createdAt,"Native verification timestamp")},d=kt(t.envelopeHash,"Native verification envelope hash");if(O(Ix,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Zl(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 ev="repairStagnation",Re={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},Hx=/^[a-f0-9]{64}$/u;var Dx=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),Bx=["data","runId","sequence","timestamp","type"],tv=["disposition","overrideSummaryHash","signatureHash"],Fx=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],iv=12;function tu(e,t){return e<t?-1:e>t?1:0}function rv(e,t,i){let r=Object.keys(e).sort(tu);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function To(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 xn(e,t){if(typeof e!="string"||!Hx.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Lx(e){if(!Array.isArray(e)||e.length>rr.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(tu)}function nv(e){if(typeof e!="string"||e.length===0||e.length>Re.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function eu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Re.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Re.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Re.maxTextCharacters&&(!n||e.length>Re.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Re.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Re.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>eu(s,t+1,i,`${r}[${c}]`));return}let a=To(e,r),o=Object.keys(a);if(o.length>Re.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Re.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Re.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");eu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function Mx(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function qx(e,t,i){let r=To(e,`Native repair trajectory event ${t+1}`);if(rv(r,Bx,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(Mx(r.timestamp),typeof r.type!="string"||!Dx.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(nv(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return eu(r.data,0,n,"Native trajectory event data"),To(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function iu(e){let t=To(e,"Native repair trajectory projection"),i=Object.keys(t).sort(tu),r=i.length===tv.length&&i.every((l,u)=>l===tv[u]);r||rv(t,Fx,"Native repair trajectory projection");let n=xn(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:xn(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(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=xn(t.contractHash,"Native repair trajectory contract hash"),s=Lx(t.failedAcceptanceIds),c=Fl(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function Vx(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function Wx(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??iv;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ll({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<rr.warningAtConsecutiveFailures?"continue":a<rr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function zx(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??iv;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function av(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Re.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=nv(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=qx(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Re.maxTotalDataNodes||c>Re.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?xn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?xn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,ev)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=iu(f[ev]);if(Vx(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),Wx(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");zx(v,i,r);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>rr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function ov(e){return av(e).history}function sv(e){let t=av(e).latestProjection;return t?{...t}:null}var or={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:[]},ru=U("comet-native-runtime:v3:scope-reopen"),Jx=[{skillVersion:"3",skillHash:U("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:U("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:U("comet-native-runtime:v1")}];function cv(e){return e.skillVersion===or.definition.metadata.version&&e.skillHash===ru||Jx.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function lv(e){return U(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var hv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Qx=new Set(hv),mv=new Set([...hv,"minimum_runtime_version","revision"]),Zx=new Set([...mv,"operation"]),eC=512*1024,au=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),tC=new Set([...au,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),ou=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 cu(e,t){return Xx.join(G(e,t),"transition.json")}function jo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function lu(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Io(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function su(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!tC.has(u)),a=[...au].find(u=>!Object.hasOwn(i,u)),o=au.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`: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(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Zl(i.summary,"Native transition journal event summary"),Oe(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&&(Zl(i.noCodeReason,"Native transition journal event no-code reason"),Oe(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")?iu(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,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function iC(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return su({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return su(e,t)}function uu(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 r=i?iC(e.eventData,e.evidenceHash):su(e.eventData,e.evidenceHash),n=bl(e.nextRun),a=e.previousRun===null?null:bl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function uv(e,t,i=!1){if(e.skill!==or.definition.metadata.name||(i?!cv(e):e.skillVersion!==or.definition.metadata.version||e.skillHash!==ru)||e.orchestration!==or.definition.orchestration.mode||e.pendingRef!==$e.pendingRef||e.trajectoryRef!==$e.trajectoryRef||e.contextRef!==$e.contextRef||e.artifactsRef!==$e.artifactsRef||e.checkpointRef!==$e.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function dv(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 fv(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 du(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(uv(o,"next Run",r||a!==null),fv(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(uv(a,"previous Run",!0),fv(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!nu(dv(a),dv(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function rC(e,t,i){return U(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function vv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function pv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function fu(e,t,i,r,n=!1){let a=i.eventData,o=pv(e),s=pv(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(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&nu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="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&&nu(e.spec_changes,t.spec_changes),l=lv({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||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(r==="spec-rebase"){let c=rC(e.name,a.summary,t.spec_changes),l=U(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&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 nC(e,t){let i=jo(e);if(lu(i,Zx),i.schema!==Wi)throw new Error(`Expected Native transition schema ${Wi}`);let r=Io(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${Wi} minimum_runtime_version must be ${3}`);let n=Io(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=uu(i,t),o=zt(i.previousState),s=zt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(fu(o,s,a,i.operation),du(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Wi,minimum_runtime_version:3,revision:n,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 aC(e,t){let i=jo(e);if(lu(i,Qx),i.schema!==an)throw new Error(`Expected Native transition schema ${an}`);let r=uu(i,t,!0),n=Ji(i.previousState),a=Ji(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return fu(n,a,r,vv(n,a,r.eventData),!0),du(n,a,r,!0),{schema:an,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function oC(e,t){let i=jo(e);if(lu(i,mv),i.schema!==zi)throw new Error(`Expected Native transition schema ${zi}`);if(Io(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${zi} minimum_runtime_version must be 2`);let n=Io(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=uu(i,t,!0),o=Gi(i.previousState),s=Gi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(fu(o,s,a,vv(o,s,a.eventData),!0),du(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:zi,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function sC(e,t){let i=jo(e);if(i.schema===Wi)return{status:"current",journal:nC(i,t)};if(i.schema===an)return{status:"migration-required",journal:aC(i,t)};if(i.schema===zi)return{status:"migration-required",journal:oC(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function cC(e,t){let i=cu(e,t),r=oe(e,i);await z(r,i);try{let n=await vt({root:r,file:i,maxBytes:eC,label:`Native transition journal ${t}`});return sC(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function gv(e,t){let i=await cC(e,t);if(!i)return null;if(i.status==="migration-required")throw new ou(t);return i.journal}var lC=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function uC(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function dC(e){return e?e.map(uC).join(" "):null}function fC(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function He(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function pC(e){return e.map(t=>He(t,[],null))}function hC(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[He("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(He("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(He("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),He("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(He("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(He("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),He("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function me(e,t){let i=t.commandArgs===void 0?fC(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?dC(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??pC(t.requiredInputs??[])}}function $o(e){let i=(e.findings??[]).filter(d=>!tr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||lC.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return me(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return me(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[He("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return me(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return me(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return me(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[He("summary",["--summary"],"<summary>")]});if(n)return me(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[He("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return me(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?me(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?me(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):me(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),me(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[He("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):me(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return me(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=hC(e.state);return me(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Cn from"path";var wv=8,mC={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function vC(e){let t=mC[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:tr(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function gC(e,t,i){if(!i.path)return null;let r;if(Cn.isAbsolute(i.path)?r=Cn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Cn.resolve(ue(e,t.name),...i.path.split(/[\\/]/u)):r=Cn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!F(e.projectRoot,r))return null;let n=Cn.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function wC(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function pu(e){return e.findings.map(t=>{let i=vC(t.code);return{code:t.code,message:t.message,severity:i.severity,path:gC(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:wC(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function hu(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,wv),truncated:t.length>wv}}import sr from"path";var ei={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},cr=/^[a-f0-9]{64}$/u;function Oo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ho(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Zt(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 yv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function yC(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||sr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=sr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Nv(e,t){return sr.join(G(e,t),"checkpoints","progress.json")}function Rn(e,t){return sr.join(G(e,t),"checkpoint-journal.json")}function bv(e,t,i){if(!cr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return sr.join(G(e,t),"checkpoints","manifests",`${i}.json`)}function NC(e){if(!cr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function vu(e,t,i){let r=await vt({root:e,file:t,maxBytes:ei.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function bC(e,t){let i=Oo(e,`checkpoint manifest artifact ${t}`);Ho(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=yC(Zt(i.path,`checkpoint artifact ${t} path`,4096)),n=nt(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!cr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:mu(i.size,`checkpoint artifact ${t} size`)}}function gu(e,t){let i=Oo(e,"Native checkpoint manifest");if(Ho(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>ei.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(bC),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=mu(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>ei.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function kv(e){return U(JSON.stringify(gu(e,e.change)))}function Sv(e,t){let i=Oo(e,"Native progress checkpoint");if(Ho(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 r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=yv(i.previousRevision,"Native checkpoint previousRevision"),a=yv(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Zt(i.manifestHash,"Native checkpoint manifestHash",64);if(!cr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=NC(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Zt(i.inputHash,"Native checkpoint inputHash",64);if(!cr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Zt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=mu(i.artifactCount,"Native checkpoint artifactCount");if(u>ei.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Zt(i.summary,"Native checkpoint summary"),f=Zt(i.nextAction,"Native checkpoint nextAction");if(Oe(d)!==d||Oe(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Zt(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function kC(e,t){let i=Oo(e,"Native checkpoint journal");if(Ho(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 r=zt(i.previousState),n=zt(i.nextState),a=Sv(i.checkpoint,t),o=gu(i.manifest,t),s=Zt(i.inputHash,"Native checkpoint journal inputHash",64),c=U(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!cr.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==kv(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:r,nextState:n,checkpoint:a,manifest:o}}async function SC(e,t,i){let r=sr.resolve(e.projectRoot,...t.split("/"));if(!F(e.projectRoot,r)||F(e.nativeRoot,r)||F(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Ic(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await vt({root:e.projectRoot,file:r,maxBytes:ei.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function EC(e,t){let i=Nv(e,t),r=oe(e,i);await z(r,i);try{return Sv(await vu(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function PC(e,t,i){let r=bv(e,t,i),n=oe(e,r);await z(n,r);let a=await vu(n,r,"Native checkpoint manifest"),o=gu(a,t);if(Ev(e,o),kv(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function wu(e,t){let i=Rn(e,t),r=oe(e,i);await z(r,i);try{let n=kC(await vu(r,i,"Native checkpoint journal"),t);return Ev(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Ev(e,t){for(let i of t.artifacts){let r=Ic(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Pv(e){let t;try{t=await EC(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Nv(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await PC(e.paths,e.name,t.manifestHash);let a=U(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await SC(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:bv(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var xv=240,Cv=8,Do=50;function Rv(e){let t=Array.from(e);return t.length<=xv?e:`${t.slice(0,xv-1).join("")}…`}function xC(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function CC(e){let t=[...new Set(e.map(xC))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Cv),reasonCount:e.length,codesTruncated:t.length>Cv};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Do),reasonsTruncated:e.length>Do}}}async function Av(e){let t=null;try{let s=await wu(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Rn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Rn(e.paths,e.state.name)}}let i=await Pv({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=CC(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ei.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Rv(i.checkpoint.summary),nextAction:Rv(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ei.maxArtifacts}}import{promises as hA}from"node:fs";import lg from"node:path";import _v from"node:path";var RC="comet.native.archive-preflight.v1",AC="comet.native.archive-preflight.v1",_C="comet.native.archive-operation.v1",TC=/^[a-f0-9]{64}$/u,Tv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Bo(e,t){return e<t?-1:e>t?1:0}function jC(e,t){if(typeof e!="string"||!TC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){return e===null?null:jC(e,t)}function $C(e,t){let i=_v.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||_v.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 OC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function HC(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(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function DC(e,t){if(!Tv.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=St(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=St(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=St(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"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function BC(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:St(e.contractHash,"Native archive contract hash"),acceptanceHash:St(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:St(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:St(e.reportHash,"Native archive report hash"),envelopeHash:St(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:St(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 FC(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!IC.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(Bo);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function LC(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(Bo)}function Iv(e){if(!Tv.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(DC).sort((l,u)=>Bo(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:O(_C,l)})),r=BC(e.evidence),n=HC(e.workspace),a=[...new Set([...FC(e.findingCodes??[]),...LC({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(Bo),o=OC(e.revision),s=$C(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:r,workspace:n,findingCodes:a};return{schema:RC,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:O(AC,c)}}import{createHash as MC}from"node:crypto";import jv from"node:path";var qC="comet.native.conflict-radar.v1",ke=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),VC="comet.native.conflict-radar.v1",WC="comet.native.conflict-radar-signals.v1",zC=/^[a-f0-9]{64}$/u,Hv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JC=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),GC=new Set(["capability","operation","baseHash"]),UC=new Set(["path","kind"]);function lr(e,t){return e<t?-1:e>t?1:0}function yu(e){return Buffer.byteLength(e,"utf8")}function Nu(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function bu(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(yu(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function KC(e,t){let i=bu(e,t,ke.maxArtifactPathBytes),r=jv.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||jv.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Dv(e,t){if(typeof e!="string"||!zC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function YC(e,t){let i=Nu(e,GC,t),r=bu(i.capability,`${t} capability`,ke.maxCapabilityBytes);if(!Hv.test(r))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 n=i.baseHash===null?null:Dv(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function XC(e,t){let i=Nu(e,UC,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:KC(i.path,`${t} path`),kind:i.kind}}function QC(e,t){let i=Nu(e,JC,`Conflict radar change ${t}`),r=bu(i.name,`Conflict radar change ${t} name`,ke.maxNameBytes);if(!Hv.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ke.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ke.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>YC(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>lr(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>XC(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>lr(c.path,l.path)||lr(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Dv(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function ZC(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ke.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(QC).sort((n,a)=>lr(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ke.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ke.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function eR(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 tR(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function iR(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function rR(e,t){let i=[],r=MC("sha256").update(`${WC}
170
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(gr(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ke.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(eR(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=tR(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:iR(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function $v(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function nR(e,t){return $v(e.classification)-$v(t.classification)||lr(e.left,t.left)||lr(e.right,t.right)}function Ov(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:qC,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Bv(e){let t=ZC(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(rR(t[s],t[c]));i.sort(nR);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=O(VC,{changes:t,relationships:r}),a=i.slice(0,ke.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Ov(t,i,a,n);for(;a.length>0&&yu(JSON.stringify(o))>ke.maxSerializedBytes;)a=a.slice(0,-1),o=Ov(t,i,a,n);if(yu(JSON.stringify(o))>ke.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as DR}from"node:crypto";import{promises as Ze}from"node:fs";import ft from"node:path";import Fv from"node:path";var Lv="comet.native.check-receipt.v1",aR="comet.native.check-receipt.v1",ur="scoped-text-safety",ku=1,Se=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),oR=/^[a-f0-9]{64}$/u,sR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cR="comet.native.checker-policy.v1",lR="comet.native.check-input.v1",uR=2048,Mv=O(cR,{policy:ur,version:ku,limits:Se,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),dR=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),qv=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Wv=["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"],fR=new Set(Wv);function ti(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ii(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Et(e,t){if(typeof e!="string"||!oR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ae(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function zv(e,t){let i=Ae(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Vv(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 pR(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>uR||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=Fv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Fv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function hR(e){let t=ti(e,"Native check receipt checker");ii(t,["policy","version","hash","limits"],"Native check receipt checker");let i=ti(t.limits,"Native check receipt limits");if(ii(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ur||t.version!==ku||t.hash!==Mv||i.maxFiles!==Se.maxFiles||i.maxFileBytes!==Se.maxFileBytes||i.maxTotalBytes!==Se.maxTotalBytes||i.maxIssues!==Se.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ur,version:ku,hash:Mv,limits:{...Se}}}function mR(e){let t=ti(e,"Native check receipt contract");return ii(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Et(t.expectedHash,"Native check expected contract hash"),beforeHash:Et(t.beforeHash,"Native check before contract hash"),afterHash:Et(t.afterHash,"Native check after contract hash")}}function vR(e){let t=ti(e,"Native check receipt implementation");return ii(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Et(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Et(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Et(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Et(t.afterSnapshotHash,"Native check after snapshot hash")}}function gR(e,t){let i=ti(e,`Native check batch ${t}`);ii(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Ae(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Ae(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Ae(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Ae(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Ae(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Ae(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Se.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Se.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function wR(e){let t=ti(e,"Native check receipt counts");ii(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Ae(t.filesSelected,"Native check filesSelected"),filesScanned:Ae(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Ae(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Ae(t.bytesScanned,"Native check bytesScanned"),issueCount:Ae(t.issueCount,"Native check issueCount"),recordedIssueCount:Ae(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(gR):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Se.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Se.maxFiles||i.bytesScanned>Se.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function yR(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||qv.indexOf(e.kind)-qv.indexOf(t.kind)}function NR(e){if(!Array.isArray(e)||e.length>Se.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=ti(r,`Native check issue ${n}`);if(ii(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!dR.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:pR(a.path,`Native check issue ${n} path`),line:zv(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(yR);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function bR(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!fR.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Wv.filter(r=>t.includes(r));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 kR(e){return O(lR,e)}function Jv(e){let t=ti(e,"Native check receipt");if(ii(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Lv)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!sR.test(t.change))throw new Error("Native check receipt change name is invalid");let i=zv(t.sourceRevision,"Native check source revision"),r=hR(t.checker),n=mR(t.contract),a=vR(t.implementation),o=kR({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Et(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=Vv(t.startedAt,"Native check receipt startedAt"),c=Vv(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=wR(t.counts),u=NR(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=bR(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Se.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Se.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Lv,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Et(t.receiptHash,"Native check receipt content hash");if(O(aR,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var Eu="comet.native.verification-receipt.v3",SR=Eu,ER="comet.native.declared-artifacts.v1",PR=/^[a-f0-9]{64}$/u,xR=/^acceptance-[a-f0-9]{64}$/u,CR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RR=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,AR=4096,_R=256,TR=1024;function dr(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 ri(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Pt(e,t){if(typeof e!="string"||!PR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Qe(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Oe(e).trim();if(!i||i.length>AR||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Su(e,t){let i=Qe(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function An(e,t,i=Qe,r=!1,n=_R){if(!Array.isArray(e)||e.length>n||!r&&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 IR(e,t){if(typeof e!="string"||!xR.test(e))throw new Error(`${t} is invalid`);return e}function jR(e){let t=dr(e,"Native verification receipt bindings");if(ri(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!CR.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:Pt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Pt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Pt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Pt(t.artifactHash,"Native verification receipt artifact hash")}}function $R(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=RR.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function OR(e,t,i,r){let n=dr(t,`Native ${e} evidence`);if(e==="automated-check"){if(ri(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Su(n.startedAt,"Native automated-check start time"),o=Su(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=dr(n.worktree,"Native automated-check worktree");if(ri(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=dr(n.afterFence,"Native automated-check after fence");if(ri(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:Qe(n.executable,"Native automated-check executable"),args:An(n.args,"Native automated-check arguments",Qe,!0),cwd:Qe(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Qe(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Pt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Pt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Pt(n.outputHash,"Native automated-check output hash"),outputSummary:Qe(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ri(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=$R(n.checkReceiptRef);if(Pt(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:An(n.subjects,"Native static inspection subjects",Qe,r==="required-check"),rule:Qe(n.rule,"Native static inspection rule"),resultSummary:Qe(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ri(n,["steps","observations"],"Native manual-evidence evidence"),{steps:An(n.steps,"Native manual evidence steps"),observations:An(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function HR(e){let t=dr(e,"Native verification receipt");if(ri(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,r=t.role,n=t.status,a=Qe(t.actor,"Native verification receipt actor"),o=An(t.acceptanceIds,"Native receipt acceptance IDs",IR,r==="required-check",TR).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Eu,kind:i,role:r,status:n,bindings:jR(t.bindings),acceptanceIds:o,actor:a,issuedAt:Su(t.issuedAt,"Native verification receipt issue time"),evidence:OR(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ur||s.actor!==`native-runtime:${ur}`))throw new Error("Native required check policy identity is invalid");return s}function Gv(e){let t=dr(e,"Native verification receipt");if(ri(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Eu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=HR(r),a=Pt(t.receiptHash,"Native verification receipt hash");if(O(SR,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Pu(e){return O(ER,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Xv=/^[a-f0-9]{64}$/u,fr=yi,CB=3*fr;function xu(e,t){let i=ft.relative(e,t);return i===""||!ft.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ft.sep}`)}function BR(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fo(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ye(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Uv(e){let t=await Ze.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Ze.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function FR(e,t){let i=ft.resolve(e),r=ft.resolve(t);if(!xu(i,r))throw new Error("Native evidence path is outside its change");let n=[await Uv(i)],a=i;for(let o of ft.relative(i,r).split(ft.sep).filter(Boolean)){a=ft.join(a,o);let s=await Uv(a);if(!xu(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Kv(e){for(let t of e){let i=await Ze.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!BR(t,i)||await Ze.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function LR(e,t,i={}){let r=await FR(t,ft.dirname(e));await i.afterParentChainCaptured?.();let n=await Ze.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Ze.realpath(e);if(!xu(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Ze.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Ze.lstat(e),Ze.realpath(e)]);if(await Kv(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fo(s,n)||!Fo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>fr)throw new Error(`Native evidence document exceeds ${fr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=fr+1-d,b=await o.read(f,0,Math.min(f.length,m),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>fr)throw new Error(`Native evidence document exceeds ${fr} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,p]=await Promise.all([o.stat(),Ze.lstat(e),Ze.realpath(e)]);if(await Kv(r),!v.isFile()||v.isSymbolicLink()||p!==a||!Fo(s,h)||!Fo(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Qv(e,t){if(!Xv.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function MR(e,t,i,r,n){if(!Xv.test(i))throw new Error("Native report evidence hash is invalid");let a=await Ni({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||DR("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 pr(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 qR(e,t,i,r,n){let a=Qv(i,r);return n?ft.join(n,...a.split("/")):Mt(G(e,t),a)}async function Ni(e){let t=qR(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??oe(e.paths,t);return await z(i,t),LR(t,i,e.hooks)}function Yv(e,t){return Co(e,t)}function VR(e,t){let i=Ro(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function WR(e,t,i){let r=Zm(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function zR(e,t,i){let r=Ql(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function JR(e,t,i,r=!1,n){let a=await Lo(e,t,i.implementationScopeRef,void 0,n);if(r&&await MR(e,t,i.reportHash,void 0,n),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 Zv(e,t,i.partialAllowanceRef,void 0,n);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 _n(e,t,i,r,n){let a=pr(i,"scopes"),o=VR(await Ni({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=pr(o.baselineProjectionRef,"snapshots"),c=pr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ni({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Yv(d,s)),Ni({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Yv(d,c))]);return Jm({baseline:l,current:u,scope:o})}async function Lo(e,t,i,r,n){return(await _n(e,t,i,r,n)).scope}async function Zv(e,t,i,r,n){let a=pr(i,"allowances");return WR(await Ni({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Tn(e,t,i,r,n){let a=pr(i,"receipts"),o=Gv(await Ni({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function hr(e,t,i,r,n){let a=pr(i,"verifications"),o=zR(await Ni({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await JR(e,t,o,!1,n),o}var GR=4096;async function UR(e,t=ke.maxChanges){try{let i=await on({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 eg(e,t){let i=await Nt(e,t),[r,n]=await Promise.all([i.implementation_scope?Lo(e,t,i.implementation_scope):null,wt(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:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Mo(e,t,i={}){let n=(await UR(e,GR)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await eg(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await eg(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Bv([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{execFile as aA}from"node:child_process";import{promisify as oA}from"node:util";import{constants as Cu,promises as De}from"node:fs";import mr from"node:path";var YR=/^[a-f0-9]{64}$/u,XR=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,In=512*1024;function QR(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qo(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ye(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ZR(e,t){let i=mr.resolve(e),r=mr.resolve(t);if(!F(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...mr.relative(i,r).split(mr.sep).filter(Boolean)]){o&&(a=mr.join(a,o));let s=await De.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await De.realpath(a);if(n.length>0&&!F(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function ig(e){for(let t of e){let i=await De.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!QR(t,i)||await De.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function eA(e){if(!YR.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function tA(e){let t=XR.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function iA(e,t,i){return Mt(G(e,t),eA(i))}async function rA(e,t,i){let r=await ZR(i,mr.dirname(e)),n=await De.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>In)throw new Error(`Native check receipt exceeds ${In} bytes`);let[a,o]=await Promise.all([De.realpath(t),De.realpath(e)]);if(!F(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Cu.O_RDONLY|Cu.O_NOFOLLOW|Cu.O_NONBLOCK,c=await De.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),De.lstat(e),De.realpath(e)]);if(await ig(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!qo(n,l)||!qo(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let N=In+1-h,P=await c.read(v,0,Math.min(v.length,N),null);if(P.bytesRead===0)break;if(h+=P.bytesRead,h>In)throw new Error(`Native check receipt exceeds ${In} bytes`);f.push(Buffer.from(v.subarray(0,P.bytesRead)))}let[p,m,b]=await Promise.all([c.stat(),De.lstat(e),De.realpath(e)]);if(await ig(r),!m.isFile()||m.isSymbolicLink()||b!==o||!F(a,b)||!qo(l,p)||!qo(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function rg(e,t,i){let r=tA(i),n=G(e,t),a=iA(e,t,r),o=oe(e,a);await z(o,a);let s=Jv(await rA(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var jn=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var NF=64*1024;var bF=3600*1e3;var kF=oA(aA);var sA=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ng(e,t){let i=[];for(let r of sA){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function ag(e){if(e.receipt.kind!=="static-inspection")return null;let t=await rg(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(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function cA(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 lA(e){let t=cA(e.bundle.baseline),i=await yl(e.paths,t,{origin:"explicit",now:e.now});return Ul({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function sg(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await _n(e.paths,e.state.name,e.state.implementation_scope),i=await ir({changeDir:ue(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await lA({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function cg(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await sg(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function uA(e){let t=await ce({root:ue(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Qp(t.text)}}function dA(e){let{receipt:t,implementationScope:i}=e,r=[],n=Gl({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function fA(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:Pu(e.implementationScope.scope.declaredArtifacts)}}async function og(e){let t=await Tn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=ng(t,e.expectedBindings);if(i.push(...r.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 n=await ag({paths:e.paths,state:e.state,receipt:t});if(n){let a=dA({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function pA(e){let t=fA({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await og({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof ni)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await og({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.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(r.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 Ru(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Au(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Ru(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([sg(e),hr(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:Ru(e.state.verification_result,"stale"),envelope:null};let r=await uA({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.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)&&n.push("verification-state-mismatch");try{await pA({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{n.push("verification-receipt-invalid")}let a=[...new Set(n)].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:Ru(e.state.verification_result,"invalid"),envelope:null}}}function mA(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function ug(e){try{return await hA.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vA(e,t){try{return(await ce({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function gA(e,t,i){let r=bo(e,i.capability);if(!F(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=lg.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await vA(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ce({root:ue(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 wA(e,t){return ug(cu(e,t))}async function _u(e){let t=e.now??new Date,i=await Nt(e.paths,e.name),r=await wt(e.paths,e.name),n=await ze(e.paths.projectRoot),a=mA(i.name,t),o=lg.resolve(e.paths.nativeRoot,...a.split("/"));if(!F(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>gA(e.paths,i.name,v))),Au({paths:e.paths,state:i,now:t}),Mo(e.paths,i.name),No(e.paths,i.name),tm(e.paths,i.name),wA(e.paths,i.name),ug(o)]);return Iv({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function yA(e,t){let i=G(e,t.name),r=await er(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await uo(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await vi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function NA(e,t){let i=await yA(e,t);return{committed:i,latest:sv(i),history:ov(i)}}async function dg(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await NA(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var xt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function kA(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function SA(e){return(await Pm(e))?.change??null}function EA(e,t,i=!1,r){return $o({state:e,archiveReady:t,evidenceRetreat:i}).command}async function PA(e,t){let i=ue(e,t.name),r=[...(await Il(i,t.brief)).findings,...(await cm(e,t)).findings,...await xm(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await no(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await _h(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await ir({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await gv(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await jl(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Tu(e,t,i){let r=await SA(e)===t,n=await Gc(e,t),a=await ho(e,t),o;try{let g=await _l(e,t);if(g.status==="migration-required"&&g.state)return{name:t,phase:g.state.phase,revision:"revision"in g.state?g.state.revision:null,approval:g.state.approval,verificationResult:g.state.verification_result,specChanges:g.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,migrationRequired:!0,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message};if(g.status!=="current"||!g.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${t} is incompatible`};o=g.state}catch(g){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:g.message}}if(n.status!=="available"){let g={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},S=pu({paths:e,state:o,findings:[g]}),D=$o({state:o,findings:S});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:D.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:hu(S),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:D,workspace:a,runtime:n,...i?.details?{findings:S}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await Av({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await dg(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let g=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:g,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let g=await ir({changeDir:ue(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),S=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let de=await hr(e,o.name,o.verification_evidence);for(let X of de.acceptanceTrace.entries)S.set(X.acceptanceId,X.status==="failed"?"failed":X.status==="missing"?"missing":"satisfied")}let D=Yp({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:S,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),I=D.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",D.nextCursor,"--project-root",e.projectRoot]:null;u={...D,...I?{nextPageCommand:kA(I),nextPageArgs:I}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Mo(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(S=>({code:S,message:`Native change overlap is visible in the current root: ${S}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await wt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let S=await pn({paths:e,identity:g});S.state==="drifted"&&S.code&&f.push({code:S.code,message:S.message??"Native workspace binding is no longer valid"})}else{let S=await mo({paths:e,identity:g});f.push(...S.findingCodes.map(D=>({code:D,message:`Native workspace advisory changed: ${D} (${S.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let g=await cg({paths:e,state:o});v=g.freshness!=="fresh",h.push(...g.findingCodes.map(S=>({code:S,message:`Native Verify implementation scope is not current: ${S}`})))}let p=null,m=[];if(o.phase==="archive")try{p=await _u({paths:e,name:o.name}),m.push(...p.findingCodes.map(g=>({code:g,message:`Native Archive is blocked: ${g}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await PA(e,o),...s.findings,...d,...f,...h,...l,...m].filter((g,S,D)=>D.findIndex(I=>I.code===g.code&&I.path===g.path)===S),N=pu({paths:e,state:o,findings:b}),P=N.filter(g=>!tr(g.code)),k=o.phase==="archive"&&p?.ready===!0&&P.length===0,E=v||o.phase==="archive"&&(p?.findingCodes??[]).some(g=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(g)),y=N.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",w=N.find(g=>g.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:y||x?null:EA(o,k,E,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:hu(N),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:$o({state:o,findings:N,archiveReady:k,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:N.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Do,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:N.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...w?{error:w.message}:{}}}async function fg(e){let t;try{t=await cl({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await bA.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>xt.maxChanges))throw new Error(`Native status exceeds ${xt.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function pg(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")}}function xA(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function CA(e,t){let i=Fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function Iu(e){let t=await Em(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=CA(e.paths,t.state),n=pg(t.state),a=r.bindingState==="mismatch"?{...n,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...n.runnerAction,kind:"none"}}:n;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:xA(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},continuation:a,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}var RA=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function ju(e,t){let i=ai.normalize(e),r=ai.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function AA(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function hg(e){let t=[];for(let i of await fg(e))t.push({name:i,kind:await Bl(e,i)?"portable":"legacy"});return t}async function wg(e){let t=Dn(e),i=t.length>0?t:[ai.resolve(e)];i.some(n=>ju(n,e))||i.push(ai.resolve(e));let r=[];for(let n of[...new Set(i.map(a=>ai.resolve(a)))].sort()){let a=await ze(n);if(!a)continue;let o=await Fi(n,a.native.artifact_root);r.push({projectRoot:n,config:a,paths:o,changes:await hg(o)})}if(r.length===0){let n=await ze(e);if(!n)throw new Error(".comet/config.yaml was not found in any registered worktree");let a=await Fi(e,n.native.artifact_root);r.push({projectRoot:ai.resolve(e),config:n,paths:a,changes:await hg(a)})}return r}function mg(e,t){return e.workspace.bindingState==="aligned"?0:ju(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function yg(e,t){let i=new Map;for(let n of t)for(let a of n.changes)i.set(a.name,[...i.get(a.name)??[],{source:n,kind:a.kind}]);let r=[];for(let[n,a]of[...i.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:c,kind:l})=>{if(l==="portable"){let u=await Iu({paths:c.paths,name:n});return{source:c,name:n,kind:l,workspace:u.workspace,portableStatus:u}}return{source:c,name:n,kind:l,workspace:await ho(c.paths,n),portableStatus:null}}));o.sort((c,l)=>mg(c,e)-mg(l,e)||c.source.projectRoot.localeCompare(l.source.projectRoot));let s=o.filter(c=>c.workspace.bindingState==="aligned");s.length>1?r.push(...s):r.push(s[0]??o[0])}if(r.length>xt.maxChanges)throw new Error(`Native status discovery exceeds ${xt.maxChanges} visible changes`);return r.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function vg(e,t){let i=t.toString(36),r=O("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${i}.${r}`}function _A(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=RA.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let r=O("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:i});if(t[3]!==r)throw new Error("Native workspace status cursor integrity failed");return i}function gg(e,t){let i=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:i?AA(i):null,nextPageArgs:i}}async function TA(e,t,i){let r=null;try{r=await rm(e.source.paths,e.name)}catch{}return r?.state?{schema:"comet.native.status.v2",name:e.name,phase:r.state.phase,status:"blocked",migrationRequired:!0,legacySchema:r.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:r.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:Tu(e.source.paths,e.name,{details:t,...i?{acceptanceCursor:i}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function Ng(e,t,i){if(e.kind==="portable"){if(i)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:Iu({paths:e.source.paths,name:e.name,details:t})}return TA(e,t,i)}async function bg(e){let t=await wg(e.projectRoot),i=(await yg(e.projectRoot,t)).filter(r=>r.name===e.name);if(i.length===0){let r=t.find(n=>ju(n.projectRoot,e.projectRoot))??t[0];return Tu(r.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:r.config.native.clarification_mode,maxVerifyFailures:r.config.native.max_verify_failures})}if(i.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${i.map(r=>r.source.projectRoot).join(", ")}`);return Ng(i[0],e.details??!1,e.acceptanceCursor)}async function kg(e){let t=await wg(e.projectRoot),i=await yg(e.projectRoot,t),r=O("comet.native.workspace-status-candidates.v1",i.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=_A({candidatesHash:r,total:i.length,cursor:e.cursor}),a=await Promise.all(i.slice(n,n+xt.maxItems).map(u=>Ng(u,!1))),o=[],s=i.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,h=f<i.length?vg(r,f):null,v={schema:s,total:i.length,offset:n,items:d,nextCursor:h,...gg(ai.resolve(e.projectRoot),h),limits:{...xt}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>xt.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<i.length?vg(r,c):null;return{schema:s,total:i.length,offset:n,items:o,nextCursor:l,...gg(ai.resolve(e.projectRoot),l),limits:{...xt}}}import Hu from"path";var a1={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var v1=16*1024*1024,g1=256*1024,w1=16*1024;var S1=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var lM=16*1024*1024,Vo=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"},Wo=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 dM=8*1024*1024;var zo=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Sg=["--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."],Ou=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:Sg,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]
171
+ 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]
172
+ 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 $u(e,t){return`${e}:
173
+ ${t.map(i=>` ${i}`).join(`
174
+ `)}`}function OA(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Ou[i]||t.length>1&&Ou[t[0]]?.subcommands?i:t[0]}function HA(e=[]){let t=OA(e),i=Ou[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",$u("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Sg];return n&&n.length>0&&r.push("",$u("Options",n)),r.push("",`Output:
175
+ ${i.output}`),i.examples&&r.push("",$u("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
176
+ `)}
177
+ `}}var DA=HA().usage;var IM=10*1024*1024,et=class extends Error{};function Jo(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new et(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Go(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new et(`${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 et(`${t} requires a value`);return e.splice(r,2),n}function Pg(e){if(e.length>0)throw new et(`Unexpected argument: ${e[0]}`)}function Eg(e,t){let i=Hu.normalize(e),r=Hu.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function BA(e){let t=Hu.resolve(e),i=Fe(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Fe(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Eg(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Eg(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function xg(e){return e?BA(e):zc(process.cwd())}function Cg(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
178
+ `}}function Rg(e,t){if(t instanceof et)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Vo)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 Wo)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof go)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 hn)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 zo)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof wo)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 jn)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 Ag(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 _g(e,t){let i=Jo(e,"--details"),r=Go(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!n)throw new et("status --details requires a change name");if(r&&n)throw new et("--cursor is only valid for status lists");if(r&&i)throw new et("--cursor cannot be combined with --details");Pg(e);let a=n?await bg({projectRoot:t,name:n,details:i}):await kg({projectRoot:t,...r?{cursor:r}:{}});return Cg("status",a)}function FA(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}})+`
180
+ `}}async function Tg(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{Jo(n,"--json"),s=Go(n,"--project-root");let u=[...n,...a],d=await xg(s);c=await t(u,d)}catch(u){c=Rg(e,u)}let l=o?FA(c):Ag(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
174
181
  `)?"":`
175
- `)),l.exitCode}process.exitCode=await lv("status",cv);
182
+ `)),l.exitCode}process.exitCode=await Tg("status",_g);