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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (572) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.html +8 -0
  4. package/assets/eval-reports/comet-native-vs-beta16-beta17-20260810/native-benchmark-report.json +286 -0
  5. package/assets/manifest.json +25 -17
  6. package/assets/skills/comet/SKILL.md +1 -1
  7. package/assets/skills/comet/agents/openai.yaml +3 -0
  8. package/assets/skills/comet/rules/comet-phase-guard.en.md +1 -1
  9. package/assets/skills/comet/rules/comet-phase-guard.md +1 -1
  10. package/assets/skills/comet/rules/comet-workflow-guard.en.md +2 -2
  11. package/assets/skills/comet/rules/comet-workflow-guard.md +2 -2
  12. package/assets/skills/comet/scripts/comet-archive.mjs +65 -65
  13. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +47 -47
  14. package/assets/skills/comet/scripts/comet-guard.mjs +105 -105
  15. package/assets/skills/comet/scripts/comet-handoff.mjs +74 -74
  16. package/assets/skills/comet/scripts/comet-hook-guard.mjs +75 -75
  17. package/assets/skills/comet/scripts/comet-hook-router.mjs +142 -140
  18. package/assets/skills/comet/scripts/comet-resume-probe.mjs +87 -87
  19. package/assets/skills/comet/scripts/comet-runtime.mjs +145 -145
  20. package/assets/skills/comet/scripts/comet-state.mjs +69 -69
  21. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +89 -89
  22. package/assets/skills/comet-any/SKILL.md +2 -1
  23. package/assets/skills/comet-any/agents/openai.yaml +5 -0
  24. package/assets/skills/comet-archive/SKILL.md +7 -6
  25. package/assets/skills/comet-archive/agents/openai.yaml +5 -0
  26. package/assets/skills/comet-build/SKILL.md +14 -13
  27. package/assets/skills/comet-build/agents/openai.yaml +5 -0
  28. package/assets/skills/comet-classic/SKILL.md +14 -14
  29. package/assets/skills/comet-classic/agents/openai.yaml +3 -0
  30. package/assets/skills/{comet → comet-classic}/reference/auto-transition.md +1 -1
  31. package/assets/skills/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
  32. package/assets/skills/{comet → comet-classic}/reference/context-recovery.md +5 -5
  33. package/assets/skills/{comet → comet-classic}/reference/debug-gate.md +2 -2
  34. package/assets/skills/{comet → comet-classic}/reference/decision-point.md +1 -1
  35. package/assets/skills/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
  36. package/assets/skills/{comet → comet-classic}/reference/file-structure.md +1 -1
  37. package/assets/skills/{comet → comet-classic}/reference/intent-frame.md +1 -1
  38. package/assets/skills/{comet → comet-classic}/reference/scripts.md +1 -1
  39. package/assets/skills/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  40. package/assets/skills/comet-design/SKILL.md +7 -6
  41. package/assets/skills/comet-design/agents/openai.yaml +5 -0
  42. package/assets/skills/comet-hotfix/SKILL.md +10 -9
  43. package/assets/skills/comet-hotfix/agents/openai.yaml +5 -0
  44. package/assets/skills/comet-native/SKILL.md +54 -168
  45. package/assets/skills/comet-native/agents/openai.yaml +3 -0
  46. package/assets/skills/comet-native/reference/artifacts.md +23 -89
  47. package/assets/skills/comet-native/reference/clarification.md +54 -29
  48. package/assets/skills/comet-native/reference/commands.md +30 -173
  49. package/assets/skills/comet-native/reference/recovery.md +38 -88
  50. package/assets/skills/comet-native/reference/workspace.md +23 -0
  51. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +184 -152
  52. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +219 -163
  53. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +126 -117
  54. package/assets/skills/comet-native/scripts/comet-native-init.mjs +134 -124
  55. package/assets/skills/comet-native/scripts/comet-native-new.mjs +170 -163
  56. package/assets/skills/comet-native/scripts/comet-native-next.mjs +179 -148
  57. package/assets/skills/comet-native/scripts/comet-native-root.mjs +152 -147
  58. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +247 -202
  59. package/assets/skills/comet-native/scripts/comet-native-select.mjs +153 -146
  60. package/assets/skills/comet-native/scripts/comet-native-show.mjs +117 -110
  61. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +133 -151
  62. package/assets/skills/comet-native/scripts/comet-native-status.mjs +146 -139
  63. package/assets/skills/comet-open/SKILL.md +7 -6
  64. package/assets/skills/comet-open/agents/openai.yaml +5 -0
  65. package/assets/skills/comet-tweak/SKILL.md +11 -10
  66. package/assets/skills/comet-tweak/agents/openai.yaml +5 -0
  67. package/assets/skills/comet-verify/SKILL.md +9 -8
  68. package/assets/skills/comet-verify/agents/openai.yaml +5 -0
  69. package/assets/skills-zh/comet/SKILL.md +1 -1
  70. package/assets/skills-zh/comet/agents/openai.yaml +3 -0
  71. package/assets/skills-zh/comet-any/SKILL.md +2 -1
  72. package/assets/skills-zh/comet-any/agents/openai.yaml +5 -0
  73. package/assets/skills-zh/comet-archive/SKILL.md +7 -6
  74. package/assets/skills-zh/comet-archive/agents/openai.yaml +5 -0
  75. package/assets/skills-zh/comet-build/SKILL.md +14 -13
  76. package/assets/skills-zh/comet-build/agents/openai.yaml +5 -0
  77. package/assets/skills-zh/comet-classic/SKILL.md +15 -15
  78. package/assets/skills-zh/comet-classic/agents/openai.yaml +3 -0
  79. package/assets/skills-zh/{comet → comet-classic}/reference/auto-transition.md +1 -1
  80. package/assets/skills-zh/{comet → comet-classic}/reference/comet-yaml-fields.md +2 -2
  81. package/assets/skills-zh/{comet → comet-classic}/reference/context-recovery.md +5 -5
  82. package/assets/skills-zh/{comet → comet-classic}/reference/debug-gate.md +2 -2
  83. package/assets/skills-zh/{comet → comet-classic}/reference/decision-point.md +1 -1
  84. package/assets/skills-zh/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
  85. package/assets/skills-zh/{comet → comet-classic}/reference/file-structure.md +1 -1
  86. package/assets/skills-zh/{comet → comet-classic}/reference/intent-frame.md +1 -1
  87. package/assets/skills-zh/{comet → comet-classic}/reference/scripts.md +1 -1
  88. package/assets/skills-zh/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  89. package/assets/skills-zh/comet-design/SKILL.md +7 -6
  90. package/assets/skills-zh/comet-design/agents/openai.yaml +5 -0
  91. package/assets/skills-zh/comet-hotfix/SKILL.md +10 -9
  92. package/assets/skills-zh/comet-hotfix/agents/openai.yaml +5 -0
  93. package/assets/skills-zh/comet-native/SKILL.md +54 -168
  94. package/assets/skills-zh/comet-native/agents/openai.yaml +3 -0
  95. package/assets/skills-zh/comet-native/reference/artifacts.md +23 -89
  96. package/assets/skills-zh/comet-native/reference/clarification.md +40 -15
  97. package/assets/skills-zh/comet-native/reference/commands.md +30 -173
  98. package/assets/skills-zh/comet-native/reference/recovery.md +36 -86
  99. package/assets/skills-zh/comet-native/reference/workspace.md +23 -0
  100. package/assets/skills-zh/comet-open/SKILL.md +7 -6
  101. package/assets/skills-zh/comet-open/agents/openai.yaml +5 -0
  102. package/assets/skills-zh/comet-tweak/SKILL.md +11 -10
  103. package/assets/skills-zh/comet-tweak/agents/openai.yaml +5 -0
  104. package/assets/skills-zh/comet-verify/SKILL.md +9 -8
  105. package/assets/skills-zh/comet-verify/agents/openai.yaml +5 -0
  106. package/bin/fast-runtime-router.js +0 -4
  107. package/dist/app/commands/doctor.d.ts.map +1 -1
  108. package/dist/app/commands/doctor.js +8 -0
  109. package/dist/app/commands/doctor.js.map +1 -1
  110. package/dist/app/commands/init.d.ts.map +1 -1
  111. package/dist/app/commands/init.js +9 -1
  112. package/dist/app/commands/init.js.map +1 -1
  113. package/dist/app/commands/update.d.ts.map +1 -1
  114. package/dist/app/commands/update.js +9 -2
  115. package/dist/app/commands/update.js.map +1 -1
  116. package/dist/config/repository-layout.json +0 -8
  117. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  118. package/dist/domains/bundle/bundle-platform.js +8 -0
  119. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  120. package/dist/domains/bundle/types.d.ts +1 -1
  121. package/dist/domains/bundle/types.d.ts.map +1 -1
  122. package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
  123. package/dist/domains/comet-entry/hook-adapter.js +2 -0
  124. package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
  125. package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
  126. package/dist/domains/comet-entry/hook-router-entry.js +11 -2
  127. package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
  128. package/dist/domains/comet-entry/project-activation.d.ts.map +1 -1
  129. package/dist/domains/comet-entry/project-activation.js +2 -1
  130. package/dist/domains/comet-entry/project-activation.js.map +1 -1
  131. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  132. package/dist/domains/comet-entry/resume-probe.js +48 -4
  133. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  134. package/dist/domains/comet-native/native-acceptance.d.ts +4 -3
  135. package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
  136. package/dist/domains/comet-native/native-acceptance.js +23 -18
  137. package/dist/domains/comet-native/native-acceptance.js.map +1 -1
  138. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  139. package/dist/domains/comet-native/native-archive-command.js +204 -61
  140. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  141. package/dist/domains/comet-native/native-archive-transaction.d.ts.map +1 -1
  142. package/dist/domains/comet-native/native-archive-transaction.js +28 -23
  143. package/dist/domains/comet-native/native-archive-transaction.js.map +1 -1
  144. package/dist/domains/comet-native/native-archive.d.ts +1 -0
  145. package/dist/domains/comet-native/native-archive.d.ts.map +1 -1
  146. package/dist/domains/comet-native/native-archive.js +56 -12
  147. package/dist/domains/comet-native/native-archive.js.map +1 -1
  148. package/dist/domains/comet-native/native-bounded-file.d.ts +32 -2
  149. package/dist/domains/comet-native/native-bounded-file.d.ts.map +1 -1
  150. package/dist/domains/comet-native/native-bounded-file.js +87 -6
  151. package/dist/domains/comet-native/native-bounded-file.js.map +1 -1
  152. package/dist/domains/comet-native/native-build-evidence.d.ts.map +1 -1
  153. package/dist/domains/comet-native/native-build-evidence.js +23 -1
  154. package/dist/domains/comet-native/native-build-evidence.js.map +1 -1
  155. package/dist/domains/comet-native/native-change.d.ts +1 -0
  156. package/dist/domains/comet-native/native-change.d.ts.map +1 -1
  157. package/dist/domains/comet-native/native-change.js +96 -8
  158. package/dist/domains/comet-native/native-change.js.map +1 -1
  159. package/dist/domains/comet-native/native-check-executor.d.ts +36 -0
  160. package/dist/domains/comet-native/native-check-executor.d.ts.map +1 -0
  161. package/dist/domains/comet-native/native-check-executor.js +132 -0
  162. package/dist/domains/comet-native/native-check-executor.js.map +1 -0
  163. package/dist/domains/comet-native/native-check-receipt-model.d.ts +9 -0
  164. package/dist/domains/comet-native/native-check-receipt-model.d.ts.map +1 -1
  165. package/dist/domains/comet-native/native-check-receipt-model.js +70 -8
  166. package/dist/domains/comet-native/native-check-receipt-model.js.map +1 -1
  167. package/dist/domains/comet-native/native-check-receipt-storage.d.ts.map +1 -1
  168. package/dist/domains/comet-native/native-check-receipt-storage.js +9 -8
  169. package/dist/domains/comet-native/native-check-receipt-storage.js.map +1 -1
  170. package/dist/domains/comet-native/native-check-receipt.d.ts.map +1 -1
  171. package/dist/domains/comet-native/native-check-receipt.js +123 -60
  172. package/dist/domains/comet-native/native-check-receipt.js.map +1 -1
  173. package/dist/domains/comet-native/native-checkpoint-command.d.ts.map +1 -1
  174. package/dist/domains/comet-native/native-checkpoint-command.js +0 -6
  175. package/dist/domains/comet-native/native-checkpoint-command.js.map +1 -1
  176. package/dist/domains/comet-native/native-checkpoint-storage.d.ts.map +1 -1
  177. package/dist/domains/comet-native/native-checkpoint-storage.js +27 -19
  178. package/dist/domains/comet-native/native-checkpoint-storage.js.map +1 -1
  179. package/dist/domains/comet-native/native-cli-help.d.ts +6 -0
  180. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -0
  181. package/dist/domains/comet-native/native-cli-help.js +192 -0
  182. package/dist/domains/comet-native/native-cli-help.js.map +1 -0
  183. package/dist/domains/comet-native/native-cli-shared.d.ts +2 -2
  184. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  185. package/dist/domains/comet-native/native-cli-shared.js +46 -24
  186. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  187. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  188. package/dist/domains/comet-native/native-cli.js +18 -11
  189. package/dist/domains/comet-native/native-cli.js.map +1 -1
  190. package/dist/domains/comet-native/native-config.d.ts +2 -1
  191. package/dist/domains/comet-native/native-config.d.ts.map +1 -1
  192. package/dist/domains/comet-native/native-config.js +2 -1
  193. package/dist/domains/comet-native/native-config.js.map +1 -1
  194. package/dist/domains/comet-native/native-continuation.d.ts.map +1 -1
  195. package/dist/domains/comet-native/native-continuation.js +175 -147
  196. package/dist/domains/comet-native/native-continuation.js.map +1 -1
  197. package/dist/domains/comet-native/native-diagnostics.d.ts.map +1 -1
  198. package/dist/domains/comet-native/native-diagnostics.js +96 -13
  199. package/dist/domains/comet-native/native-diagnostics.js.map +1 -1
  200. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  201. package/dist/domains/comet-native/native-doctor-command.js +327 -0
  202. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  203. package/dist/domains/comet-native/native-doctor.d.ts +1 -0
  204. package/dist/domains/comet-native/native-doctor.d.ts.map +1 -1
  205. package/dist/domains/comet-native/native-doctor.js +116 -22
  206. package/dist/domains/comet-native/native-doctor.js.map +1 -1
  207. package/dist/domains/comet-native/native-evidence-projection.d.ts +50 -0
  208. package/dist/domains/comet-native/native-evidence-projection.d.ts.map +1 -0
  209. package/dist/domains/comet-native/native-evidence-projection.js +284 -0
  210. package/dist/domains/comet-native/native-evidence-projection.js.map +1 -0
  211. package/dist/domains/comet-native/native-evidence-retention.d.ts.map +1 -1
  212. package/dist/domains/comet-native/native-evidence-retention.js +14 -12
  213. package/dist/domains/comet-native/native-evidence-retention.js.map +1 -1
  214. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  215. package/dist/domains/comet-native/native-evidence-storage.js +14 -11
  216. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  217. package/dist/domains/comet-native/native-findings.d.ts.map +1 -1
  218. package/dist/domains/comet-native/native-findings.js +18 -0
  219. package/dist/domains/comet-native/native-findings.js.map +1 -1
  220. package/dist/domains/comet-native/native-git-provenance.d.ts +16 -0
  221. package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -0
  222. package/dist/domains/comet-native/native-git-provenance.js +171 -0
  223. package/dist/domains/comet-native/native-git-provenance.js.map +1 -0
  224. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  225. package/dist/domains/comet-native/native-hook-guard.js +159 -18
  226. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  227. package/dist/domains/comet-native/native-init-command.d.ts.map +1 -1
  228. package/dist/domains/comet-native/native-init-command.js +14 -2
  229. package/dist/domains/comet-native/native-init-command.js.map +1 -1
  230. package/dist/domains/comet-native/native-local-execution.d.ts +25 -0
  231. package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -0
  232. package/dist/domains/comet-native/native-local-execution.js +241 -0
  233. package/dist/domains/comet-native/native-local-execution.js.map +1 -0
  234. package/dist/domains/comet-native/native-lock.d.ts +1 -1
  235. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  236. package/dist/domains/comet-native/native-lock.js +9 -9
  237. package/dist/domains/comet-native/native-lock.js.map +1 -1
  238. package/dist/domains/comet-native/native-loop-runtime.d.ts +63 -0
  239. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -0
  240. package/dist/domains/comet-native/native-loop-runtime.js +580 -0
  241. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -0
  242. package/dist/domains/comet-native/native-mutation-lock.d.ts +2 -0
  243. package/dist/domains/comet-native/native-mutation-lock.d.ts.map +1 -1
  244. package/dist/domains/comet-native/native-mutation-lock.js +23 -2
  245. package/dist/domains/comet-native/native-mutation-lock.js.map +1 -1
  246. package/dist/domains/comet-native/native-new-command.d.ts.map +1 -1
  247. package/dist/domains/comet-native/native-new-command.js +27 -20
  248. package/dist/domains/comet-native/native-new-command.js.map +1 -1
  249. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  250. package/dist/domains/comet-native/native-next-command.js +114 -63
  251. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  252. package/dist/domains/comet-native/native-paths.d.ts +18 -0
  253. package/dist/domains/comet-native/native-paths.d.ts.map +1 -1
  254. package/dist/domains/comet-native/native-paths.js +125 -13
  255. package/dist/domains/comet-native/native-paths.js.map +1 -1
  256. package/dist/domains/comet-native/native-portable-acceptance.d.ts +28 -0
  257. package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -0
  258. package/dist/domains/comet-native/native-portable-acceptance.js +73 -0
  259. package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -0
  260. package/dist/domains/comet-native/native-portable-archive.d.ts +37 -0
  261. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -0
  262. package/dist/domains/comet-native/native-portable-archive.js +492 -0
  263. package/dist/domains/comet-native/native-portable-archive.js.map +1 -0
  264. package/dist/domains/comet-native/native-portable-continuation.d.ts +29 -0
  265. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -0
  266. package/dist/domains/comet-native/native-portable-continuation.js +341 -0
  267. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -0
  268. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts +9 -0
  269. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -0
  270. package/dist/domains/comet-native/native-portable-migration-runtime.js +213 -0
  271. package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -0
  272. package/dist/domains/comet-native/native-portable-migration.d.ts +42 -0
  273. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -0
  274. package/dist/domains/comet-native/native-portable-migration.js +212 -0
  275. package/dist/domains/comet-native/native-portable-migration.js.map +1 -0
  276. package/dist/domains/comet-native/native-portable-recovery.d.ts +15 -0
  277. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -0
  278. package/dist/domains/comet-native/native-portable-recovery.js +203 -0
  279. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -0
  280. package/dist/domains/comet-native/native-portable-runtime.d.ts +150 -0
  281. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -0
  282. package/dist/domains/comet-native/native-portable-runtime.js +1444 -0
  283. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -0
  284. package/dist/domains/comet-native/native-portable-state.d.ts +30 -0
  285. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -0
  286. package/dist/domains/comet-native/native-portable-state.js +688 -0
  287. package/dist/domains/comet-native/native-portable-state.js.map +1 -0
  288. package/dist/domains/comet-native/native-portable-status.d.ts +62 -0
  289. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -0
  290. package/dist/domains/comet-native/native-portable-status.js +125 -0
  291. package/dist/domains/comet-native/native-portable-status.js.map +1 -0
  292. package/dist/domains/comet-native/native-portable-text.d.ts +8 -0
  293. package/dist/domains/comet-native/native-portable-text.d.ts.map +1 -0
  294. package/dist/domains/comet-native/native-portable-text.js +28 -0
  295. package/dist/domains/comet-native/native-portable-text.js.map +1 -0
  296. package/dist/domains/comet-native/native-portable-transactions.d.ts +41 -0
  297. package/dist/domains/comet-native/native-portable-transactions.d.ts.map +1 -0
  298. package/dist/domains/comet-native/native-portable-transactions.js +204 -0
  299. package/dist/domains/comet-native/native-portable-transactions.js.map +1 -0
  300. package/dist/domains/comet-native/native-portable-types.d.ts +165 -0
  301. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -0
  302. package/dist/domains/comet-native/native-portable-types.js +18 -0
  303. package/dist/domains/comet-native/native-portable-types.js.map +1 -0
  304. package/dist/domains/comet-native/native-repair-integration.js +5 -5
  305. package/dist/domains/comet-native/native-repair-integration.js.map +1 -1
  306. package/dist/domains/comet-native/native-resume-view.d.ts.map +1 -1
  307. package/dist/domains/comet-native/native-resume-view.js +1 -5
  308. package/dist/domains/comet-native/native-resume-view.js.map +1 -1
  309. package/dist/domains/comet-native/native-root-move.d.ts.map +1 -1
  310. package/dist/domains/comet-native/native-root-move.js +4 -20
  311. package/dist/domains/comet-native/native-root-move.js.map +1 -1
  312. package/dist/domains/comet-native/native-run-consistency.d.ts.map +1 -1
  313. package/dist/domains/comet-native/native-run-consistency.js +8 -12
  314. package/dist/domains/comet-native/native-run-consistency.js.map +1 -1
  315. package/dist/domains/comet-native/native-run-store.js +4 -4
  316. package/dist/domains/comet-native/native-run-store.js.map +1 -1
  317. package/dist/domains/comet-native/native-runner-input.d.ts +160 -0
  318. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -0
  319. package/dist/domains/comet-native/native-runner-input.js +347 -0
  320. package/dist/domains/comet-native/native-runner-input.js.map +1 -0
  321. package/dist/domains/comet-native/native-runner-protocol.d.ts +40 -0
  322. package/dist/domains/comet-native/native-runner-protocol.d.ts.map +1 -0
  323. package/dist/domains/comet-native/native-runner-protocol.js +55 -0
  324. package/dist/domains/comet-native/native-runner-protocol.js.map +1 -0
  325. package/dist/domains/comet-native/native-runtime-package.d.ts +3 -0
  326. package/dist/domains/comet-native/native-runtime-package.d.ts.map +1 -1
  327. package/dist/domains/comet-native/native-runtime-package.js +5 -1
  328. package/dist/domains/comet-native/native-runtime-package.js.map +1 -1
  329. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  330. package/dist/domains/comet-native/native-schema-migration.js +30 -27
  331. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  332. package/dist/domains/comet-native/native-select-command.d.ts.map +1 -1
  333. package/dist/domains/comet-native/native-select-command.js +8 -4
  334. package/dist/domains/comet-native/native-select-command.js.map +1 -1
  335. package/dist/domains/comet-native/native-selection.d.ts.map +1 -1
  336. package/dist/domains/comet-native/native-selection.js +11 -2
  337. package/dist/domains/comet-native/native-selection.js.map +1 -1
  338. package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
  339. package/dist/domains/comet-native/native-show-command.js +36 -0
  340. package/dist/domains/comet-native/native-show-command.js.map +1 -1
  341. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  342. package/dist/domains/comet-native/native-snapshot.js +13 -10
  343. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  344. package/dist/domains/comet-native/native-spec-command.d.ts.map +1 -1
  345. package/dist/domains/comet-native/native-spec-command.js +14 -28
  346. package/dist/domains/comet-native/native-spec-command.js.map +1 -1
  347. package/dist/domains/comet-native/native-specs.js +3 -3
  348. package/dist/domains/comet-native/native-specs.js.map +1 -1
  349. package/dist/domains/comet-native/native-status-command.d.ts.map +1 -1
  350. package/dist/domains/comet-native/native-status-command.js +7 -17
  351. package/dist/domains/comet-native/native-status-command.js.map +1 -1
  352. package/dist/domains/comet-native/native-status-discovery.d.ts +51 -0
  353. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -0
  354. package/dist/domains/comet-native/native-status-discovery.js +299 -0
  355. package/dist/domains/comet-native/native-status-discovery.js.map +1 -0
  356. package/dist/domains/comet-native/native-trajectory-recovery.d.ts.map +1 -1
  357. package/dist/domains/comet-native/native-trajectory-recovery.js +6 -9
  358. package/dist/domains/comet-native/native-trajectory-recovery.js.map +1 -1
  359. package/dist/domains/comet-native/native-transaction.d.ts.map +1 -1
  360. package/dist/domains/comet-native/native-transaction.js +31 -20
  361. package/dist/domains/comet-native/native-transaction.js.map +1 -1
  362. package/dist/domains/comet-native/native-transition-evidence.d.ts.map +1 -1
  363. package/dist/domains/comet-native/native-transition-evidence.js +1 -0
  364. package/dist/domains/comet-native/native-transition-evidence.js.map +1 -1
  365. package/dist/domains/comet-native/native-transition-journal.d.ts.map +1 -1
  366. package/dist/domains/comet-native/native-transition-journal.js +71 -22
  367. package/dist/domains/comet-native/native-transition-journal.js.map +1 -1
  368. package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
  369. package/dist/domains/comet-native/native-transitions.js +167 -15
  370. package/dist/domains/comet-native/native-transitions.js.map +1 -1
  371. package/dist/domains/comet-native/native-types.d.ts +36 -1
  372. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  373. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  374. package/dist/domains/comet-native/native-verification-receipt-runtime.js +18 -100
  375. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  376. package/dist/domains/comet-native/native-verification-report-v2.d.ts +12 -0
  377. package/dist/domains/comet-native/native-verification-report-v2.d.ts.map +1 -0
  378. package/dist/domains/comet-native/native-verification-report-v2.js +141 -0
  379. package/dist/domains/comet-native/native-verification-report-v2.js.map +1 -0
  380. package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
  381. package/dist/domains/comet-native/native-verification-runtime.js +7 -2
  382. package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
  383. package/dist/domains/comet-native/native-verification-scope.d.ts +23 -0
  384. package/dist/domains/comet-native/native-verification-scope.d.ts.map +1 -1
  385. package/dist/domains/comet-native/native-verification-scope.js +106 -19
  386. package/dist/domains/comet-native/native-verification-scope.js.map +1 -1
  387. package/dist/domains/comet-native/native-verifier-protocol.d.ts +49 -0
  388. package/dist/domains/comet-native/native-verifier-protocol.d.ts.map +1 -0
  389. package/dist/domains/comet-native/native-verifier-protocol.js +157 -0
  390. package/dist/domains/comet-native/native-verifier-protocol.js.map +1 -0
  391. package/dist/domains/comet-native/native-workspace-finish.d.ts +61 -0
  392. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -0
  393. package/dist/domains/comet-native/native-workspace-finish.js +332 -0
  394. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -0
  395. package/dist/domains/comet-native/native-workspace-preparation.d.ts +32 -0
  396. package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -0
  397. package/dist/domains/comet-native/native-workspace-preparation.js +265 -0
  398. package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -0
  399. package/dist/domains/comet-native/native-workspace.d.ts +9 -1
  400. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  401. package/dist/domains/comet-native/native-workspace.js +109 -11
  402. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  403. package/dist/domains/dashboard/native-adapter.d.ts +136 -127
  404. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  405. package/dist/domains/dashboard/native-adapter.js +157 -271
  406. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  407. package/dist/domains/dashboard/native-collector.d.ts +4 -4
  408. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  409. package/dist/domains/dashboard/native-collector.js +230 -412
  410. package/dist/domains/dashboard/native-collector.js.map +1 -1
  411. package/dist/domains/dashboard/native-legacy-adapter.d.ts +30 -0
  412. package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -0
  413. package/dist/domains/dashboard/native-legacy-adapter.js +115 -0
  414. package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -0
  415. package/dist/domains/dashboard/web/assets/{arc-ClrSujVb.js → arc-CkuYweSh.js} +1 -1
  416. package/dist/domains/dashboard/web/assets/{architectureDiagram-3BPJPVTR-B4A_t84A.js → architectureDiagram-3BPJPVTR--tTGrKam.js} +1 -1
  417. package/dist/domains/dashboard/web/assets/{blockDiagram-GPEHLZMM-D72u2953.js → blockDiagram-GPEHLZMM-DLKYOixs.js} +1 -1
  418. package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-Ca5zba3N.js → c4Diagram-AAUBKEIU-BL17BIb8.js} +1 -1
  419. package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +1 -0
  420. package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-CCVPBm0J.js → chunk-2J33WTMH-B_DDS2IK.js} +1 -1
  421. package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-JYluRsP-.js → chunk-4BX2VUAB-vQyyh3eG.js} +1 -1
  422. package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-DfYm7pN7.js → chunk-55IACEB6-Cug8J1Qa.js} +1 -1
  423. package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-CwghIMO9.js → chunk-727SXJPM-pMreYMW7.js} +1 -1
  424. package/dist/domains/dashboard/web/assets/{chunk-AQP2D5EJ-BA_zgMXZ.js → chunk-AQP2D5EJ-BUkV_rb7.js} +1 -1
  425. package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-BAJLB5V6.js → chunk-FMBD7UC4-CQXqBSqQ.js} +1 -1
  426. package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-Bj6HWRwi.js → chunk-ND2GUHAM-XWLMOyd4.js} +1 -1
  427. package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-B1kXfg5N.js → chunk-QZHKN3VN-4drjXzHQ.js} +1 -1
  428. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +1 -0
  429. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +1 -0
  430. package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-BBrkuiAU.js → cose-bilkent-S5V4N54A-IQKP-hgj.js} +1 -1
  431. package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-DlFhgQHt.js → cynefin-VYW2F7L2-CvvRO4J2.js} +1 -1
  432. package/dist/domains/dashboard/web/assets/{dagre-BM42HDAG-B0Bk5oiP.js → dagre-BM42HDAG-DeOQo7bP.js} +1 -1
  433. package/dist/domains/dashboard/web/assets/demo-CeIDHUFJ.js +24 -0
  434. package/dist/domains/dashboard/web/assets/{diagram-2AECGRRQ-tvTUiBA2.js → diagram-2AECGRRQ-IQd_jQwB.js} +1 -1
  435. package/dist/domains/dashboard/web/assets/{diagram-5GNKFQAL-BZfcK29q.js → diagram-5GNKFQAL-Dllkdt0m.js} +1 -1
  436. package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-BQahyP-C.js → diagram-KO2AKTUF-CN_LYqvT.js} +1 -1
  437. package/dist/domains/dashboard/web/assets/{diagram-LMA3HP47-D5bJnW2C.js → diagram-LMA3HP47-DK36WkNN.js} +1 -1
  438. package/dist/domains/dashboard/web/assets/{diagram-OG6HWLK6-DTwWdzWJ.js → diagram-OG6HWLK6-iqUnMYEh.js} +1 -1
  439. package/dist/domains/dashboard/web/assets/{erDiagram-TEJ5UH35-BbvrdCp9.js → erDiagram-TEJ5UH35-Bc64lzy8.js} +1 -1
  440. package/dist/domains/dashboard/web/assets/{flowDiagram-I6XJVG4X-DgbR7Tcc.js → flowDiagram-I6XJVG4X-UfOqef9j.js} +1 -1
  441. package/dist/domains/dashboard/web/assets/{ganttDiagram-6RSMTGT7-wWMOA7F4.js → ganttDiagram-6RSMTGT7-D-u6Aauc.js} +1 -1
  442. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-DCxvMAUJ.js → gitGraphDiagram-PVQCEYII-CaWEk3PM.js} +1 -1
  443. package/dist/domains/dashboard/web/assets/index-BFwKBVTJ.css +1 -0
  444. package/dist/domains/dashboard/web/assets/{index-Blit0P5Z.js → index-BNyOfAhu.js} +1 -1
  445. package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +257 -0
  446. package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-9qXEkzDe.js → infoDiagram-5YYISTIA-BK07mNG0.js} +1 -1
  447. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-Dkf5othW.js → ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js} +1 -1
  448. package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-C2_IkO4s.js → journeyDiagram-JHISSGLW-BPy-P7xx.js} +1 -1
  449. package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-BxWgu4DL.js → kanban-definition-UN3LZRKU-3Jq9c_lo.js} +1 -1
  450. package/dist/domains/dashboard/web/assets/{linear-Dkr6p-Ro.js → linear-kQyEW-4G.js} +1 -1
  451. package/dist/domains/dashboard/web/assets/{mermaid.core-DZUcsoG4.js → mermaid.core-COBBjtVH.js} +4 -4
  452. package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-C9xyxGfa.js → mindmap-definition-RKZ34NQL-CyyurUpv.js} +1 -1
  453. package/dist/domains/dashboard/web/assets/{pieDiagram-4H26LBE5-Dn67tdOF.js → pieDiagram-4H26LBE5-CJro_XKk.js} +1 -1
  454. package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-Cy6iOcxc.js → quadrantDiagram-W4KKPZXB-CpayUMjH.js} +1 -1
  455. package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-B_gZONhx.js → requirementDiagram-4Y6WPE33-Bi8YpfnA.js} +1 -1
  456. package/dist/domains/dashboard/web/assets/{sankeyDiagram-5OEKKPKP-C3u-4dOk.js → sankeyDiagram-5OEKKPKP-Wx60WwHe.js} +1 -1
  457. package/dist/domains/dashboard/web/assets/{sequenceDiagram-3UESZ5HK-Xd3ByTVF.js → sequenceDiagram-3UESZ5HK-BiMsRFbc.js} +1 -1
  458. package/dist/domains/dashboard/web/assets/{stateDiagram-AJRCARHV-CJGHL7Up.js → stateDiagram-AJRCARHV-BrURMY0R.js} +1 -1
  459. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +1 -0
  460. package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-DvONX2YQ.js → timeline-definition-PNZ67QCA-aHrrtV-b.js} +1 -1
  461. package/dist/domains/dashboard/web/assets/{vennDiagram-CIIHVFJN-B-L4qWy4.js → vennDiagram-CIIHVFJN-DGB16bvR.js} +1 -1
  462. package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-cf39WX2o.js → wardleyDiagram-YWT4CUSO-RVQbcySh.js} +1 -1
  463. package/dist/domains/dashboard/web/assets/{xychartDiagram-2RQKCTM6-Dk1vcm3u.js → xychartDiagram-2RQKCTM6-DMzzwDVX.js} +1 -1
  464. package/dist/domains/dashboard/web/index.html +16 -16
  465. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  466. package/dist/domains/skill/platform-inspect.js +11 -3
  467. package/dist/domains/skill/platform-inspect.js.map +1 -1
  468. package/dist/domains/skill/platform-install.d.ts +7 -1
  469. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  470. package/dist/domains/skill/platform-install.js +114 -33
  471. package/dist/domains/skill/platform-install.js.map +1 -1
  472. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  473. package/dist/domains/skill/uninstall.js +69 -15
  474. package/dist/domains/skill/uninstall.js.map +1 -1
  475. package/dist/domains/workflow-contract/index.d.ts +1 -0
  476. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  477. package/dist/domains/workflow-contract/index.js +1 -0
  478. package/dist/domains/workflow-contract/index.js.map +1 -1
  479. package/dist/domains/workflow-contract/project-config.d.ts +2 -0
  480. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  481. package/dist/domains/workflow-contract/project-config.js +77 -17
  482. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  483. package/dist/domains/workflow-contract/project-gitignore.d.ts +9 -0
  484. package/dist/domains/workflow-contract/project-gitignore.d.ts.map +1 -0
  485. package/dist/domains/workflow-contract/project-gitignore.js +108 -0
  486. package/dist/domains/workflow-contract/project-gitignore.js.map +1 -0
  487. package/dist/platform/install/platforms.d.ts +3 -1
  488. package/dist/platform/install/platforms.d.ts.map +1 -1
  489. package/dist/platform/install/platforms.js +9 -0
  490. package/dist/platform/install/platforms.js.map +1 -1
  491. package/dist/platform/paths/git-worktree.d.ts +2 -1
  492. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  493. package/dist/platform/paths/git-worktree.js +14 -1
  494. package/dist/platform/paths/git-worktree.js.map +1 -1
  495. package/dist/platform/process/external-command.d.ts +13 -0
  496. package/dist/platform/process/external-command.d.ts.map +1 -0
  497. package/dist/platform/process/external-command.js +45 -0
  498. package/dist/platform/process/external-command.js.map +1 -0
  499. package/dist/platform/process/git.d.ts +12 -0
  500. package/dist/platform/process/git.d.ts.map +1 -0
  501. package/dist/platform/process/git.js +86 -0
  502. package/dist/platform/process/git.js.map +1 -0
  503. package/dist/platform/process/spawn-command.d.ts +8 -0
  504. package/dist/platform/process/spawn-command.d.ts.map +1 -0
  505. package/dist/platform/process/spawn-command.js +113 -0
  506. package/dist/platform/process/spawn-command.js.map +1 -0
  507. package/eval/local/tasks/comet-native-clarification/validation/test_native_clarification.py +9 -21
  508. package/eval/local/tasks/comet-native-clarification-depth/validation/test_native_clarification_depth.py +4 -7
  509. package/eval/local/tasks/comet-native-clarification-modes/validation/test_native_clarification_modes.py +4 -10
  510. package/eval/local/tasks/comet-native-interrupted-transition/instruction.md +1 -1
  511. package/eval/local/tasks/comet-native-interrupted-transition/validation/test_native_interrupted_transition.py +15 -16
  512. package/eval/local/tasks/comet-native-repository-fact/instruction.md +2 -2
  513. package/eval/local/tasks/comet-native-repository-fact/validation/test_native_repository_fact.py +8 -2
  514. package/eval/local/tasks/comet-native-wave-b-decision-resume/instruction.md +8 -4
  515. package/eval/local/tasks/comet-native-wave-b-decision-resume/task.toml +6 -6
  516. package/eval/local/tasks/comet-native-wave-b-decision-resume/validation/test_native_wave_b_decision_resume.py +126 -135
  517. package/eval/local/tasks/comet-native-wave-c-verification-integrity/instruction.md +6 -6
  518. package/eval/local/tasks/comet-native-wave-c-verification-integrity/task.toml +8 -8
  519. package/eval/local/tasks/comet-native-wave-c-verification-integrity/validation/test_native_wave_c_verification_integrity.py +97 -317
  520. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +7 -7
  521. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +4 -4
  522. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +130 -199
  523. package/eval/local/tasks/comet-native-wave-e-parallel-safety/instruction.md +5 -5
  524. package/eval/local/tasks/comet-native-wave-e-parallel-safety/task.toml +8 -8
  525. package/eval/local/tasks/comet-native-wave-e-parallel-safety/validation/test_native_wave_e_parallel_safety.py +135 -239
  526. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/instruction.md +3 -3
  527. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/task.toml +6 -6
  528. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/validation/test_native_wave_f_dashboard_readonly.py +81 -439
  529. package/eval/local/tasks/comet-native-workflow/instruction.md +5 -4
  530. package/eval/local/tasks/comet-native-workflow/validation/test_native_workflow.py +145 -502
  531. package/eval/local/tasks/index.yaml +5 -5
  532. package/eval/local/tests/scaffold/test_native_aligned_eval.py +146 -35
  533. package/eval/local/tests/scaffold/test_native_wave_evaluations.py +75 -2054
  534. package/eval/local/tests/scaffold/test_tasks.py +38 -52
  535. package/eval/local/tests/tasks/test_tasks.py +3 -3
  536. package/eval/local/treatments/comet/comet_native_phase1.yaml +7 -4
  537. package/eval/pyproject.toml +4 -4
  538. package/eval/scaffold/python/native_eval.py +10 -5
  539. package/eval/scaffold/python/validation/native_v4.py +249 -0
  540. package/eval/scaffold/python/validation/native_wave.py +4 -5
  541. package/eval/scaffold/python/validation/native_workflow.py +193 -97
  542. package/eval/scaffold/python/validation/rubric.py +114 -1
  543. package/package.json +2 -1
  544. package/assets/skills/comet-native/scripts/comet-native-check.mjs +0 -179
  545. package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +0 -179
  546. package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +0 -151
  547. package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +0 -187
  548. package/dist/domains/comet-native/native-check-entry.d.ts +0 -2
  549. package/dist/domains/comet-native/native-check-entry.d.ts.map +0 -1
  550. package/dist/domains/comet-native/native-check-entry.js +0 -4
  551. package/dist/domains/comet-native/native-check-entry.js.map +0 -1
  552. package/dist/domains/comet-native/native-checkpoint-entry.d.ts +0 -2
  553. package/dist/domains/comet-native/native-checkpoint-entry.d.ts.map +0 -1
  554. package/dist/domains/comet-native/native-checkpoint-entry.js +0 -4
  555. package/dist/domains/comet-native/native-checkpoint-entry.js.map +0 -1
  556. package/dist/domains/comet-native/native-evidence-entry.d.ts +0 -2
  557. package/dist/domains/comet-native/native-evidence-entry.d.ts.map +0 -1
  558. package/dist/domains/comet-native/native-evidence-entry.js +0 -4
  559. package/dist/domains/comet-native/native-evidence-entry.js.map +0 -1
  560. package/dist/domains/comet-native/native-receipt-entry.d.ts +0 -2
  561. package/dist/domains/comet-native/native-receipt-entry.d.ts.map +0 -1
  562. package/dist/domains/comet-native/native-receipt-entry.js +0 -4
  563. package/dist/domains/comet-native/native-receipt-entry.js.map +0 -1
  564. package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +0 -1
  565. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-BpA7BPgX.js +0 -1
  566. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-BpA7BPgX.js +0 -1
  567. package/dist/domains/dashboard/web/assets/demo-DZYPLZpF.js +0 -25
  568. package/dist/domains/dashboard/web/assets/index-Bk1o-4VO.css +0 -1
  569. package/dist/domains/dashboard/web/assets/index-g8vyW0R_.js +0 -257
  570. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +0 -1
  571. /package/assets/skills/{comet → comet-classic}/reference/classic-layout.md +0 -0
  572. /package/assets/skills-zh/{comet → comet-classic}/reference/classic-layout.md +0 -0
@@ -1,178 +1,185 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var Wv=Object.create;var eu=Object.defineProperty;var zv=Object.getOwnPropertyDescriptor;var Jv=Object.getOwnPropertyNames;var Gv=Object.getPrototypeOf,Uv=Object.prototype.hasOwnProperty;var or=(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 Kv=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Jv(t))!Uv.call(e,r)&&r!==i&&eu(e,r,{get:()=>t[r],enumerable:!(n=zv(t,r))||n.enumerable});return e};var Co=(e,t,i)=>(i=e!=null?Wv(Gv(e)):{},Kv(t||!e||!e.__esModule?eu(i,"default",{value:e,enumerable:!0}):i,e));var D=R(ae=>{"use strict";var Ro=Symbol.for("yaml.alias"),tu=Symbol.for("yaml.document"),sr=Symbol.for("yaml.map"),iu=Symbol.for("yaml.pair"),Po=Symbol.for("yaml.scalar"),cr=Symbol.for("yaml.seq"),Ke=Symbol.for("yaml.node.type"),Yv=e=>!!e&&typeof e=="object"&&e[Ke]===Ro,Xv=e=>!!e&&typeof e=="object"&&e[Ke]===tu,Qv=e=>!!e&&typeof e=="object"&&e[Ke]===sr,Zv=e=>!!e&&typeof e=="object"&&e[Ke]===iu,nu=e=>!!e&&typeof e=="object"&&e[Ke]===Po,eg=e=>!!e&&typeof e=="object"&&e[Ke]===cr;function ru(e){if(e&&typeof e=="object")switch(e[Ke]){case sr:case cr:return!0}return!1}function tg(e){if(e&&typeof e=="object")switch(e[Ke]){case Ro:case sr:case Po:case cr:return!0}return!1}var ig=e=>(nu(e)||ru(e))&&!!e.anchor;ae.ALIAS=Ro;ae.DOC=tu;ae.MAP=sr;ae.NODE_TYPE=Ke;ae.PAIR=iu;ae.SCALAR=Po;ae.SEQ=cr;ae.hasAnchor=ig;ae.isAlias=Yv;ae.isCollection=ru;ae.isDocument=Xv;ae.isMap=Qv;ae.isNode=tg;ae.isPair=Zv;ae.isScalar=nu;ae.isSeq=eg});var Wi=R(Ao=>{"use strict";var re=D(),fe=Symbol("break visit"),au=Symbol("skip children"),Ve=Symbol("remove node");function lr(e,t){let i=ou(t);re.isDocument(e)?li(null,e.contents,i,Object.freeze([e]))===Ve&&(e.contents=null):li(null,e,i,Object.freeze([]))}lr.BREAK=fe;lr.SKIP=au;lr.REMOVE=Ve;function li(e,t,i,n){let r=su(e,t,i,n);if(re.isNode(r)||re.isPair(r))return cu(e,n,r),li(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=li(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===Ve&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){n=Object.freeze(n.concat(t));let a=li("key",t.key,i,n);if(a===fe)return fe;a===Ve&&(t.key=null);let o=li("value",t.value,i,n);if(o===fe)return fe;o===Ve&&(t.value=null)}}return r}async function ur(e,t){let i=ou(t);re.isDocument(e)?await ui(null,e.contents,i,Object.freeze([e]))===Ve&&(e.contents=null):await ui(null,e,i,Object.freeze([]))}ur.BREAK=fe;ur.SKIP=au;ur.REMOVE=Ve;async function ui(e,t,i,n){let r=await su(e,t,i,n);if(re.isNode(r)||re.isPair(r))return cu(e,n,r),ui(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 ui(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===Ve&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){n=Object.freeze(n.concat(t));let a=await ui("key",t.key,i,n);if(a===fe)return fe;a===Ve&&(t.key=null);let o=await ui("value",t.value,i,n);if(o===fe)return fe;o===Ve&&(t.value=null)}}return r}function ou(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 su(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 cu(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`)}}Ao.visit=lr;Ao.visitAsync=ur});var xo=R(uu=>{"use strict";var lu=D(),ng=Wi(),rg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ag=e=>e.replace(/[!,[\]{}]/g,t=>rg[t]),zi=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+ag(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&&lu.isNode(t.contents)){let a={};ng.visit(t.contents,(o,s)=>{lu.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
- `)}};zi.defaultYaml={explicit:!1,version:"1.2"};zi.defaultTags={"!!":"tag:yaml.org,2002:"};uu.Directives=zi});var dr=R(Ji=>{"use strict";var du=D(),og=Wi();function sg(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 fu(e){let t=new Set;return og.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function hu(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function cg(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=fu(e));let o=hu(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(du.isScalar(o.node)||du.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}}Ji.anchorIsValid=sg;Ji.anchorNames=fu;Ji.createNodeAnchors=cg;Ji.findNewAnchor=hu});var To=R(pu=>{"use strict";function Gi(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=Gi(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=Gi(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=Gi(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=Gi(e,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return e.call(t,i,n)}pu.applyReviver=Gi});var ut=R(vu=>{"use strict";var lg=D();function mu(e,t,i){if(Array.isArray(e))return e.map((n,r)=>mu(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!lg.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}vu.toJS=mu});var fr=R(wu=>{"use strict";var ug=To(),gu=D(),dg=ut(),Io=class{constructor(t){Object.defineProperty(this,gu.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(!gu.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=dg.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?ug.applyReviver(a,{"":s},"",s):s}};wu.NodeBase=Io});var Ui=R(yu=>{"use strict";var fg=dr(),hg=Wi(),di=D(),pg=fr(),mg=ut(),_o=class extends pg.NodeBase{constructor(t){super(di.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=[],hg.visit(t,{Node:(a,o)=>{(di.isAlias(o)||di.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||(mg.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=hr(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(fg.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 hr(e,t,i){if(di.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(di.isCollection(t)){let n=0;for(let r of t.items){let a=hr(e,r,i);a>n&&(n=a)}return n}else if(di.isPair(t)){let n=hr(e,t.key,i),r=hr(e,t.value,i);return Math.max(n,r)}return 1}yu.Alias=_o});var te=R(jo=>{"use strict";var vg=D(),gg=fr(),wg=ut(),yg=e=>!e||typeof e!="function"&&typeof e!="object",dt=class extends gg.NodeBase{constructor(t){super(vg.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:wg.toJS(this.value,t,i)}toString(){return String(this.value)}};dt.BLOCK_FOLDED="BLOCK_FOLDED";dt.BLOCK_LITERAL="BLOCK_LITERAL";dt.PLAIN="PLAIN";dt.QUOTE_DOUBLE="QUOTE_DOUBLE";dt.QUOTE_SINGLE="QUOTE_SINGLE";jo.Scalar=dt;jo.isScalarValue=yg});var Ki=R(bu=>{"use strict";var Ng=Ui(),Ht=D(),Nu=te(),bg="tag:yaml.org,2002:";function kg(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 Sg(e,t,i){if(Ht.isDocument(e)&&(e=e.contents),Ht.isNode(e))return e;if(Ht.isPair(e)){let d=i.schema[Ht.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 Ng.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=bg+t.slice(2));let l=kg(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Nu.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Ht.MAP]:Symbol.iterator in Object(e)?o[Ht.SEQ]:o[Ht.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 Nu.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}bu.createNode=Sg});var mr=R(pr=>{"use strict";var Eg=Ki(),We=D(),Cg=fr();function Oo(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 Eg.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 ku=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,$o=class extends Cg.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=>We.isNode(n)||We.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(ku(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(We.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Oo(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(We.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&&We.isScalar(a)?a.value:a:We.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!We.isPair(i))return!1;let n=i.value;return n==null||t&&We.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 We.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(We.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Oo(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};pr.Collection=$o;pr.collectionFromPath=Oo;pr.isEmptyPath=ku});var Yi=R(vr=>{"use strict";var Rg=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ho(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Pg=(e,t,i)=>e.endsWith(`
6
- `)?Ho(i,t):i.includes(`
4
+ var lw=Object.create;var Xu=Object.defineProperty;var uw=Object.getOwnPropertyDescriptor;var dw=Object.getOwnPropertyNames;var fw=Object.getPrototypeOf,pw=Object.prototype.hasOwnProperty;var On=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var C=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(i){throw e=0,i}};var hw=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of dw(e))!pw.call(t,n)&&n!==i&&Xu(t,n,{get:()=>e[n],enumerable:!(r=uw(e,n))||r.enumerable});return t};var Hn=(t,e,i)=>(i=t!=null?lw(fw(t)):{},hw(e||!t||!t.__esModule?Xu(i,"default",{value:t,enumerable:!0}):i,t));var L=C(ce=>{"use strict";var os=Symbol.for("yaml.alias"),Qu=Symbol.for("yaml.document"),Dn=Symbol.for("yaml.map"),Zu=Symbol.for("yaml.pair"),ss=Symbol.for("yaml.scalar"),Bn=Symbol.for("yaml.seq"),vt=Symbol.for("yaml.node.type"),mw=t=>!!t&&typeof t=="object"&&t[vt]===os,vw=t=>!!t&&typeof t=="object"&&t[vt]===Qu,gw=t=>!!t&&typeof t=="object"&&t[vt]===Dn,ww=t=>!!t&&typeof t=="object"&&t[vt]===Zu,ed=t=>!!t&&typeof t=="object"&&t[vt]===ss,yw=t=>!!t&&typeof t=="object"&&t[vt]===Bn;function td(t){if(t&&typeof t=="object")switch(t[vt]){case Dn:case Bn:return!0}return!1}function Nw(t){if(t&&typeof t=="object")switch(t[vt]){case os:case Dn:case ss:case Bn:return!0}return!1}var bw=t=>(ed(t)||td(t))&&!!t.anchor;ce.ALIAS=os;ce.DOC=Qu;ce.MAP=Dn;ce.NODE_TYPE=vt;ce.PAIR=Zu;ce.SCALAR=ss;ce.SEQ=Bn;ce.hasAnchor=bw;ce.isAlias=mw;ce.isCollection=td;ce.isDocument=vw;ce.isMap=gw;ce.isNode=Nw;ce.isPair=ww;ce.isScalar=ed;ce.isSeq=yw});var vr=C(cs=>{"use strict";var ae=L(),ye=Symbol("break visit"),id=Symbol("skip children"),rt=Symbol("remove node");function Fn(t,e){let i=rd(e);ae.isDocument(t)?xi(null,t.contents,i,Object.freeze([t]))===rt&&(t.contents=null):xi(null,t,i,Object.freeze([]))}Fn.BREAK=ye;Fn.SKIP=id;Fn.REMOVE=rt;function xi(t,e,i,r){let n=nd(t,e,i,r);if(ae.isNode(n)||ae.isPair(n))return ad(t,r,n),xi(t,n,i,r);if(typeof n!="symbol"){if(ae.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a<e.items.length;++a){let o=xi(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ye)return ye;o===rt&&(e.items.splice(a,1),a-=1)}}}else if(ae.isPair(e)){r=Object.freeze(r.concat(e));let a=xi("key",e.key,i,r);if(a===ye)return ye;a===rt&&(e.key=null);let o=xi("value",e.value,i,r);if(o===ye)return ye;o===rt&&(e.value=null)}}return n}async function Ln(t,e){let i=rd(e);ae.isDocument(t)?await Ci(null,t.contents,i,Object.freeze([t]))===rt&&(t.contents=null):await Ci(null,t,i,Object.freeze([]))}Ln.BREAK=ye;Ln.SKIP=id;Ln.REMOVE=rt;async function Ci(t,e,i,r){let n=await nd(t,e,i,r);if(ae.isNode(n)||ae.isPair(n))return ad(t,r,n),Ci(t,n,i,r);if(typeof n!="symbol"){if(ae.isCollection(e)){r=Object.freeze(r.concat(e));for(let a=0;a<e.items.length;++a){let o=await Ci(a,e.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ye)return ye;o===rt&&(e.items.splice(a,1),a-=1)}}}else if(ae.isPair(e)){r=Object.freeze(r.concat(e));let a=await Ci("key",e.key,i,r);if(a===ye)return ye;a===rt&&(e.key=null);let o=await Ci("value",e.value,i,r);if(o===ye)return ye;o===rt&&(e.value=null)}}return n}function rd(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function nd(t,e,i,r){if(typeof i=="function")return i(t,e,r);if(ae.isMap(e))return i.Map?.(t,e,r);if(ae.isSeq(e))return i.Seq?.(t,e,r);if(ae.isPair(e))return i.Pair?.(t,e,r);if(ae.isScalar(e))return i.Scalar?.(t,e,r);if(ae.isAlias(e))return i.Alias?.(t,e,r)}function ad(t,e,i){let r=e[e.length-1];if(ae.isCollection(r))r.items[t]=i;else if(ae.isPair(r))t==="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`)}}cs.visit=Fn;cs.visitAsync=Ln});var ls=C(sd=>{"use strict";var od=L(),kw=vr(),Sw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ew=t=>t.replace(/[!,[\]{}]/g,e=>Sw[e]),gr=class t{constructor(e,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,i)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,i){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.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(e,i){if(e==="!")return"!";if(e[0]!=="!")return i(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=e.match(/^(.*!)([^!]*)$/s);n||i(`The ${e} 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==="!"?e:(i(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[i,r]of Object.entries(this.tags))if(e.startsWith(r))return i+Ew(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(e&&r.length>0&&od.isNode(e.contents)){let a={};kw.visit(e.contents,(o,s)=>{od.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:"||(!e||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
+ `)}};gr.defaultYaml={explicit:!1,version:"1.2"};gr.defaultTags={"!!":"tag:yaml.org,2002:"};sd.Directives=gr});var Mn=C(wr=>{"use strict";var cd=L(),Pw=vr();function xw(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(i)}return!0}function ld(t){let e=new Set;return Pw.visit(t,{Value(i,r){r.anchor&&e.add(r.anchor)}}),e}function ud(t,e){for(let i=1;;++i){let r=`${t}${i}`;if(!e.has(r))return r}}function Cw(t,e){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=ld(t));let o=ud(e,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(cd.isScalar(o.node)||cd.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}}wr.anchorIsValid=xw;wr.anchorNames=ld;wr.createNodeAnchors=Cw;wr.findNewAnchor=ud});var us=C(dd=>{"use strict";function yr(t,e,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=yr(t,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=yr(t,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=yr(t,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=yr(t,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return t.call(e,i,r)}dd.applyReviver=yr});var It=C(pd=>{"use strict";var Rw=L();function fd(t,e,i){if(Array.isArray(t))return t.map((r,n)=>fd(r,String(n),i));if(t&&typeof t.toJSON=="function"){if(!i||!Rw.hasAnchor(t))return t.toJSON(e,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(t,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=t.toJSON(e,i);return i.onCreate&&i.onCreate(n),n}return typeof t=="bigint"&&!i?.keep?Number(t):t}pd.toJS=fd});var qn=C(md=>{"use strict";var Aw=us(),hd=L(),_w=It(),ds=class{constructor(e){Object.defineProperty(this,hd.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!hd.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=_w.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Aw.applyReviver(a,{"":s},"",s):s}};md.NodeBase=ds});var Nr=C(vd=>{"use strict";var Tw=Mn(),Iw=vr(),Ri=L(),jw=qn(),$w=It(),fs=class extends jw.NodeBase{constructor(e){super(Ri.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],Iw.visit(e,{Node:(a,o)=>{(Ri.isAlias(o)||Ri.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(e,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||($w.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=Vn(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(e,i,r){let n=`*${this.source}`;if(e){if(Tw.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Vn(t,e,i){if(Ri.isAlias(e)){let r=e.resolve(t),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Ri.isCollection(e)){let r=0;for(let n of e.items){let a=Vn(t,n,i);a>r&&(r=a)}return r}else if(Ri.isPair(e)){let r=Vn(t,e.key,i),n=Vn(t,e.value,i);return Math.max(r,n)}return 1}vd.Alias=fs});var ie=C(ps=>{"use strict";var Ow=L(),Hw=qn(),Dw=It(),Bw=t=>!t||typeof t!="function"&&typeof t!="object",jt=class extends Hw.NodeBase{constructor(e){super(Ow.SCALAR),this.value=e}toJSON(e,i){return i?.keep?this.value:Dw.toJS(this.value,e,i)}toString(){return String(this.value)}};jt.BLOCK_FOLDED="BLOCK_FOLDED";jt.BLOCK_LITERAL="BLOCK_LITERAL";jt.PLAIN="PLAIN";jt.QUOTE_DOUBLE="QUOTE_DOUBLE";jt.QUOTE_SINGLE="QUOTE_SINGLE";ps.Scalar=jt;ps.isScalarValue=Bw});var br=C(wd=>{"use strict";var Fw=Nr(),si=L(),gd=ie(),Lw="tag:yaml.org,2002:";function Mw(t,e,i){if(e){let r=i.filter(a=>a.tag===e),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return i.find(r=>r.identify?.(t)&&!r.format)}function qw(t,e,i){if(si.isDocument(t)&&(t=t.contents),si.isNode(t))return t;if(si.isPair(t)){let d=i.schema[si.MAP].createNode?.(i.schema,null,i);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new Fw.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Lw+e.slice(2));let l=Mw(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new gd.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[si.MAP]:Symbol.iterator in Object(t)?o[si.SEQ]:o[si.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,t,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,t,i):new gd.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}wd.createNode=qw});var zn=C(Wn=>{"use strict";var Vw=br(),nt=L(),Ww=qn();function hs(t,e,i){let r=i;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return Vw.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var yd=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,ms=class extends Ww.NodeBase{constructor(e,i){super(e),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(e){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(i.schema=e),i.items=i.items.map(r=>nt.isNode(r)||nt.isPair(r)?r.clone(e):r),this.range&&(i.range=this.range.slice()),i}addIn(e,i){if(yd(e))this.add(i);else{let[r,...n]=e,a=this.get(r,!0);if(nt.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,hs(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){let[i,...r]=e;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(nt.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(e,i){let[r,...n]=e,a=this.get(r,!0);return n.length===0?!i&&nt.isScalar(a)?a.value:a:nt.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(e){return this.items.every(i=>{if(!nt.isPair(i))return!1;let r=i.value;return r==null||e&&nt.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[i,...r]=e;if(r.length===0)return this.has(i);let n=this.get(i,!0);return nt.isCollection(n)?n.hasIn(r):!1}setIn(e,i){let[r,...n]=e;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(nt.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,hs(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};Wn.Collection=ms;Wn.collectionFromPath=hs;Wn.isEmptyPath=yd});var kr=C(Jn=>{"use strict";var zw=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function vs(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Jw=(t,e,i)=>t.endsWith(`
6
+ `)?vs(i,e):i.includes(`
7
7
  `)?`
8
- `+Ho(i,t):(e.endsWith(" ")?"":" ")+i;vr.indentComment=Ho;vr.lineComment=Pg;vr.stringifyComment=Rg});var Eu=R(Xi=>{"use strict";var Ag="flow",Fo="block",gr="quoted";function xg(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===Fo&&(h=Su(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(i===gr&&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===Fo&&(h=Su(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===gr){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===gr&&u[b]&&(N+=`${e[b]}\\`),N+=`
13
- ${t}${e.slice(b+1,C)}`)}return N}function Su(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}Xi.FOLD_BLOCK=Fo;Xi.FOLD_FLOW=Ag;Xi.FOLD_QUOTED=gr;Xi.foldFlowLines=xg});var Zi=R(Cu=>{"use strict";var xe=te(),ft=Eu(),yr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Nr=e=>/^(%|---|\.\.\.)/m.test(e);function Tg(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 Qi(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Nr(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
+ `+vs(i,e):(t.endsWith(" ")?"":" ")+i;Jn.indentComment=vs;Jn.lineComment=Jw;Jn.stringifyComment=zw});var bd=C(Sr=>{"use strict";var Gw="flow",gs="block",Gn="quoted";function Uw(t,e,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;n<a&&(a=0);let c=Math.max(1+a,1+n-e.length);if(t.length<=c)return t;let l=[],u={},d=n-e.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===gs&&(p=Nd(t,p,e.length),p!==-1&&(d=p+c));for(let P;P=t[p+=1];){if(i===Gn&&P==="\\"){switch(m=p,t[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===gs&&(p=Nd(t,p,e.length)),d=p+e.length+c,f=void 0;else{if(P===" "&&h&&h!==" "&&h!==`
10
+ `&&h!==" "){let k=t[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===Gn){for(;h===" "||h===" ";)h=P,P=t[p+=1],v=!0;let k=p>b+1?p-2:m-1;if(u[k])return t;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 t;o&&o();let N=t.slice(0,l[0]);for(let P=0;P<l.length;++P){let k=l[P],E=l[P+1]||t.length;k===0?N=`
12
+ ${e}${t.slice(0,E)}`:(i===Gn&&u[k]&&(N+=`${t[k]}\\`),N+=`
13
+ ${e}${t.slice(k+1,E)}`)}return N}function Nd(t,e,i){let r=e,n=e+1,a=t[n];for(;a===" "||a===" ";)if(e<n+i)a=t[++e];else{do a=t[++e];while(a&&a!==`
14
+ `);r=e,n=e+1,a=t[n]}return r}Sr.FOLD_BLOCK=gs;Sr.FOLD_FLOW=Gw;Sr.FOLD_QUOTED=Gn;Sr.foldFlowLines=Uw});var Pr=C(kd=>{"use strict";var qe=ie(),$t=bd(),Kn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),Yn=t=>/^(%|---|\.\.\.)/m.test(t);function Kw(t,e,i){if(!e||e<0)return!1;let r=e-i,n=t.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
15
+ `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Er(t,e){let i=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(Yn(t)?" ":""),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:ft.foldFlowLines(o,a,ft.FOLD_QUOTED,yr(t,!1))}function Do(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Qi(e,t);let i=t.indent||(Nr(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?n:ft.foldFlowLines(n,i,ft.FOLD_FLOW,yr(t,!1))}function fi(e,t){let{singleQuote:i}=t.options,n;if(i===!1)n=Qi;else{let r=e.includes('"'),a=e.includes("'");r&&!a?n=Do:a&&!r?n=Qi:n=i?Do:Qi}return n(e,t)}var Lo;try{Lo=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:$t.foldFlowLines(o,a,$t.FOLD_QUOTED,Kn(e,!1))}function ws(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(t))return Er(t,e);let i=e.indent||(Yn(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return e.implicitKey?r:$t.foldFlowLines(r,i,$t.FOLD_FLOW,Kn(e,!1))}function Ai(t,e){let{singleQuote:i}=e.options,r;if(i===!1)r=Er;else{let n=t.includes('"'),a=t.includes("'");n&&!a?r=ws:a&&!n?r=Er:r=i?ws:Er}return r(t,e)}var ys;try{ys=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Lo=/\n+(?!\n|$)/g}function wr({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 fi(i,n);let l=n.indent||(n.forceBlockIndent||Nr(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===xe.Scalar.BLOCK_FOLDED?!1:t===xe.Scalar.BLOCK_LITERAL?!0:!Tg(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{ys=/\n+(?!\n|$)/g}function Un({comment:t,type:e,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return Ai(i,r);let l=r.indent||(r.forceBlockIndent||Yn(i)?" ":""),u=o==="literal"?!0:o==="folded"||e===qe.Scalar.BLOCK_FOLDED?!1:e===qe.Scalar.BLOCK_LITERAL?!0:!Kw(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(Lo,`$&${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=yr(n,!0);o!=="folded"&&t!==xe.Scalar.BLOCK_FOLDED&&(w.onOverflow=()=>{y=!0});let v=ft.foldFlowLines(`${N}${C}${p}`,l,ft.FOLD_BLOCK,w);if(!y)return`>${b}
31
- ${l}${v}`}return i=i.replace(/\n+/g,`$&${l}`),`|${b}
32
- ${l}${N}${i}${p}`}function Ig(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 fi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?fi(a,t):wr(e,t,i,n);if(!s&&!u&&r!==xe.Scalar.PLAIN&&a.includes(`
35
- `))return wr(e,t,i,n);if(Nr(a)){if(c==="")return t.forceBlockIndent=!0,wr(e,t,i,n);if(s&&c===l)return fi(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 fi(a,t)}return s?d:ft.foldFlowLines(d,c,ft.FOLD_FLOW,yr(t,!1))}function _g(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!==xe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=xe.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case xe.Scalar.BLOCK_FOLDED:case xe.Scalar.BLOCK_LITERAL:return r||a?fi(o.value,t):wr(o,t,i,n);case xe.Scalar.QUOTE_DOUBLE:return Qi(o.value,t);case xe.Scalar.QUOTE_SINGLE:return Do(o.value,t);case xe.Scalar.PLAIN:return Ig(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}Cu.stringifyString=_g});var en=R(Mo=>{"use strict";var jg=dr(),ht=D(),Og=Yi(),$g=Zi();function Hg(e,t){let i=Object.assign({blockQuote:!0,commentString:Og.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 Fg(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(ht.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 Dg(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(ht.isScalar(e)||ht.isCollection(e))&&e.anchor;a&&jg.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 Lg(e,t,i,n){if(ht.isPair(e))return e.toString(t,i,n);if(ht.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=ht.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=Fg(t.doc.schema.tags,a));let o=Dg(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):ht.isScalar(a)?$g.stringifyString(a,t,i,n):a.toString(t,i,n);return o?ht.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Mo.createStringifyContext=Hg;Mo.stringify=Lg});var xu=R(Au=>{"use strict";var Ye=D(),Ru=te(),Pu=en(),tn=Yi();function Mg({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=Ye.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ye.isCollection(e)||!Ye.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||Ye.isCollection(e)||(Ye.isScalar(e)?e.type===Ru.Scalar.BLOCK_FOLDED||e.type===Ru.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+=tn.lineComment(g,i.indent,l(f)):h&&r&&r(),g;m&&(f=null),p?(f&&(g+=tn.lineComment(g,i.indent,l(f))),g=`? ${g}
38
- ${s}:`):(g=`${g}:`,f&&(g+=tn.lineComment(g,i.indent,l(f))));let S,N,k;Ye.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&&Ye.isScalar(t)&&(i.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&Ye.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
- ${tn.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(ys,`$&${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(t&&(k+=" "+s(t.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=Kn(r,!0);o!=="folded"&&e!==qe.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{y=!0});let w=$t.foldFlowLines(`${N}${E}${h}`,l,$t.FOLD_BLOCK,x);if(!y)return`>${k}
31
+ ${l}${w}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
32
+ ${l}${N}${i}${h}`}function Yw(t,e,i,r){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=e;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return Ai(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?Ai(a,e):Un(t,e,i,r);if(!s&&!u&&n!==qe.Scalar.PLAIN&&a.includes(`
35
+ `))return Un(t,e,i,r);if(Yn(a)){if(c==="")return e.forceBlockIndent=!0,Un(t,e,i,r);if(s&&c===l)return Ai(a,e)}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}=e.doc.schema;if(v.some(f)||h?.some(f))return Ai(a,e)}return s?d:$t.foldFlowLines(d,c,$t.FOLD_FLOW,Kn(e,!1))}function Xw(t,e,i,r){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==qe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=qe.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case qe.Scalar.BLOCK_FOLDED:case qe.Scalar.BLOCK_LITERAL:return n||a?Ai(o.value,e):Un(o,e,i,r);case qe.Scalar.QUOTE_DOUBLE:return Er(o.value,e);case qe.Scalar.QUOTE_SINGLE:return ws(o.value,e);case qe.Scalar.PLAIN:return Yw(o,e,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}kd.stringifyString=Xw});var xr=C(Ns=>{"use strict";var Qw=Mn(),Ot=L(),Zw=kr(),ey=Pr();function ty(t,e){let i=Object.assign({blockQuote:!0,commentString:Zw.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},t.schema.toStringOptions,e),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function iy(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let i,r;if(Ot.isScalar(e)){r=e.value;let n=t.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===e.format)??n.find(a=>!a.format)}else r=e,i=t.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 ry(t,e,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Ot.isScalar(t)||Ot.isCollection(t))&&t.anchor;a&&Qw.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function ny(t,e,i,r){if(Ot.isPair(t))return t.toString(e,i,r);if(Ot.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Ot.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=iy(e.doc.schema.tags,a));let o=ry(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,i,r):Ot.isScalar(a)?ey.stringifyString(a,e,i,r):a.toString(e,i,r);return o?Ot.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${e.indent}${s}`:s}Ns.createStringifyContext=ty;Ns.stringify=ny});var xd=C(Pd=>{"use strict";var gt=L(),Sd=ie(),Ed=xr(),Cr=kr();function ay({key:t,value:e},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=gt.isNode(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(gt.isCollection(t)||!gt.isNode(t)&&typeof t=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let h=!d&&(!t||f&&e==null&&!i.inFlow||gt.isCollection(t)||(gt.isScalar(t)?t.type===Sd.Scalar.BLOCK_FOLDED||t.type===Sd.Scalar.BLOCK_LITERAL:typeof t=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,p=!1,m=Ed.stringify(t,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||e==null)return v&&r&&r(),m===""?"?":h?`? ${m}`:m}else if(a&&!d||e==null&&h)return m=`? ${m}`,f&&!v?m+=Cr.lineComment(m,i.indent,l(f)):p&&n&&n(),m;v&&(f=null),h?(f&&(m+=Cr.lineComment(m,i.indent,l(f))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,f&&(m+=Cr.lineComment(m,i.indent,l(f))));let b,N,P;gt.isNode(e)?(b=!!e.spaceBefore,N=e.commentBefore,P=e.comment):(b=!1,N=null,P=null,e&&typeof e=="object"&&(e=o.createNode(e))),i.implicitKey=!1,!h&&!f&&gt.isScalar(e)&&(i.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&gt.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(i.indent=i.indent.substring(2));let k=!1,E=Ed.stringify(e,i,()=>k=!0,()=>p=!0),y=" ";if(f||b||N){if(y=b?`
39
+ `:"",N){let x=l(N);y+=`
40
+ ${Cr.indentComment(x,i.indent)}`}E===""&&!i.inFlow?y===`
41
+ `&&P&&(y=`
42
42
 
43
43
  `):y+=`
44
- ${i.indent}`}else if(!p&&Ye.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 G=!1;if(E&&(w==="&"||w==="!")){let M=C.indexOf(" ");w==="&"&&M!==-1&&M<v&&C[M+1]==="!"&&(M=C.indexOf(" ",M+1)),(M===-1||v<M)&&(G=!0)}G||(y=`
46
- ${i.indent}`)}}else(C===""||C[0]===`
47
- `)&&(y="");return g+=y+C,i.inFlow?b&&n&&n():k&&!b?g+=tn.lineComment(g,i.indent,l(k)):h&&r&&r(),g}Au.stringifyPair=Mg});var qo=R(Bo=>{"use strict";var Tu=or("process");function Bg(e,...t){e==="debug"&&console.log(...t)}function qg(e,t){(e==="debug"||e==="warn")&&(typeof Tu.emitWarning=="function"?Tu.emitWarning(t):console.warn(t))}Bo.debug=Bg;Bo.warn=qg});var Cr=R(Er=>{"use strict";var Sr=D(),Iu=te(),br="<<",kr={identify:e=>e===br||typeof e=="symbol"&&e.description===br,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Iu.Scalar(Symbol(br)),{addToJSMap:_u}),stringify:()=>br},Vg=(e,t)=>(kr.identify(t)||Sr.isScalar(t)&&(!t.type||t.type===Iu.Scalar.PLAIN)&&kr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===kr.tag&&i.default);function _u(e,t,i){let n=ju(e,i);if(Sr.isSeq(n))for(let r of n.items)Vo(e,t,r);else if(Array.isArray(n))for(let r of n)Vo(e,t,r);else Vo(e,t,n)}function Vo(e,t,i){let n=ju(e,i);if(!Sr.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 ju(e,t){return e&&Sr.isAlias(t)?t.resolve(e.doc,e):t}Er.addMergeToJSMap=_u;Er.isMergeKey=Vg;Er.merge=kr});var zo=R(Hu=>{"use strict";var Wg=qo(),Ou=Cr(),zg=en(),$u=D(),Wo=ut();function Jg(e,t,{key:i,value:n}){if($u.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(Ou.isMergeKey(e,i))Ou.addMergeToJSMap(e,t,n);else{let r=Wo.toJS(i,"",e);if(t instanceof Map)t.set(r,Wo.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=Gg(i,r,e),o=Wo.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 Gg(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if($u.isNode(e)&&i?.doc){let n=zg.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)+'..."'),Wg.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)}Hu.addPairToJSMap=Jg});var pt=R(Jo=>{"use strict";var Fu=Ki(),Ug=xu(),Kg=zo(),Rr=D();function Yg(e,t,i){let n=Fu.createNode(e,void 0,i),r=Fu.createNode(t,void 0,i);return new Pr(n,r)}var Pr=class e{constructor(t,i=null){Object.defineProperty(this,Rr.NODE_TYPE,{value:Rr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return Rr.isNode(i)&&(i=i.clone(t)),Rr.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return Kg.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?Ug.stringifyPair(this,t,i,n):JSON.stringify(this)}};Jo.Pair=Pr;Jo.createPair=Yg});var Go=R(Lu=>{"use strict";var Ft=D(),Du=en(),Ar=Yi();function Xg(e,t,i){return(t.inFlow??e.flow?Zg:Qg)(e,t,i)}function Qg({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(Ft.isNode(h))!d&&h.spaceBefore&&f.push(""),xr(i,f,h.commentBefore,d),h.comment&&(g=h.comment);else if(Ft.isPair(h)){let N=Ft.isNode(h.key)?h.key:null;N&&(!d&&N.spaceBefore&&f.push(""),xr(i,f,N.commentBefore,d))}d=!1;let S=Du.stringify(h,u,()=>g=null,()=>d=!0);g&&(S+=Ar.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
- `+Ar.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Zg({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(Ft.isNode(h))h.spaceBefore&&d.push(""),xr(t,d,h.commentBefore,!1),h.comment&&(g=h.comment);else if(Ft.isPair(h)){let N=Ft.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&d.push(""),xr(t,d,N.commentBefore,!1),N.comment&&(l=!0));let k=Ft.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=Du.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+=Ar.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 xr({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=Ar.indentComment(t(n),e);i.push(a.trimStart())}}Lu.stringifyCollection=Xg});var vt=R(Ko=>{"use strict";var ew=Go(),tw=zo(),iw=mr(),mt=D(),Tr=pt(),nw=te();function nn(e,t){let i=mt.isScalar(t)?t.value:t;for(let n of e)if(mt.isPair(n)&&(n.key===t||n.key===i||mt.isScalar(n.key)&&n.key.value===i))return n}var Uo=class extends iw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(mt.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(Tr.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;mt.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Tr.Pair(t,t?.value):n=new Tr.Pair(t.key,t.value);let r=nn(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);mt.isScalar(r.value)&&nw.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=nn(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=nn(this.items,t)?.value;return(!i&&mt.isScalar(r)?r.value:r)??void 0}has(t){return!!nn(this.items,t)}set(t,i){this.add(new Tr.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)tw.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!mt.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})),ew.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};Ko.YAMLMap=Uo;Ko.findPair=nn});var hi=R(Bu=>{"use strict";var rw=D(),Mu=vt(),aw={collection:"map",default:!0,nodeClass:Mu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return rw.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Mu.YAMLMap.from(e,t,i)};Bu.map=aw});var gt=R(qu=>{"use strict";var ow=Ki(),sw=Go(),cw=mr(),_r=D(),lw=te(),uw=ut(),Yo=class extends cw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(_r.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ir(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=Ir(t);if(typeof n!="number")return;let r=this.items[n];return!i&&_r.isScalar(r)?r.value:r}has(t){let i=Ir(t);return typeof i=="number"&&i<this.items.length}set(t,i){let n=Ir(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[n];_r.isScalar(r)&&lw.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(uw.toJS(a,String(r++),i));return n}toString(t,i,n){return t?sw.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(ow.createNode(s,void 0,n))}}return a}};function Ir(e){let t=_r.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}qu.YAMLSeq=Yo});var pi=R(Wu=>{"use strict";var dw=D(),Vu=gt(),fw={collection:"seq",default:!0,nodeClass:Vu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return dw.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Vu.YAMLSeq.from(e,t,i)};Wu.seq=fw});var rn=R(zu=>{"use strict";var hw=Zi(),pw={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),hw.stringifyString(e,t,i,n)}};zu.string=pw});var jr=R(Uu=>{"use strict";var Ju=te(),Gu={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"&&Gu.test.test(e)?e:t.options.nullStr};Uu.nullTag=Gu});var Xo=R(Yu=>{"use strict";var mw=te(),Ku={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new mw.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Ku.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};Yu.boolTag=Ku});var mi=R(Xu=>{"use strict";function vw({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}Xu.stringifyNumber=vw});var Zo=R(Or=>{"use strict";var gw=te(),Qo=mi(),ww={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:Qo.stringifyNumber},yw={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():Qo.stringifyNumber(e)}},Nw={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 gw.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Qo.stringifyNumber};Or.float=Nw;Or.floatExp=yw;Or.floatNaN=ww});var ts=R(Hr=>{"use strict";var Qu=mi(),$r=e=>typeof e=="bigint"||Number.isInteger(e),es=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function Zu(e,t,i){let{value:n}=e;return $r(n)&&n>=0?i+n.toString(t):Qu.stringifyNumber(e)}var bw={identify:e=>$r(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>es(e,2,8,i),stringify:e=>Zu(e,8,"0o")},kw={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>es(e,0,10,i),stringify:Qu.stringifyNumber},Sw={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)=>es(e,2,16,i),stringify:e=>Zu(e,16,"0x")};Hr.int=kw;Hr.intHex=Sw;Hr.intOct=bw});var td=R(ed=>{"use strict";var Ew=hi(),Cw=jr(),Rw=pi(),Pw=rn(),Aw=Xo(),is=Zo(),ns=ts(),xw=[Ew.map,Rw.seq,Pw.string,Cw.nullTag,Aw.boolTag,ns.intOct,ns.int,ns.intHex,is.floatNaN,is.floatExp,is.float];ed.schema=xw});var rd=R(nd=>{"use strict";var Tw=te(),Iw=hi(),_w=pi();function id(e){return typeof e=="bigint"||Number.isInteger(e)}var Fr=({value:e})=>JSON.stringify(e),jw=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Fr},{identify:e=>e==null,createNode:()=>new Tw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Fr},{identify:id,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>id(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Fr}],Ow={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},$w=[Iw.map,_w.seq].concat(jw,Ow);nd.schema=$w});var as=R(ad=>{"use strict";var an=or("buffer"),rs=te(),Hw=Zi(),Fw={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof an.Buffer=="function")return an.Buffer.from(e,"base64");if(typeof atob=="function"){let 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 an.Buffer=="function")s=o instanceof an.Buffer?o.toString("base64"):an.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=rs.Scalar.BLOCK_LITERAL),t!==rs.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===rs.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return Hw.stringifyString({comment:e,type:t,value:s},n,r,a)}};ad.binary=Fw});var Mr=R(Lr=>{"use strict";var Dr=D(),os=pt(),Dw=te(),Lw=gt();function od(e,t){if(Dr.isSeq(e))for(let i=0;i<e.items.length;++i){let n=e.items[i];if(!Dr.isPair(n)){if(Dr.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new os.Pair(new Dw.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]=Dr.isPair(n)?n:new os.Pair(n)}}else t("Expected a sequence for this tag");return e}function sd(e,t,i){let{replacer:n}=i,r=new Lw.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(os.createPair(s,c,i))}return r}var Mw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:od,createNode:sd};Lr.createPairs=sd;Lr.pairs=Mw;Lr.resolvePairs=od});var ls=R(cs=>{"use strict";var cd=D(),ss=ut(),on=vt(),Bw=gt(),ld=Mr(),Dt=class e extends Bw.YAMLSeq{constructor(){super(),this.add=on.YAMLMap.prototype.add.bind(this),this.delete=on.YAMLMap.prototype.delete.bind(this),this.get=on.YAMLMap.prototype.get.bind(this),this.has=on.YAMLMap.prototype.has.bind(this),this.set=on.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(cd.isPair(r)?(a=ss.toJS(r.key,"",i),o=ss.toJS(r.value,a,i)):a=ss.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,i,n){let r=ld.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Dt.tag="tag:yaml.org,2002:omap";var qw={collection:"seq",identify:e=>e instanceof Map,nodeClass:Dt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=ld.resolvePairs(e,t),n=[];for(let{key:r}of i.items)cd.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Dt,i)},createNode:(e,t,i)=>Dt.from(e,t,i)};cs.YAMLOMap=Dt;cs.omap=qw});var pd=R(us=>{"use strict";var ud=te();function dd({value:e,source:t},i){return t&&(e?fd:hd).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var fd={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ud.Scalar(!0),stringify:dd},hd={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ud.Scalar(!1),stringify:dd};us.falseTag=hd;us.trueTag=fd});var md=R(Br=>{"use strict";var Vw=te(),ds=mi(),Ww={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:ds.stringifyNumber},zw={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():ds.stringifyNumber(e)}},Jw={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 Vw.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:ds.stringifyNumber};Br.float=Jw;Br.floatExp=zw;Br.floatNaN=Ww});var gd=R(cn=>{"use strict";var vd=mi(),sn=e=>typeof e=="bigint"||Number.isInteger(e);function qr(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 fs(e,t,i){let{value:n}=e;if(sn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return vd.stringifyNumber(e)}var Gw={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>qr(e,2,2,i),stringify:e=>fs(e,2,"0b")},Uw={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>qr(e,1,8,i),stringify:e=>fs(e,8,"0")},Kw={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>qr(e,0,10,i),stringify:vd.stringifyNumber},Yw={identify:sn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>qr(e,2,16,i),stringify:e=>fs(e,16,"0x")};cn.int=Kw;cn.intBin=Gw;cn.intHex=Yw;cn.intOct=Uw});var ps=R(hs=>{"use strict";var zr=D(),Vr=pt(),Wr=vt(),Lt=class e extends Wr.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;zr.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Vr.Pair(t.key,null):i=new Vr.Pair(t,null),Wr.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=Wr.findPair(this.items,t);return!i&&zr.isPair(n)?zr.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=Wr.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Vr.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(Vr.createPair(o,null,n));return a}};Lt.tag="tag:yaml.org,2002:set";var Xw={collection:"map",identify:e=>e instanceof Set,nodeClass:Lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Lt.from(e,t,i),resolve(e,t){if(zr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Lt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};hs.YAMLSet=Lt;hs.set=Xw});var vs=R(Jr=>{"use strict";var Qw=mi();function ms(e,t){let i=e[0],n=i==="-"||i==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function wd(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Qw.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 Zw={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})=>ms(e,i),stringify:wd},ey={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=>ms(e,!1),stringify:wd},yd={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(yd.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,n,r,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,n-1,r,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=ms(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$/,"")??""};Jr.floatTime=ey;Jr.intTime=Zw;Jr.timestamp=yd});var kd=R(bd=>{"use strict";var ty=hi(),iy=jr(),ny=pi(),ry=rn(),ay=as(),Nd=pd(),gs=md(),Gr=gd(),oy=Cr(),sy=ls(),cy=Mr(),ly=ps(),ws=vs(),uy=[ty.map,ny.seq,ry.string,iy.nullTag,Nd.trueTag,Nd.falseTag,Gr.intBin,Gr.intOct,Gr.int,Gr.intHex,gs.floatNaN,gs.floatExp,gs.float,ay.binary,oy.merge,sy.omap,cy.pairs,ly.set,ws.intTime,ws.floatTime,ws.timestamp];bd.schema=uy});var _d=R(bs=>{"use strict";var Rd=hi(),dy=jr(),Pd=pi(),fy=rn(),hy=Xo(),ys=Zo(),Ns=ts(),py=td(),my=rd(),Ad=as(),ln=Cr(),xd=ls(),Td=Mr(),Sd=kd(),Id=ps(),Ur=vs(),Ed=new Map([["core",py.schema],["failsafe",[Rd.map,Pd.seq,fy.string]],["json",my.schema],["yaml11",Sd.schema],["yaml-1.1",Sd.schema]]),Cd={binary:Ad.binary,bool:hy.boolTag,float:ys.float,floatExp:ys.floatExp,floatNaN:ys.floatNaN,floatTime:Ur.floatTime,int:Ns.int,intHex:Ns.intHex,intOct:Ns.intOct,intTime:Ur.intTime,map:Rd.map,merge:ln.merge,null:dy.nullTag,omap:xd.omap,pairs:Td.pairs,seq:Pd.seq,set:Id.set,timestamp:Ur.timestamp},vy={"tag:yaml.org,2002:binary":Ad.binary,"tag:yaml.org,2002:merge":ln.merge,"tag:yaml.org,2002:omap":xd.omap,"tag:yaml.org,2002:pairs":Td.pairs,"tag:yaml.org,2002:set":Id.set,"tag:yaml.org,2002:timestamp":Ur.timestamp};function gy(e,t,i){let n=Ed.get(t);if(n&&!e)return i&&!n.includes(ln.merge)?n.concat(ln.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(Ed.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)r=r.concat(a);else typeof e=="function"&&(r=e(r.slice()));return i&&(r=r.concat(ln.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Cd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Cd).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}bs.coreKnownTags=vy;bs.getTags=gy});var Es=R(jd=>{"use strict";var ks=D(),wy=hi(),yy=pi(),Ny=rn(),Kr=_d(),by=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Ss=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Kr.getTags(t,"compat"):t?Kr.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?Kr.coreKnownTags:{},this.tags=Kr.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,ks.MAP,{value:wy.map}),Object.defineProperty(this,ks.SCALAR,{value:Ny.string}),Object.defineProperty(this,ks.SEQ,{value:yy.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?by:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};jd.Schema=Ss});var $d=R(Od=>{"use strict";var ky=D(),Cs=en(),un=Yi();function Sy(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=Cs.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(un.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(ky.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(un.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Cs.stringify(e.contents,r,()=>s=null,c);s&&(l+=un.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Cs.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(un.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(un.indentComment(a(c),"")))}return i.join(`
44
+ ${i.indent}`}else if(!h&&gt.isCollection(e)){let x=E[0],w=E.indexOf(`
45
+ `),g=w!==-1,S=i.inFlow??e.flow??e.items.length===0;if(g||!S){let H=!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)&&(H=!0)}H||(y=`
46
+ ${i.indent}`)}}else(E===""||E[0]===`
47
+ `)&&(y="");return m+=y+E,i.inFlow?k&&r&&r():P&&!k?m+=Cr.lineComment(m,i.indent,l(P)):p&&n&&n(),m}Pd.stringifyPair=ay});var ks=C(bs=>{"use strict";var Cd=On("process");function oy(t,...e){t==="debug"&&console.log(...e)}function sy(t,e){(t==="debug"||t==="warn")&&(typeof Cd.emitWarning=="function"?Cd.emitWarning(e):console.warn(e))}bs.debug=oy;bs.warn=sy});var ta=C(ea=>{"use strict";var Zn=L(),Rd=ie(),Xn="<<",Qn={identify:t=>t===Xn||typeof t=="symbol"&&t.description===Xn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Rd.Scalar(Symbol(Xn)),{addToJSMap:Ad}),stringify:()=>Xn},cy=(t,e)=>(Qn.identify(e)||Zn.isScalar(e)&&(!e.type||e.type===Rd.Scalar.PLAIN)&&Qn.identify(e.value))&&t?.doc.schema.tags.some(i=>i.tag===Qn.tag&&i.default);function Ad(t,e,i){let r=_d(t,i);if(Zn.isSeq(r))for(let n of r.items)Ss(t,e,n);else if(Array.isArray(r))for(let n of r)Ss(t,e,n);else Ss(t,e,r)}function Ss(t,e,i){let r=_d(t,i);if(!Zn.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function _d(t,e){return t&&Zn.isAlias(e)?e.resolve(t.doc,t):e}ea.addMergeToJSMap=Ad;ea.isMergeKey=cy;ea.merge=Qn});var Ps=C(jd=>{"use strict";var ly=ks(),Td=ta(),uy=xr(),Id=L(),Es=It();function dy(t,e,{key:i,value:r}){if(Id.isNode(i)&&i.addToJSMap)i.addToJSMap(t,e,r);else if(Td.isMergeKey(t,i))Td.addMergeToJSMap(t,e,r);else{let n=Es.toJS(i,"",t);if(e instanceof Map)e.set(n,Es.toJS(r,n,t));else if(e instanceof Set)e.add(n);else{let a=fy(i,n,t),o=Es.toJS(r,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function fy(t,e,i){if(e===null)return"";if(typeof e!="object")return String(e);if(Id.isNode(t)&&i?.doc){let r=uy.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=t.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),ly.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(e)}jd.addPairToJSMap=dy});var Ht=C(xs=>{"use strict";var $d=br(),py=xd(),hy=Ps(),ia=L();function my(t,e,i){let r=$d.createNode(t,void 0,i),n=$d.createNode(e,void 0,i);return new ra(r,n)}var ra=class t{constructor(e,i=null){Object.defineProperty(this,ia.NODE_TYPE,{value:ia.PAIR}),this.key=e,this.value=i}clone(e){let{key:i,value:r}=this;return ia.isNode(i)&&(i=i.clone(e)),ia.isNode(r)&&(r=r.clone(e)),new t(i,r)}toJSON(e,i){let r=i?.mapAsMap?new Map:{};return hy.addPairToJSMap(i,r,this)}toString(e,i,r){return e?.doc?py.stringifyPair(this,e,i,r):JSON.stringify(this)}};xs.Pair=ra;xs.createPair=my});var Cs=C(Hd=>{"use strict";var ci=L(),Od=xr(),na=kr();function vy(t,e,i){return(e.inFlow??t.flow?wy:gy)(t,e,i)}function gy({comment:t,items:e},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<e.length;++v){let p=e[v],m=null;if(ci.isNode(p))!d&&p.spaceBefore&&f.push(""),aa(i,f,p.commentBefore,d),p.comment&&(m=p.comment);else if(ci.isPair(p)){let N=ci.isNode(p.key)?p.key:null;N&&(!d&&N.spaceBefore&&f.push(""),aa(i,f,N.commentBefore,d))}d=!1;let b=Od.stringify(p,u,()=>m=null,()=>d=!0);m&&(b+=na.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 t?(h+=`
50
+ `+na.indentComment(l(t),c),s&&s()):d&&o&&o(),h}function wy({items:t},e,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;r+=a;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if(ci.isNode(p))p.spaceBefore&&d.push(""),aa(e,d,p.commentBefore,!1),p.comment&&(m=p.comment);else if(ci.isPair(p)){let N=ci.isNode(p.key)?p.key:null;N&&(N.spaceBefore&&d.push(""),aa(e,d,N.commentBefore,!1),N.comment&&(l=!0));let P=ci.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=Od.stringify(p,c,()=>m=null);l||(l=d.length>u||b.includes(`
51
+ `)),v<t.length-1?b+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=d.reduce((N,P)=>N+P.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),m&&(b+=na.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=e.options.lineWidth>0&&v>e.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 aa({indent:t,options:{commentString:e}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=na.indentComment(e(r),t);i.push(a.trimStart())}}Hd.stringifyCollection=vy});var Bt=C(As=>{"use strict";var yy=Cs(),Ny=Ps(),by=zn(),Dt=L(),oa=Ht(),ky=ie();function Rr(t,e){let i=Dt.isScalar(e)?e.value:e;for(let r of t)if(Dt.isPair(r)&&(r.key===e||r.key===i||Dt.isScalar(r.key)&&r.key.value===i))return r}var Rs=class extends by.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Dt.MAP,e),this.items=[]}static from(e,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(e),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(oa.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 e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,i){let r;Dt.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new oa.Pair(e,e?.value):r=new oa.Pair(e.key,e.value);let n=Rr(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Dt.isScalar(n.value)&&ky.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(e){let i=Rr(this.items,e);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(e,i){let n=Rr(this.items,e)?.value;return(!i&&Dt.isScalar(n)?n.value:n)??void 0}has(e){return!!Rr(this.items,e)}set(e,i){this.add(new oa.Pair(e,i),!0)}toJSON(e,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)Ny.addPairToJSMap(i,n,a);return n}toString(e,i,r){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Dt.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),yy.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:i})}};As.YAMLMap=Rs;As.findPair=Rr});var _i=C(Bd=>{"use strict";var Sy=L(),Dd=Bt(),Ey={collection:"map",default:!0,nodeClass:Dd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Sy.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,i)=>Dd.YAMLMap.from(t,e,i)};Bd.map=Ey});var Ft=C(Fd=>{"use strict";var Py=br(),xy=Cs(),Cy=zn(),ca=L(),Ry=ie(),Ay=It(),_s=class extends Cy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ca.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let i=sa(e);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(e,i){let r=sa(e);if(typeof r!="number")return;let n=this.items[r];return!i&&ca.isScalar(n)?n.value:n}has(e){let i=sa(e);return typeof i=="number"&&i<this.items.length}set(e,i){let r=sa(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[r];ca.isScalar(n)&&Ry.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(e,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(Ay.toJS(a,String(n++),i));return r}toString(e,i,r){return e?xy.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(e,i,r){let{replacer:n}=r,a=new this(e);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(Py.createNode(s,void 0,r))}}return a}};function sa(t){let e=ca.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Fd.YAMLSeq=_s});var Ti=C(Md=>{"use strict";var _y=L(),Ld=Ft(),Ty={collection:"seq",default:!0,nodeClass:Ld.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return _y.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,i)=>Ld.YAMLSeq.from(t,e,i)};Md.seq=Ty});var Ar=C(qd=>{"use strict";var Iy=Pr(),jy={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,i,r){return e=Object.assign({actualString:!0},e),Iy.stringifyString(t,e,i,r)}};qd.string=jy});var la=C(zd=>{"use strict";var Vd=ie(),Wd={identify:t=>t==null,createNode:()=>new Vd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Vd.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Wd.test.test(t)?t:e.options.nullStr};zd.nullTag=Wd});var Ts=C(Gd=>{"use strict";var $y=ie(),Jd={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new $y.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},i){if(t&&Jd.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?i.options.trueStr:i.options.falseStr}};Gd.boolTag=Jd});var Ii=C(Ud=>{"use strict";function Oy({format:t,minFractionDigits:e,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(!t&&e&&(!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=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Ud.stringifyNumber=Oy});var js=C(ua=>{"use strict";var Hy=ie(),Is=Ii(),Dy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Is.stringifyNumber},By={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Is.stringifyNumber(t)}},Fy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Hy.Scalar(parseFloat(t)),i=t.indexOf(".");return i!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-i-1),e},stringify:Is.stringifyNumber};ua.float=Fy;ua.floatExp=By;ua.floatNaN=Dy});var Os=C(fa=>{"use strict";var Kd=Ii(),da=t=>typeof t=="bigint"||Number.isInteger(t),$s=(t,e,i,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),i);function Yd(t,e,i){let{value:r}=t;return da(r)&&r>=0?i+r.toString(e):Kd.stringifyNumber(t)}var Ly={identify:t=>da(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,i)=>$s(t,2,8,i),stringify:t=>Yd(t,8,"0o")},My={identify:da,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,i)=>$s(t,0,10,i),stringify:Kd.stringifyNumber},qy={identify:t=>da(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,i)=>$s(t,2,16,i),stringify:t=>Yd(t,16,"0x")};fa.int=My;fa.intHex=qy;fa.intOct=Ly});var Qd=C(Xd=>{"use strict";var Vy=_i(),Wy=la(),zy=Ti(),Jy=Ar(),Gy=Ts(),Hs=js(),Ds=Os(),Uy=[Vy.map,zy.seq,Jy.string,Wy.nullTag,Gy.boolTag,Ds.intOct,Ds.int,Ds.intHex,Hs.floatNaN,Hs.floatExp,Hs.float];Xd.schema=Uy});var tf=C(ef=>{"use strict";var Ky=ie(),Yy=_i(),Xy=Ti();function Zd(t){return typeof t=="bigint"||Number.isInteger(t)}var pa=({value:t})=>JSON.stringify(t),Qy=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:pa},{identify:t=>t==null,createNode:()=>new Ky.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:pa},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:pa},{identify:Zd,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:i})=>i?BigInt(t):parseInt(t,10),stringify:({value:t})=>Zd(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:pa}],Zy={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},eN=[Yy.map,Xy.seq].concat(Qy,Zy);ef.schema=eN});var Fs=C(rf=>{"use strict";var _r=On("buffer"),Bs=ie(),tN=Pr(),iN={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof _r.Buffer=="function")return _r.Buffer.from(t,"base64");if(typeof atob=="function"){let i=atob(t.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 e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof _r.Buffer=="function")s=o instanceof _r.Buffer?o.toString("base64"):_r.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Bs.Scalar.BLOCK_LITERAL),e!==Bs.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(e===Bs.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return tN.stringifyString({comment:t,type:e,value:s},r,n,a)}};rf.binary=iN});var va=C(ma=>{"use strict";var ha=L(),Ls=Ht(),rN=ie(),nN=Ft();function nf(t,e){if(ha.isSeq(t))for(let i=0;i<t.items.length;++i){let r=t.items[i];if(!ha.isPair(r)){if(ha.isMap(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let n=r.items[0]||new Ls.Pair(new rN.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}t.items[i]=ha.isPair(r)?r:new Ls.Pair(r)}}else e("Expected a sequence for this tag");return t}function af(t,e,i){let{replacer:r}=i,n=new nN.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Ls.createPair(s,c,i))}return n}var aN={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:nf,createNode:af};ma.createPairs=af;ma.pairs=aN;ma.resolvePairs=nf});var Vs=C(qs=>{"use strict";var of=L(),Ms=It(),Tr=Bt(),oN=Ft(),sf=va(),li=class t extends oN.YAMLSeq{constructor(){super(),this.add=Tr.YAMLMap.prototype.add.bind(this),this.delete=Tr.YAMLMap.prototype.delete.bind(this),this.get=Tr.YAMLMap.prototype.get.bind(this),this.has=Tr.YAMLMap.prototype.has.bind(this),this.set=Tr.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,i){if(!i)return super.toJSON(e);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(of.isPair(n)?(a=Ms.toJS(n.key,"",i),o=Ms.toJS(n.value,a,i)):a=Ms.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(e,i,r){let n=sf.createPairs(e,i,r),a=new this;return a.items=n.items,a}};li.tag="tag:yaml.org,2002:omap";var sN={collection:"seq",identify:t=>t instanceof Map,nodeClass:li,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let i=sf.resolvePairs(t,e),r=[];for(let{key:n}of i.items)of.isScalar(n)&&(r.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new li,i)},createNode:(t,e,i)=>li.from(t,e,i)};qs.YAMLOMap=li;qs.omap=sN});var ff=C(Ws=>{"use strict";var cf=ie();function lf({value:t,source:e},i){return e&&(t?uf:df).test.test(e)?e:t?i.options.trueStr:i.options.falseStr}var uf={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new cf.Scalar(!0),stringify:lf},df={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new cf.Scalar(!1),stringify:lf};Ws.falseTag=df;Ws.trueTag=uf});var pf=C(ga=>{"use strict";var cN=ie(),zs=Ii(),lN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:zs.stringifyNumber},uN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():zs.stringifyNumber(t)}},dN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new cN.Scalar(parseFloat(t.replace(/_/g,""))),i=t.indexOf(".");if(i!==-1){let r=t.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:zs.stringifyNumber};ga.float=dN;ga.floatExp=uN;ga.floatNaN=lN});var mf=C(jr=>{"use strict";var hf=Ii(),Ir=t=>typeof t=="bigint"||Number.isInteger(t);function wa(t,e,i,{intAsBigInt:r}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(i){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,i);return n==="-"?-1*a:a}function Js(t,e,i){let{value:r}=t;if(Ir(r)){let n=r.toString(e);return r<0?"-"+i+n.substr(1):i+n}return hf.stringifyNumber(t)}var fN={identify:Ir,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,i)=>wa(t,2,2,i),stringify:t=>Js(t,2,"0b")},pN={identify:Ir,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,i)=>wa(t,1,8,i),stringify:t=>Js(t,8,"0")},hN={identify:Ir,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,i)=>wa(t,0,10,i),stringify:hf.stringifyNumber},mN={identify:Ir,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,i)=>wa(t,2,16,i),stringify:t=>Js(t,16,"0x")};jr.int=hN;jr.intBin=fN;jr.intHex=mN;jr.intOct=pN});var Us=C(Gs=>{"use strict";var ba=L(),ya=Ht(),Na=Bt(),ui=class t extends Na.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let i;ba.isPair(e)?i=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?i=new ya.Pair(e.key,null):i=new ya.Pair(e,null),Na.findPair(this.items,i.key)||this.items.push(i)}get(e,i){let r=Na.findPair(this.items,e);return!i&&ba.isPair(r)?ba.isScalar(r.key)?r.key.value:r.key:r}set(e,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Na.findPair(this.items,e);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new ya.Pair(e))}toJSON(e,i){return super.toJSON(e,i,Set)}toString(e,i,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(e,i,r){let{replacer:n}=r,a=new this(e);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(ya.createPair(o,null,r));return a}};ui.tag="tag:yaml.org,2002:set";var vN={collection:"map",identify:t=>t instanceof Set,nodeClass:ui,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,i)=>ui.from(t,e,i),resolve(t,e){if(ba.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new ui,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Gs.YAMLSet=ui;Gs.set=vN});var Ys=C(ka=>{"use strict";var gN=Ii();function Ks(t,e){let i=t[0],r=i==="-"||i==="+"?t.substring(1):t,n=o=>e?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 vf(t){let{value:e}=t,i=o=>o;if(typeof e=="bigint")i=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return gN.stringifyNumber(t);let r="";e<0&&(r="-",e*=i(-1));let n=i(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var wN={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:i})=>Ks(t,i),stringify:vf},yN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Ks(t,!1),stringify:vf},gf={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(t){let e=t.match(gf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let d=Ks(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ka.floatTime=yN;ka.intTime=wN;ka.timestamp=gf});var Nf=C(yf=>{"use strict";var NN=_i(),bN=la(),kN=Ti(),SN=Ar(),EN=Fs(),wf=ff(),Xs=pf(),Sa=mf(),PN=ta(),xN=Vs(),CN=va(),RN=Us(),Qs=Ys(),AN=[NN.map,kN.seq,SN.string,bN.nullTag,wf.trueTag,wf.falseTag,Sa.intBin,Sa.intOct,Sa.int,Sa.intHex,Xs.floatNaN,Xs.floatExp,Xs.float,EN.binary,PN.merge,xN.omap,CN.pairs,RN.set,Qs.intTime,Qs.floatTime,Qs.timestamp];yf.schema=AN});var _f=C(tc=>{"use strict";var Ef=_i(),_N=la(),Pf=Ti(),TN=Ar(),IN=Ts(),Zs=js(),ec=Os(),jN=Qd(),$N=tf(),xf=Fs(),$r=ta(),Cf=Vs(),Rf=va(),bf=Nf(),Af=Us(),Ea=Ys(),kf=new Map([["core",jN.schema],["failsafe",[Ef.map,Pf.seq,TN.string]],["json",$N.schema],["yaml11",bf.schema],["yaml-1.1",bf.schema]]),Sf={binary:xf.binary,bool:IN.boolTag,float:Zs.float,floatExp:Zs.floatExp,floatNaN:Zs.floatNaN,floatTime:Ea.floatTime,int:ec.int,intHex:ec.intHex,intOct:ec.intOct,intTime:Ea.intTime,map:Ef.map,merge:$r.merge,null:_N.nullTag,omap:Cf.omap,pairs:Rf.pairs,seq:Pf.seq,set:Af.set,timestamp:Ea.timestamp},ON={"tag:yaml.org,2002:binary":xf.binary,"tag:yaml.org,2002:merge":$r.merge,"tag:yaml.org,2002:omap":Cf.omap,"tag:yaml.org,2002:pairs":Rf.pairs,"tag:yaml.org,2002:set":Af.set,"tag:yaml.org,2002:timestamp":Ea.timestamp};function HN(t,e,i){let r=kf.get(e);if(r&&!t)return i&&!r.includes($r.merge)?r.concat($r.merge):r.slice();let n=r;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(kf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return i&&(n=n.concat($r.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Sf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Sf).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},[])}tc.coreKnownTags=ON;tc.getTags=HN});var nc=C(Tf=>{"use strict";var ic=L(),DN=_i(),BN=Ti(),FN=Ar(),Pa=_f(),LN=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,rc=class t{constructor({compat:e,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Pa.getTags(e,"compat"):e?Pa.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Pa.coreKnownTags:{},this.tags=Pa.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,ic.MAP,{value:DN.map}),Object.defineProperty(this,ic.SCALAR,{value:FN.string}),Object.defineProperty(this,ic.SEQ,{value:BN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?LN:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Tf.Schema=rc});var jf=C(If=>{"use strict";var MN=L(),ac=xr(),Or=kr();function qN(t,e){let i=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(i.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&i.push("---");let n=ac.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){i.length!==1&&i.unshift("");let c=a(t.commentBefore);i.unshift(Or.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(MN.isNode(t.contents)){if(t.contents.spaceBefore&&r&&i.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);i.push(Or.indentComment(u,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=ac.stringify(t.contents,n,()=>s=null,c);s&&(l+=Or.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(ac.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(Or.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(Or.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}Od.stringifyDocument=Sy});var dn=R(Hd=>{"use strict";var Ey=Ui(),vi=mr(),be=D(),Cy=pt(),Ry=ut(),Py=Es(),Ay=$d(),Rs=dr(),xy=To(),Ty=Ki(),Ps=xo(),As=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 Ps.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){gi(this.contents)&&this.contents.add(t)}addIn(t,i){gi(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=Rs.anchorNames(this);t.anchor=!i||n.has(i)?Rs.findNewAnchor(i||"a",n):i}return new Ey.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}=Rs.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=Ty.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 Cy.Pair(r,a)}delete(t){return gi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return vi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):gi(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 vi.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 vi.isEmptyPath(t)?this.contents!==void 0:be.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=vi.collectionFromPath(this.schema,[t],i):gi(this.contents)&&this.contents.set(t,i)}setIn(t,i){vi.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=vi.collectionFromPath(this.schema,Array.from(t),i):gi(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 Ps.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 Ps.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 Py.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=Ry.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"?xy.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 Ay.stringifyDocument(this,t)}};function gi(e){if(be.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Hd.Document=As});var pn=R(hn=>{"use strict";var fn=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},xs=class extends fn{constructor(t,i,n){super("YAMLParseError",t,i,n)}},Ts=class extends fn{constructor(t,i,n){super("YAMLWarning",t,i,n)}},Iy=(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
+ `}If.stringifyDocument=qN});var Hr=C($f=>{"use strict";var VN=Nr(),ji=zn(),Ie=L(),WN=Ht(),zN=It(),JN=nc(),GN=jf(),oc=Mn(),UN=us(),KN=br(),sc=ls(),cc=class t{constructor(e,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ie.NODE_TYPE,{value:Ie.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 sc.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,n,r)}clone(){let e=Object.create(t.prototype,{[Ie.NODE_TYPE]:{value:Ie.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Ie.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){$i(this.contents)&&this.contents.add(e)}addIn(e,i){$i(this.contents)&&this.contents.addIn(e,i)}createAlias(e,i){if(!e.anchor){let r=oc.anchorNames(this);e.anchor=!i||r.has(i)?oc.findNewAnchor(i||"a",r):i}return new VN.Alias(e.anchor)}createNode(e,i,r){let n;if(typeof i=="function")e=i.call({"":e},"",e),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}=oc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=KN.createNode(e,u,v);return s&&Ie.isCollection(p)&&(p.flow=!0),f(),p}createPair(e,i,r={}){let n=this.createNode(e,null,r),a=this.createNode(i,null,r);return new WN.Pair(n,a)}delete(e){return $i(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ji.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):$i(this.contents)?this.contents.deleteIn(e):!1}get(e,i){return Ie.isCollection(this.contents)?this.contents.get(e,i):void 0}getIn(e,i){return ji.isEmptyPath(e)?!i&&Ie.isScalar(this.contents)?this.contents.value:this.contents:Ie.isCollection(this.contents)?this.contents.getIn(e,i):void 0}has(e){return Ie.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return ji.isEmptyPath(e)?this.contents!==void 0:Ie.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,i){this.contents==null?this.contents=ji.collectionFromPath(this.schema,[e],i):$i(this.contents)&&this.contents.set(e,i)}setIn(e,i){ji.isEmptyPath(e)?this.contents=i:this.contents==null?this.contents=ji.collectionFromPath(this.schema,Array.from(e),i):$i(this.contents)&&this.contents.setIn(e,i)}setSchema(e,i={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new sc.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new sc.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new JN.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=zN.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"?UN.applyReviver(o,{"":c},"",c):c}toJSON(e,i){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:i})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let i=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return GN.stringifyDocument(this,e)}};function $i(t){if(Ie.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}$f.Document=cc});var Fr=C(Br=>{"use strict";var Dr=class extends Error{constructor(e,i,r,n){super(),this.name=e,this.code=r,this.message=n,this.pos=i}},lc=class extends Dr{constructor(e,i,r){super("YAMLParseError",e,i,r)}},uc=class extends Dr{constructor(e,i,r){super("YAMLWarning",e,i,r)}},YN=(t,e)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>e.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=t.substring(e.lineStarts[r-1],e.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=t.substring(e.lineStarts[r-2],e.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
- `}};hn.YAMLError=fn;hn.YAMLParseError=xs;hn.YAMLWarning=Ts;hn.prettifyError=Iy});var mn=R(Fd=>{"use strict";function _y(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}}Fd.resolveProps=_y});var Yr=R(Dd=>{"use strict";function Is(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(Is(t.key)||Is(t.value))return!0}return!1;default:return!0}}Dd.containsNewline=Is});var _s=R(Ld=>{"use strict";var jy=Yr();function Oy(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&jy.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ld.flowIndentCheck=Oy});var js=R(Bd=>{"use strict";var Md=D();function $y(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||Md.isScalar(a)&&Md.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Bd.mapIncludes=$y});var Gd=R(Jd=>{"use strict";var qd=pt(),Hy=vt(),Vd=mn(),Fy=Yr(),Wd=_s(),Dy=js(),zd="All mapping items must start at the same column";function Ly({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??Hy.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=Vd.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",zd)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Fy.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",zd);i.atKey=!0;let S=h.end,N=f?e(i,f,h,r):t(i,S,d,null,h,r);i.schema.compat&&Wd.flowIndentCheck(n.indent,f,r),i.atKey=!1,Dy.mapIncludes(i,s.items,N)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let k=Vd.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&&Wd.flowIndentCheck(n.indent,m,r),c=b.range[2];let C=new qd.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 qd.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=Ly});var Kd=R(Ud=>{"use strict";var My=gt(),By=mn(),qy=_s();function Vy({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??My.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=By.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&&qy.flowIndentCheck(n.indent,d,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}Ud.resolveBlockSeq=Vy});var wi=R(Yd=>{"use strict";function Wy(e,t,i,n){let r="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";r?r+=o+u:r=u,o="";break}case"newline":r&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:r,offset:t}}Yd.resolveEnd=Wy});var ef=R(Zd=>{"use strict";var zy=D(),Jy=pt(),Xd=vt(),Gy=gt(),Uy=wi(),Qd=mn(),Ky=Yr(),Yy=js(),Os="Block collections are not allowed within flow collections",$s=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Xy({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Xd.YAMLMap:Gy.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=Qd.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&&Ky.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];zy.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],$s(C)&&r(w.range,"BLOCK_IN_FLOW",Os)}else{i.atKey=!0;let w=y.end,v=k?e(i,k,y,r):t(i,w,N,null,y,r);$s(k)&&r(v.range,"BLOCK_IN_FLOW",Os),i.atKey=!1;let E=Qd.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 M of b){if(M===E.found)break;if(M.type==="newline"){r(M,"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?$s(C)&&r(I.range,"BLOCK_IN_FLOW",Os):E.comment&&(v.comment?v.comment+=`
71
- `+E.comment:v.comment=E.comment);let G=new Jy.Pair(v,I);if(i.options.keepSourceTokens&&(G.srcToken=S),o){let M=l;Yy.mapIncludes(i,M.items,v)&&r(w,"DUPLICATE_KEY","Map keys must be unique"),M.items.push(G)}else{let M=new Xd.YAMLMap(i.schema);M.flow=!0,M.items.push(G);let z=(I??v).range;M.range=[v.range[0],z[1],z[2]],l.items.push(M)}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=Uy.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}Zd.resolveFlowCollection=Xy});var nf=R(tf=>{"use strict";var Qy=D(),Zy=te(),eN=vt(),tN=gt(),iN=Gd(),nN=Kd(),rN=ef();function Hs(e,t,i,n,r,a){let o=i.type==="block-map"?iN.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?nN.resolveBlockSeq(e,t,i,n,a):rN.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 aN(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===eN.YAMLMap.tagName&&s==="map"||o===tN.YAMLSeq.tagName&&s==="seq")return Hs(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),Hs(e,t,i,r,o)}let l=Hs(e,t,i,r,o,c),u=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Qy.isNode(u)?u:new Zy.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}tf.composeCollection=aN});var Ds=R(rf=>{"use strict";var Fs=te();function oN(e,t,i){let n=t.offset,r=sN(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?Fs.Scalar.BLOCK_FOLDED:Fs.Scalar.BLOCK_LITERAL,o=t.source?cN(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===Fs.Scalar.BLOCK_LITERAL?(d+=f+g.slice(c)+S,f=`
75
- `):g.length>c||S[0]===" "?(f===" "?f=`
76
- `:!p&&f===`
65
+ `}};Br.YAMLError=Dr;Br.YAMLParseError=lc;Br.YAMLWarning=uc;Br.prettifyError=YN});var Lr=C(Of=>{"use strict";function XN(t,{flow:e,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 t)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":!e&&(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 ${e??"collection"}`),k=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(e){P&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),P=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let y=t[t.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}}Of.resolveProps=XN});var xa=C(Hf=>{"use strict";function dc(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
66
+ `))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let i of e.start)if(i.type==="newline")return!0;if(e.sep){for(let i of e.sep)if(i.type==="newline")return!0}if(dc(e.key)||dc(e.value))return!0}return!1;default:return!0}}Hf.containsNewline=dc});var fc=C(Df=>{"use strict";var QN=xa();function ZN(t,e,i){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&QN.containsNewline(e)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Df.flowIndentCheck=ZN});var pc=C(Ff=>{"use strict";var Bf=L();function eb(t,e,i){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Bf.isScalar(a)&&Bf.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,i))}Ff.mapIncludes=eb});var zf=C(Wf=>{"use strict";var Lf=Ht(),tb=Bt(),Mf=Lr(),ib=xa(),qf=fc(),rb=pc(),Vf="All mapping items must start at the same column";function nb({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??tb.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=Mf.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",Vf)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
67
+ `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||ib.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",Vf);i.atKey=!0;let b=p.end,N=f?t(i,f,p,n):e(i,b,d,null,p,n);i.schema.compat&&qf.flowIndentCheck(r.indent,f,n),i.atKey=!1,rb.mapIncludes(i,s.items,N)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let P=Mf.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?t(i,v,P,n):e(i,c,h,null,P,n);i.schema.compat&&qf.flowIndentCheck(r.indent,v,n),c=k.range[2];let E=new Lf.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 Lf.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}Wf.resolveBlockMap=nb});var Gf=C(Jf=>{"use strict";var ab=Ft(),ob=Lr(),sb=fc();function cb({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=a?.nodeClass??ab.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=ob.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?t(i,d,f,n):e(i,f.end,u,null,f,n);i.schema.compat&&sb.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Jf.resolveBlockSeq=cb});var Oi=C(Uf=>{"use strict";function lb(t,e,i,r){let n="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{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`)}e+=c.length}}return{comment:n,offset:e}}Uf.resolveEnd=lb});var Qf=C(Xf=>{"use strict";var ub=L(),db=Ht(),Kf=Bt(),fb=Ft(),pb=Oi(),Yf=Lr(),hb=xa(),mb=pc(),hc="Block collections are not allowed within flow collections",mc=t=>t&&(t.type==="block-map"||t.type==="block-seq");function vb({composeNode:t,composeEmptyNode:e},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Kf.YAMLMap:fb.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let 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=Yf.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&&hb.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];ub.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?t(i,E,y,n):e(i,y.end,k,null,y,n);l.items.push(x),d=x.range[2],mc(E)&&n(x.range,"BLOCK_IN_FLOW",hc)}else{i.atKey=!0;let x=y.end,w=P?t(i,P,y,n):e(i,x,N,null,y,n);mc(P)&&n(w.range,"BLOCK_IN_FLOW",hc),i.atKey=!1;let g=Yf.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?t(i,E,g,n):g.found?e(i,g.end,k,null,g,n):null;S?mc(E)&&n(S.range,"BLOCK_IN_FLOW",hc):g.comment&&(w.comment?w.comment+=`
71
+ `+g.comment:w.comment=g.comment);let H=new db.Pair(w,S);if(i.options.keepSourceTokens&&(H.srcToken=b),o){let I=l;mb.mapIncludes(i,I.items,w)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),I.items.push(H)}else{let I=new Kf.YAMLMap(i.schema);I.flow=!0,I.items.push(H);let ue=(S??w).range;I.range=[w.range[0],ue[1],ue[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=pb.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}Xf.resolveFlowCollection=vb});var ep=C(Zf=>{"use strict";var gb=L(),wb=ie(),yb=Bt(),Nb=Ft(),bb=zf(),kb=Gf(),Sb=Qf();function vc(t,e,i,r,n,a){let o=i.type==="block-map"?bb.resolveBlockMap(t,e,i,r,a):i.type==="block-seq"?kb.resolveBlockSeq(t,e,i,r,a):Sb.resolveFlowCollection(t,e,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Eb(t,e,i,r,n){let a=r.tag,o=a?e.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===yb.YAMLMap.tagName&&s==="map"||o===Nb.YAMLSeq.tagName&&s==="seq")return vc(t,e,i,n,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=e.schema.knownTags[o];if(f?.collection===s)e.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),vc(t,e,i,n,o)}let l=vc(t,e,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),e.options)??l,d=gb.isNode(u)?u:new wb.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Zf.composeCollection=Eb});var wc=C(tp=>{"use strict";var gc=ie();function Pb(t,e,i){let r=e.offset,n=xb(e,t.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?gc.Scalar.BLOCK_FOLDED:gc.Scalar.BLOCK_LITERAL,o=e.source?Cb(e.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return e.source&&(m+=e.source.length),{value:p,type:a,comment:n.comment,range:[r,m,m]}}let c=e.indent+n.indent,l=e.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&&!t.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===gc.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 sN({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 cN(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}rf.resolveBlockScalar=oN});var Ms=R(of=>{"use strict";var Ls=te(),lN=wi();function uN(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=Ls.Scalar.PLAIN,c=dN(a,l);break;case"single-quoted-scalar":s=Ls.Scalar.QUOTE_SINGLE,c=fN(a,l);break;case"double-quoted-scalar":s=Ls.Scalar.QUOTE_DOUBLE,c=hN(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=lN.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function dN(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}`),af(e)}function fN(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),af(e.slice(1,-1)).replace(/''/g,"'")}function af(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=r+n.length+e.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function xb({offset:t,props:e},i,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[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=t+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<e.length;++f){let h=e[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 Cb(t){let e=t.split(/\n( *)/),i=e[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}tp.resolveBlockScalar=Pb});var Nc=C(rp=>{"use strict";var yc=ie(),Rb=Oi();function Ab(t,e,i){let{offset:r,type:n,source:a,end:o}=t,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=yc.Scalar.PLAIN,c=_b(a,l);break;case"single-quoted-scalar":s=yc.Scalar.QUOTE_SINGLE,c=Tb(a,l);break;case"double-quoted-scalar":s=yc.Scalar.QUOTE_DOUBLE,c=Ib(a,l);break;default:return i(t,"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,e,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function _b(t,e){let i="";switch(t[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 ${t[0]}`;break}case"@":case"`":{i=`reserved character ${t[0]}`;break}}return i&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),ip(t)}function Tb(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),ip(t.slice(1,-1)).replace(/''/g,"'")}function ip(t){let e,i;try{e=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 hN(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}=pN(e,n);i+=a,n=o}else if(r==="\\"){let a=e[++n],o=mN[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+=vN(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 pN(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{e=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(t);if(!r)return t;let n=r[1],a=" ",o=e.lastIndex;for(i.lastIndex=o;r=i.exec(t);)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(t),n+a+(r?.[1]??"")}function Ib(t,e){let i="";for(let r=1;r<t.length-1;++r){let n=t[r];if(!(n==="\r"&&t[r+1]===`
92
+ `))if(n===`
93
+ `){let{fold:a,offset:o}=jb(t,r);i+=a,r=o}else if(n==="\\"){let a=t[++r],o=$b[a];if(o)i+=o;else if(a===`
94
+ `)for(a=t[r+1];a===" "||a===" ";)a=t[++r+1];else if(a==="\r"&&t[r+1]===`
95
+ `)for(a=t[++r+1];a===" "||a===" ";)a=t[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=Ob(t,r+1,s,e),r+=s}else{let s=t.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=t[r+1];for(;o===" "||o===" ";)o=t[++r+1];o!==`
96
+ `&&!(o==="\r"&&t[r+2]===`
97
+ `)&&(i+=r>a?t.slice(a,r+1):n)}else i+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),i}function jb(t,e){let i="",r=t[e+1];for(;(r===" "||r===" "||r===`
98
+ `||r==="\r")&&!(r==="\r"&&t[e+2]!==`
99
+ `);)r===`
100
100
  `&&(i+=`
101
- `),t+=1,n=e[t+1];return i||(i=" "),{fold:i,offset:t}}var mN={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function vN(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}}of.resolveFlowScalar=uN});var lf=R(cf=>{"use strict";var Mt=D(),sf=te(),gN=Ds(),wN=Ms();function yN(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?gN.resolveBlockScalar(e,t,n):wN.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[Mt.SCALAR]:c?l=NN(e.schema,r,c,i,n):t.type==="scalar"?l=bN(e,r,t,n):l=e.schema[Mt.SCALAR];let u;try{let d=l.resolve(r,f=>n(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Mt.isScalar(d)?d:new sf.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(i??t,"TAG_RESOLVE_FAILED",f),u=new sf.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 NN(e,t,i,n,r){if(i==="!")return e[Mt.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[Mt.SCALAR])}function bN({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[Mt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[Mt.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}cf.composeScalar=yN});var df=R(uf=>{"use strict";function kN(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}uf.emptyScalarPosition=kN});var pf=R(qs=>{"use strict";var SN=Ui(),EN=D(),CN=nf(),ff=lf(),RN=wi(),PN=df(),AN={composeNode:hf,composeEmptyNode:Bs};function hf(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=xN(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=ff.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=CN.composeCollection(AN,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=Bs(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&&(!EN.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 Bs(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:PN.emptyScalarPosition(t,i,n),indent:-1,source:""},d=ff.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 xN({options:e},{offset:t,source:i,end:n},r){let a=new SN.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=RN.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}qs.composeEmptyNode=Bs;qs.composeNode=hf});var gf=R(vf=>{"use strict";var TN=dn(),mf=pf(),IN=wi(),_N=mn();function jN(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new TN.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=_N.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?mf.composeNode(l,r,u,o):mf.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=IN.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}vf.composeDoc=jN});var Ws=R(Nf=>{"use strict";var ON=or("process"),$N=xo(),HN=dn(),vn=pn(),wf=D(),FN=gf(),DN=wi();function gn(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 yf(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
+ `),e+=1,r=t[e+1];return i||(i=" "),{fold:i,offset:e}}var $b={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ob(t,e,i,r){let n=t.substr(e,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,i+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}rp.resolveFlowScalar=Ab});var op=C(ap=>{"use strict";var di=L(),np=ie(),Hb=wc(),Db=Nc();function Bb(t,e,i,r){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Hb.resolveBlockScalar(t,e,r):Db.resolveFlowScalar(e,t.options.strict,r),c=i?t.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[di.SCALAR]:c?l=Fb(t.schema,n,c,i,r):e.type==="scalar"?l=Lb(t,n,e,r):l=t.schema[di.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??e,"TAG_RESOLVE_FAILED",f),t.options);u=di.isScalar(d)?d:new np.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??e,"TAG_RESOLVE_FAILED",f),u=new np.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 Fb(t,e,i,r,n){if(i==="!")return t[di.SCALAR];let a=[];for(let s of t.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(e))return s;let o=t.knownTags[i];return o&&!o.collection?(t.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"),t[di.SCALAR])}function Lb({atKey:t,directives:e,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(r))||i[di.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[di.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}ap.composeScalar=Bb});var cp=C(sp=>{"use strict";function Mb(t,e,i){if(e){i??(i=e.length);for(let r=i-1;r>=0;--r){let n=e[r];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++r];n?.type==="space";)t+=n.source.length,n=e[++r];break}}return t}sp.emptyScalarPosition=Mb});var dp=C(kc=>{"use strict";var qb=Nr(),Vb=L(),Wb=ep(),lp=op(),zb=Oi(),Jb=cp(),Gb={composeNode:up,composeEmptyNode:bc};function up(t,e,i,r){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(e.type){case"alias":l=Ub(t,e,r),(s||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=lp.composeScalar(t,e,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Wb.composeCollection(Gb,t,e,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=bc(t,e.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!Vb.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function bc(t,e,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Jb.emptyScalarPosition(e,i,r),indent:-1,source:""},d=lp.composeScalar(t,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 Ub({options:t},{offset:e,source:i,end:r},n){let a=new qb.Alias(i.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+i.length,s=zb.resolveEnd(r,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}kc.composeEmptyNode=bc;kc.composeNode=up});var hp=C(pp=>{"use strict";var Kb=Hr(),fp=dp(),Yb=Oi(),Xb=Lr();function Qb(t,e,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new Kb.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?fp.composeNode(l,n,u,o):fp.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Yb.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}pp.composeDoc=Qb});var Ec=C(gp=>{"use strict";var Zb=On("process"),ek=ls(),tk=Hr(),Mr=Fr(),mp=L(),ik=hp(),rk=Oi();function qr(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:i}=t;return[e,e+(typeof i=="string"?i.length:1)]}function vp(t){let e="",i=!1,r=!1;for(let n=0;n<t.length;++n){let a=t[n];switch(a[0]){case"#":e+=(e===""?"":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 Vs=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=gn(i);a?this.warnings.push(new vn.YAMLWarning(o,n,r)):this.errors.push(new vn.YAMLParseError(o,n,r))},this.directives=new $N.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=yf(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(wf.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];wf.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:yf(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(ON.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,n,r)=>{let a=gn(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=FN.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 vn.YAMLParseError(gn(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 vn.YAMLParseError(gn(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=DN.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 vn.YAMLParseError(gn(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 HN.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}}};Nf.Composer=Vs});var Sf=R(Xr=>{"use strict";var LN=Ds(),MN=Ms(),BN=pn(),bf=Zi();function qN(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 BN.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return MN.resolveFlowScalar(e,t,n);case"block-scalar":return LN.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function VN(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=bf.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"%":t[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:e,afterEmptyLine:r}}var Sc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=qr(i);a?this.warnings.push(new Mr.YAMLWarning(o,r,n)):this.errors.push(new Mr.YAMLParseError(o,r,n))},this.directives=new ek.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,i){let{comment:r,afterEmptyLine:n}=vp(this.prelude);if(r){let a=e.contents;if(i)e.comment=e.comment?`${e.comment}
106
+ ${r}`:r;else if(n||e.directives.docStart||!a)e.commentBefore=r;else if(mp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];mp.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)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:vp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,i=!1,r=-1){for(let n of e)yield*this.next(n);yield*this.end(i,r)}*next(e){switch(Zb.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(i,r,n)=>{let a=qr(e);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let i=ik.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(e,"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(e.source);break;case"error":{let i=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Mr.YAMLParseError(qr(e),"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 Mr.YAMLParseError(qr(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=rk.resolveEnd(e.end,e.offset+e.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 Mr.YAMLParseError(qr(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),n=new tk.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}}};gp.Composer=Sc});var Np=C(Ca=>{"use strict";var nk=wc(),ak=Nc(),ok=Fr(),wp=Pr();function sk(t,e=!0,i){if(t){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 ok.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ak.resolveFlowScalar(t,e,r);case"block-scalar":return nk.resolveBlockScalar({options:{strict:e}},t,r)}}return null}function ck(t,e){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=wp.stringifyString({type:o,value:t},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.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 kf(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 WN(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=bf.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">":zN(e,c);break;case'"':zs(e,c,"double-quoted-scalar");break;case"'":zs(e,c,"single-quoted-scalar");break;default:zs(e,c,"scalar")}}function zN(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}];kf(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 kf(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 zs(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})}}}Xr.createScalarToken=VN;Xr.resolveAsScalar=qN;Xr.setScalarValue=WN});var Cf=R(Ef=>{"use strict";var JN=e=>"type"in e?Zr(e):Qr(e);function Zr(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Zr(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Qr(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Qr(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Qr(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 Qr({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=Zr(t)),i)for(let a of i)r+=a.source;return n&&(r+=Zr(n)),r}Ef.stringify=JN});var xf=R(Af=>{"use strict";var Js=Symbol("break visit"),GN=Symbol("skip children"),Rf=Symbol("remove item");function Bt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Pf(Object.freeze([]),e,t)}Bt.BREAK=Js;Bt.SKIP=GN;Bt.REMOVE=Rf;Bt.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};Bt.parentCollection=(e,t)=>{let i=Bt.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===Js)return Js;s===Rf&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}Af.visit=Bt});var ea=R(he=>{"use strict";var Gs=Sf(),UN=Cf(),KN=xf(),Us="\uFEFF",Ks="",Ys="",Xs="",YN=e=>!!e&&"items"in e,XN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function QN(e){switch(e){case Us:return"<BOM>";case Ks:return"<DOC>";case Ys:return"<FLOW_END>";case Xs:return"<SCALAR>";default:return JSON.stringify(e)}}function ZN(e){switch(e){case Us:return"byte-order-mark";case Ks:return"doc-mode";case Ys:return"flow-error-end";case Xs: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 yp(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 lk(t,e,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in t?t.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=wp.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":uk(t,c);break;case'"':Pc(t,c,"double-quoted-scalar");break;case"'":Pc(t,c,"single-quoted-scalar");break;default:Pc(t,c,"scalar")}}function uk(t,e){let i=e.indexOf(`
114
+ `),r=e.substring(0,i),n=e.substring(i+1)+`
115
+ `;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,t.source=n}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];yp(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function yp(t,e){if(e)for(let i of e)switch(i.type){case"space":case"comment":t.push(i);break;case"newline":return t.push(i),!0}return!1}function Pc(t,e,i){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=i,t.source=e;break;case"block-scalar":{let r=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let a of r)a.offset+=n;delete t.props,Object.assign(t,{type:i,source:e,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
117
+ `};delete t.items,Object.assign(t,{type:i,source:e,end:[n]});break}default:{let r="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:i,indent:r,source:e,end:n})}}}Ca.createScalarToken=ck;Ca.resolveAsScalar=sk;Ca.setScalarValue=lk});var kp=C(bp=>{"use strict";var dk=t=>"type"in t?Aa(t):Ra(t);function Aa(t){switch(t.type){case"block-scalar":{let e="";for(let i of t.props)e+=Aa(i);return e+t.source}case"block-map":case"block-seq":{let e="";for(let i of t.items)e+=Ra(i);return e}case"flow-collection":{let e=t.start.source;for(let i of t.items)e+=Ra(i);for(let i of t.end)e+=i.source;return e}case"document":{let e=Ra(t);if(t.end)for(let i of t.end)e+=i.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let i of t.end)e+=i.source;return e}}}function Ra({start:t,key:e,sep:i,value:r}){let n="";for(let a of t)n+=a.source;if(e&&(n+=Aa(e)),i)for(let a of i)n+=a.source;return r&&(n+=Aa(r)),n}bp.stringify=dk});var xp=C(Pp=>{"use strict";var xc=Symbol("break visit"),fk=Symbol("skip children"),Sp=Symbol("remove item");function fi(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Ep(Object.freeze([]),t,e)}fi.BREAK=xc;fi.SKIP=fk;fi.REMOVE=Sp;fi.itemAtPath=(t,e)=>{let i=t;for(let[r,n]of e){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};fi.parentCollection=(t,e)=>{let i=fi.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Ep(t,e,i){let r=i(e,t);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Ep(Object.freeze(t.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===xc)return xc;s===Sp&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}Pp.visit=fi});var _a=C(Ne=>{"use strict";var Cc=Np(),pk=kp(),hk=xp(),Rc="\uFEFF",Ac="",_c="",Tc="",mk=t=>!!t&&"items"in t,vk=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function gk(t){switch(t){case Rc:return"<BOM>";case Ac:return"<DOC>";case _c:return"<FLOW_END>";case Tc:return"<SCALAR>";default:return JSON.stringify(t)}}function wk(t){switch(t){case Rc:return"byte-order-mark";case Ac:return"doc-mode";case _c:return"flow-error-end";case Tc: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}he.createScalarToken=Gs.createScalarToken;he.resolveAsScalar=Gs.resolveAsScalar;he.setScalarValue=Gs.setScalarValue;he.stringify=UN.stringify;he.visit=KN.visit;he.BOM=Us;he.DOCUMENT=Ks;he.FLOW_END=Ys;he.SCALAR=Xs;he.isCollection=YN;he.isScalar=XN;he.prettyToken=QN;he.tokenType=ZN});var ec=R(If=>{"use strict";var wn=ea();function Te(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var Tf=new Set("0123456789ABCDEFabcdef"),eb=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ta=new Set(",[]{}"),tb=new Set(` ,[]{}
121
- \r `),Qs=e=>!e||tb.has(e),Zs=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===`
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==="...")&&Te(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]===wn.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 wn.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==="...")&&Te(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&&!Te(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===":")&&Te(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(Qs),"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("..."))&&Te(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield wn.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(Qs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Te(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=>Te(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`
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 wn.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(Te(a)||t&&ta.has(a))break;i=n}else if(Te(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&&ta.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&&ta.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield wn.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(Qs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(Te(n)||i&&ta.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(;!Te(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(eb.has(i))i=this.buffer[++t];else if(i==="%"&&Tf.has(this.buffer[t+1])&&Tf.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
- `?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)}};If.Lexer=Zs});var ic=R(_f=>{"use strict";var tc=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}}}};_f.LineCounter=tc});var rc=R(Ff=>{"use strict";var ib=or("process"),jf=ea(),nb=ec();function wt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Of(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 Hf(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 ia(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 yi(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 na(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 $f(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!wt(t.start,"explicit-key-ind")&&!wt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Hf(t.value)?t.value.end?na(t.value.end,t.sep):t.value.end=t.sep:na(t.start,t.sep),delete t.sep)}var nc=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 nb.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,ib.env.LOG_TOKENS&&console.log("|",jf.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=jf.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"&&$f(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&&Of(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":{Of(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=ia(this.peek(2)),n=yi(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(`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Ne.createScalarToken=Cc.createScalarToken;Ne.resolveAsScalar=Cc.resolveAsScalar;Ne.setScalarValue=Cc.setScalarValue;Ne.stringify=pk.stringify;Ne.visit=hk.visit;Ne.BOM=Rc;Ne.DOCUMENT=Ac;Ne.FLOW_END=_c;Ne.SCALAR=Tc;Ne.isCollection=mk;Ne.isScalar=vk;Ne.prettyToken=gk;Ne.tokenType=wk});var $c=C(Rp=>{"use strict";var Vr=_a();function Ve(t){switch(t){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Cp=new Set("0123456789ABCDEFabcdef"),yk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ta=new Set(",[]{}"),Nk=new Set(` ,[]{}
121
+ \r `),Ic=t=>!t||Nk.has(t),jc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,i=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,i=this.buffer[e];for(;i===" "||i===" ";)i=this.buffer[++e];return!i||i==="#"||i===`
122
+ `?!0:i==="\r"?this.buffer[e+1]===`
123
+ `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let i=this.buffer[e];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+e];if(i==="\r"){let n=this.buffer[r+e+1];if(n===`
124
+ `||!n&&!this.atEnd)return e+r+1}return i===`
125
+ `||r>=this.indentNext||!i&&!this.atEnd?e+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Ve(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Vr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let i=e.length,r=e.indexOf("#");for(;r!==-1;){let a=e[r-1];if(a===" "||a===" "){i=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let a=e[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-i),yield*this.pushNewline(),"stream"}return yield Vr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&Ve(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&&!Ve(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ve(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 e=this.getLine();if(e===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(e[i]){case"#":yield*this.pushCount(e.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(Ic),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,i,r=-1;do e=yield*this.pushNewline(),e>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(e+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("..."))&&Ve(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Vr.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(Ic),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ve(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),i=this.buffer.indexOf(e,this.pos+1);if(e==="'")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 e=this.pos;for(;;){let i=this.buffer[++e];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=>Ve(i)||i==="#")}*parseBlockScalar(){let e=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
+ `:e=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(!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(e+1);if(a===-1)break;e=this.buffer.indexOf(`
131
+ `,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
132
+ `;)r=this.buffer[++n];e=n-1}else if(!this.blockScalarKeep)do{let a=e-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
+ `&&a>=this.pos&&a+1+i>s)e=a;else break}while(!0);return yield Vr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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(Ve(a)||e&&Ta.has(a))break;i=r}else if(Ve(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
134
+ `?(r+=1,n=`
135
+ `,a=this.buffer[r+1]):i=r),a==="#"||e&&Ta.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&Ta.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Vr.SCALAR,yield*this.pushToIndex(i+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,i){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ic),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ve(r)||i&&Ta.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,i=this.buffer[e];for(;!Ve(i)&&i!==">";)i=this.buffer[++e];return yield*this.pushToIndex(i===">"?e+1:e,!1)}else{let e=this.pos+1,i=this.buffer[e];for(;i;)if(yk.has(i))i=this.buffer[++e];else if(i==="%"&&Cp.has(this.buffer[e+1])&&Cp.has(this.buffer[e+2]))i=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
137
+ `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||e&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(e){let i=this.pos,r=this.buffer[i];for(;!e(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Rp.Lexer=jc});var Hc=C(Ap=>{"use strict";var Oc=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<e?i=a+1:r=a}if(this.lineStarts[i]===e)return{line:i+1,col:1};if(i===0)return{line:0,col:e};let n=this.lineStarts[i-1];return{line:i,col:e-n+1}}}};Ap.LineCounter=Oc});var Bc=C($p=>{"use strict";var bk=On("process"),_p=_a(),kk=$c();function Lt(t,e){for(let i=0;i<t.length;++i)if(t[i].type===e)return!0;return!1}function Tp(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function jp(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ia(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function Hi(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function ja(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let i=0;i<e.length;++i)t.push(e[i])}function Ip(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Lt(e.start,"explicit-key-ind")&&!Lt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,jp(e.value)?e.value.end?ja(e.value.end,e.sep):e.value.end=e.sep:ja(e.start,e.sep),delete e.sep)}var Dc=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new kk.Lexer,this.onNewLine=e}*parse(e,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,i))yield*this.next(r);i||(yield*this.end())}*next(e){if(this.source=e,bk.env.LOG_TOKENS&&console.log("|",_p.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let i=_p.tokenType(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let i=e??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"&&Ip(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&&Tp(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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Tp(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let i=Ia(this.peek(2)),r=Hi(i),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let 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)){na(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(wt(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(Hf(i.key)&&!wt(i.sep,"newline")){let o=yi(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(wt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=yi(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]}):wt(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&&!wt(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)){na(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||wt(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=ia(n),a=yi(r);$f(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(e){let i=e.items[e.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):e.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)e.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){ja(n,i.start),n.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.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>e.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),e.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),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Lt(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(jp(i.key)&&!Lt(i.sep,"newline")){let o=Hi(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(Lt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Hi(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?e.items.push({start:a,key:null,sep:[this.sourceToken]}):Lt(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?(e.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(e);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Lt(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&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.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):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){ja(n,i.start),n.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||Lt(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.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(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.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?e.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?e.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":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);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===e.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=Ia(r),a=Hi(n);Ip(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let 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=ia(t),n=yi(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=ia(t),n=yi(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())}}};Ff.Parser=nc});var qf=R(Nn=>{"use strict";var Df=Ws(),rb=dn(),yn=pn(),ab=qo(),ob=D(),sb=ic(),Lf=rc();function Mf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new sb.LineCounter||null,prettyErrors:t}}function cb(e,t={}){let{lineCounter:i,prettyErrors:n}=Mf(t),r=new Lf.Parser(i?.addNewLine),a=new Df.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(yn.prettifyError(e,i)),s.warnings.forEach(yn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Bf(e,t={}){let{lineCounter:i,prettyErrors:n}=Mf(t),r=new Lf.Parser(i?.addNewLine),a=new Df.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 yn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(yn.prettifyError(e,i)),o.warnings.forEach(yn.prettifyError(e,i))),o}function lb(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Bf(e,i);if(!r)return null;if(r.warnings.forEach(a=>ab.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 ub(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 ob.isDocument(e)&&!n?e.toString(i):new rb.Document(e,n,i).toString(i)}Nn.parse=lb;Nn.parseAllDocuments=cb;Nn.parseDocument=Bf;Nn.stringify=ub});var aa=R(q=>{"use strict";var db=Ws(),fb=dn(),hb=Es(),ac=pn(),pb=Ui(),yt=D(),mb=pt(),vb=te(),gb=vt(),wb=gt(),yb=ea(),Nb=ec(),bb=ic(),kb=rc(),ra=qf(),Vf=Wi();q.Composer=db.Composer;q.Document=fb.Document;q.Schema=hb.Schema;q.YAMLError=ac.YAMLError;q.YAMLParseError=ac.YAMLParseError;q.YAMLWarning=ac.YAMLWarning;q.Alias=pb.Alias;q.isAlias=yt.isAlias;q.isCollection=yt.isCollection;q.isDocument=yt.isDocument;q.isMap=yt.isMap;q.isNode=yt.isNode;q.isPair=yt.isPair;q.isScalar=yt.isScalar;q.isSeq=yt.isSeq;q.Pair=mb.Pair;q.Scalar=vb.Scalar;q.YAMLMap=gb.YAMLMap;q.YAMLSeq=wb.YAMLSeq;q.CST=yb;q.Lexer=Nb.Lexer;q.LineCounter=bb.LineCounter;q.Parser=kb.Parser;q.parse=ra.parse;q.parseAllDocuments=ra.parseAllDocuments;q.parseDocument=ra.parseDocument;q.stringify=ra.stringify;q.visit=Vf.visit;q.visitAsync=Vf.visitAsync});import{promises as Qc}from"fs";import pp from"path";var Kc=Co(aa(),1);import{promises as sp}from"fs";import At from"path";import{createHash as Rb}from"node:crypto";import{promises as Ie}from"node:fs";import ke from"node:path";import{TextDecoder as Pb}from"node:util";import oc from"path";var Sb=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Eb=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Cb(e){return e.toLowerCase().startsWith(".env")}function ze(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Cb(n))?"environment-file":i.some(n=>Eb.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Sb.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function sc(e,t){let i=ze(t);if(i)return i;let n=oc.resolve(e.projectRoot,...t.split("/")),r=oc.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===oc.resolve(e.configFile)?"native-runtime":null}function Nt(e){return e!==0&&e!==0n&&e!=="0"}function le(e,t){return Nt(e.dev)&&Nt(t.dev)&&Nt(e.ino)&&Nt(t.ino)}function B(e,t){let i=Nt(e.dev)&&Nt(t.dev);if(i&&e.dev!==t.dev)return!1;let n=Nt(e.ino)&&Nt(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var bn=1024*1024;function cc(e,t){let i=ke.relative(e,t);return i===""||!ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ke.sep}`)}function Ab(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=ze(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 xb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Tb(e,t){return B({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function oa(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return le(i,n)?B(i,n):B(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Wf(e){let t=await Ie.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ie.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ib(e,t){let i=ke.resolve(e),n=ke.resolve(t);if(!cc(i,n))throw new Error("Native artifact path is outside its root");let r=[await Wf(i)],a=i;for(let o of ke.relative(i,n).split(ke.sep).filter(Boolean)){a=ke.join(a,o);let s=await Wf(a);if(!cc(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function zf(e){for(let t of e){let i=await Ie.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Tb(t,i)||await Ie.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ue(e){let t=Ab(e.ref),i=xb(e.maxBytes??bn),n=ke.resolve(e.root,...t.split("/")),r=await Ib(e.root,ke.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Ie.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 Ie.realpath(n);if(!cc(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ie.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ie.lstat(n),Ie.realpath(n)]);if(await zf(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!oa(a,c)||!oa(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(),Ie.lstat(n),Ie.realpath(n)]);if(await zf(r),!h.isFile()||h.isSymbolicLink()||g!==o||!oa(c,m)||!oa(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),N;try{N=new Pb("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:Rb("sha256").update(S).digest("hex"),text:N}}finally{await s.close()}}var uc=Co(aa(),1);import sa from"path";var Sn=64*1024,ca=1024,la=64,dc=5,_b=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],pe={include:["**/*"],exclude:[..._b],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function jb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||sa.posix.isAbsolute(i)||sa.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 qt(e){let t=jb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Gf(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 fc(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||sa.posix.isAbsolute(n)||sa.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 kn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Uf(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 ua(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>ca)throw new Error(`${t} exceeds ${ca} 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>la)throw new Error(`${t} contains more than ${la} 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=>ua(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function lc(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 Ob(e){if(e===void 0)return{...pe,include:[...pe.include],exclude:[...pe.exclude]};let t=kn(e,"native.snapshot");return{include:Jf(t.include,"native.snapshot.include",pe.include),exclude:Jf(t.exclude,"native.snapshot.exclude",pe.exclude),max_files:lc(t.max_files,pe.max_files,"native.snapshot.max_files"),max_total_bytes:lc(t.max_total_bytes,pe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:lc(t.max_duration_ms,pe.max_duration_ms,"native.snapshot.max_duration_ms")}}function $b(e){if(e===void 0)return;let t=kn(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=kn(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:qt(n),toArtifactRoot:qt(r),stage:a,...o?{cleanup:o}:{}}}function Hb(e,t={}){let i=kn(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??dc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=$b(i.pending_root_move);return{artifact_root:qt(n),language:Uf(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:Ob(i.snapshot),...s?{pending_root_move:s}:{}}}function Fb(e){let t=kn(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:Gf(t.artifact_layout),language:Uf(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function Db(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Lb(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 En(e,t={}){let i=(0,uc.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=Db(r.ambient_resume),o=r.native===void 0?void 0:Hb(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:Fb(r.classic),c=Lb(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function da(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:qt(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:dc,snapshot:{...pe,include:[...pe.include],exclude:[...pe.exclude]}}}}import{createHash as Bb}from"crypto";import{promises as pa}from"fs";import bt from"path";import{constants as fa,promises as Vt}from"fs";var _e=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function hc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Kf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Cn(e){return{dev:e.dev,ino:e.ino,birthtime:hc(e)}}function ha(e,t){let i=Cn(e),n=Cn(t);return le(i,n)?B(i,n):B(i,n)&&hc(e)===hc(t)&&Kf(e)===Kf(t)&&e.size===t.size}async function Wt(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 Vt.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new _e("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new _e("too-large",`${n} exceeds ${t} bytes`);let o=await Vt.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Cn(a)});let s=process.platform==="win32"?fa.O_RDONLY:fa.O_RDONLY|fa.O_NOFOLLOW|fa.O_NONBLOCK,c;try{c=await Vt.open(e,s)}catch(l){throw l.code==="ELOOP"?new _e("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Vt.lstat(e,{bigint:r}),Vt.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ha(a,l)||!ha(a,u))throw new _e("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Cn(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 _e("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}),Vt.lstat(e,{bigint:r}),Vt.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||S!==o||!ha(a,h)||!ha(a,g))throw new _e("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:Cn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function Mb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function pc(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}async function Yf(e,t){let i=bt.resolve(e),n=await pa.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return pa.realpath(i)}async function Xf(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=bt.join(r,i[a]);let o;try{o=await pa.lstat(r)}catch(u){if(Mb(u))return{exists:!1,kind:"missing"};throw u}let s=bt.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 pa.realpath(r);if(!pc(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 Rn(e,t,i){let n=fc(t,i.label),r=bt.resolve(e),a=await Yf(r,i.label),o=n.split("/"),s=bt.resolve(r,...o);if(!pc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Xf(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function zt(e,t,i,n){let r=await Rn(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 Yf(r.projectRoot,n.label);return Wt(r.target,i,{...n,verify:async(o,s)=>{if(!pc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Xf(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var Pn=".comet/config.yaml";function qb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function mc(e,t={}){return(await ma(e,t)).document}async function Vb(e){try{return(await zt(e,Pn,Sn,{label:Pn})).bytes}catch(t){if(qb(t))return null;throw t}}function Wb(e){return e?{exists:!0,sha256:Bb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ma(e,t={}){let i=await Vb(e);return{document:i?En(i.toString("utf8"),t):null,identity:Wb(i)}}var vT=16*1024;import{promises as Ni}from"fs";import J from"path";import Kb from"os";var ga=".comet/config.yaml";async function wc(e){try{return await Ni.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Yb(e){try{let t=await Ni.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(e,t){let i=J.relative(e,t);return i===""||!J.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${J.sep}`)}async function xn(e){let t=[],i=e;for(;!await wc(i);){let r=J.dirname(i);if(r===i)break;t.push(J.basename(i)),i=r}let n=await Ni.realpath(i);return J.resolve(n,...t.reverse())}async function Zf(e){try{return(await Ni.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wa(e){let t=J.resolve(e);try{(await Ni.stat(t)).isDirectory()||(t=J.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=J.resolve(Kb.homedir());for(;;){if(!(t===n&&i!==n)){let o=J.join(t,...ga.split("/")),s=t===i||await Yb(o);if(await wc(o)&&s)return t}if(await wc(J.join(t,".git")))return t;let a=J.dirname(t);if(a===t)return i;t=a}}function ya(e){return qt(e)}async function Xb(e,t){let i=ya(t),n=J.resolve(e,...i.split("/")),r=await Ni.realpath(e),a=await xn(n);if(!An(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function yc(e,t){let i=ya(t),n=await Xb(e,i),r=J.join(n,"comet");if(await Zf(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([xn(n),xn(r)]);if(!An(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:J.resolve(e),configFile:J.join(e,...ga.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:J.join(r,"specs"),changesDir:J.join(r,"changes"),archiveDir:J.join(r,"archive"),runtimeDir:J.join(r,"runtime"),locksDir:J.join(r,"runtime","locks"),transactionsDir:J.join(r,"runtime","transactions")}}function W(e,t){return An(J.resolve(e),J.resolve(t))}async function V(e,t){let i=J.resolve(e),n=J.resolve(t);if(!An(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Zf(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([xn(i),xn(n)]);if(!An(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var bc=pe;var Na=ua;function Zb(e="docs",t="en"){return da(e,t)}async function kt(e){let t=(await mc(e))?.config??null;return t?.native?t:null}async function ba(e){let t=await kt(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function eh(e){let t=await wa(e.startPath),i=await kt(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${ga} 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?ya(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??Zb(n??"docs"),a=await yc(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as Pk}from"fs";import Ak from"path";import{AsyncLocalStorage as ek}from"async_hooks";import{randomUUID as nh}from"crypto";import{promises as Se}from"fs";import rh from"os";import de from"path";var th=16*1024,ah=".coordinator",tk=5e3,ih=new ek,ka=new Map;function ik(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function nk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function oh(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function kc(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return le(i,n)?B(i,n):B(i,n)&&e.size===t.size}function Sc(e,t){return kc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Xe(e){let t,i;try{let n=await Wt(e,th,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof _e?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${th} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:nk(JSON.parse(t.toString("utf8")),e),identity:oh(i)}}async function rk(e){return(await Xe(e))?.owner??null}function sh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==rh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=uk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function ak(e,t){try{await Se.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Se.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Ec(e,t){let i=await Xe(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Sc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Se.mkdir(t,{recursive:!0});let n=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${nh()}.removed`);try{await Se.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await Xe(n);if(!r||r.owner.id!==e.owner.id||!kc(r.identity,e.identity))throw await ak(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Se.rm(n,{force:!0}),"removed"}function ch(e){return{id:nh(),pid:process.pid,hostname:rh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function lh(e,t){let i;try{i=await Se.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await rk(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
143
- `,"utf8"),await i.sync(),oh(await i.stat({bigint:!0}))}finally{await i.close()}}async function ok(e,t){let i=await V(e.nativeRoot,e.locksDir);await Se.mkdir(i,{recursive:!0});let n=await V(e.nativeRoot,de.join(i,ah));await Se.mkdir(n,{recursive:!0});let r=ch(t),a=de.join(n,`.${r.id}.tmp`),o=de.join(n,`${r.id}.claim`);try{let s=await lh(a,r);await Se.rename(a,o);let c=await Xe(o);if(!c||!kc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await Se.rm(a,{force:!0})}}async function sk(e){let t=de.dirname(e.file),i=!1,n=de.basename(e.file);for(let r of await Se.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=de.join(t,r.name);if(de.resolve(a)!==de.resolve(e.file))try{let o=await Xe(a),s=sh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ec(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function uh(e){let t=await Xe(e.file);if(t){if(t.owner.id!==e.owner.id||!Sc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Ec(t,de.dirname(e.file))}}async function ck(e,t){let i=Date.now()+tk;for(;;){let n=await ok(e,t);if(!await sk(n))return n;if(await uh(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function lk(e){let t=ka.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return ka.set(e,r),await t,()=>{i(),ka.get(e)===r&&ka.delete(e)}}async function dh(e,t,i){let n=de.resolve(e.locksDir),r=ih.getStore();if(r?.has(n))return i();let a=await lk(n);try{let o=await ck(e,t),s=new Map(r??[]);return s.set(n,o),await ih.run(s,async()=>{try{return await i()}finally{await uh(o)}})}finally{a()}}async function Sa(e,t,i){return dh(e,`acquire ${t}`,async()=>{let n=await V(e.nativeRoot,e.locksDir);await Se.mkdir(n,{recursive:!0});let r=await V(e.nativeRoot,de.join(n,ik(t))),a=ch(i),o=await lh(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Ea(e){await Xe(e.file)&&await dh(e,`release ${de.basename(e.file)}`,async()=>{let t=await Xe(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Sc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=de.join(e.locksDir,ah);await Ec(t,i)})}function uk(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function fh(e){return sh(await Xe(e))}import Ze from"path";import{TextDecoder as gk}from"util";import{createHash as dk}from"node:crypto";import{constants as Ca,promises as we}from"node:fs";import je from"node:path";import{TextDecoder as fk}from"node:util";function Pa(e,t){let i=je.relative(e,t);return i===""||!je.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${je.sep}`)}function hh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function hk(e,t){return B({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function pk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ra(e,t){return B({...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 Cc(e,t){let i=await we.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await we.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function ph(e,t,i){let n=je.resolve(e),r=je.resolve(t);if(!Pa(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Cc(n,i)],o=n;for(let s of je.relative(n,r).split(je.sep).filter(Boolean)){await Qe(a,i),o=je.join(o,s);let c=await Cc(o,i);if(!Pa(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Qe(a,i),a}async function Qe(e,t){for(let i of e){let n=await we.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!hk(i,n)||await we.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function mk(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 Je(e){let t=hh(e.maxBytes),i=je.resolve(e.file),n=await ph(e.root,je.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Cc(je.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Qe(n,e.label);let a=await we.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=pk(a),s=await we.realpath(i);if(!Pa(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Pa(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ca.O_RDONLY:Ca.O_RDONLY|Ca.O_NOFOLLOW|Ca.O_NONBLOCK,l=await we.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([we.lstat(i),we.realpath(i)]);if(await Qe(n,e.label),await Qe(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Ra(o,u)||!Ra(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await mk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),we.lstat(i),we.realpath(i)]);if(await Qe(n,e.label),await Qe(r,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!Ra(o,m)||!Ra(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:dk("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function mh(e){let t=await Je(e),i;try{i=new fk("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 Tn(e){let t=await ph(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await we.readdir(e.directory,{withFileTypes:!0});else{let n=hh(e.maxEntries);i=[];let r=await we.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 Qe(t,e.label),{entries:i,verify:()=>Qe(t,e.label)}}var wk=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),yk=new Set(["id","type","source","target","staged","backup"]),Nk=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),bk=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var wh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var kk=256*1024,oI=1024*1024,sI=16*1024;var cI=64*1024*1024;var Sk=new gk("utf-8",{fatal:!0});function xa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ta(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 yh(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Rc(e,t){if(typeof e!="string"||e.length===0||Ze.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Aa(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function vh(e,t){if(Rc(e,t),e.includes("\\")||e!==Ze.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function Ek(e,t){let i=xa(e,`transaction operations[${t}]`);if(Ta(i,yk,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Rc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Rc(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Nh(e){let t=xa(e,"Native Archive transaction journal");if(Ta(t,Nk,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!wh.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!yh(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Aa(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=xa(s,`Archive transaction operations[${c}]`);if(Ta(l,bk,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);vh(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&vh(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Aa(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Aa(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Aa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Ck(e){let t=xa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Nh(t);if(Ta(t,wk,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!wh.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Ze.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Ze.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!yh(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(Ek),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Rk(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Ze.join(e.transactionsDir,t)}function bh(e,t){let i=Rk(e,t);return{directory:i,journal:Ze.join(i,"transaction.json"),events:Ze.join(i,"events.jsonl"),staged:Ze.join(i,"staged"),backups:Ze.join(i,"backups")}}async function Pc(e,t){let i=bh(e,t);return await Promise.all(Object.values(i).map(n=>V(e.nativeRoot,n))),i}async function Ac(e,t,i={}){let n=await Pc(e,t),r=await Je({root:e.nativeRoot,file:n.journal,maxBytes:kk,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Sk.decode(r.bytes)),o=Ck(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function xk(e,t){let i;try{i=await Pk.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let r=await Ac(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function Tk(e,t){let i=Date.now()+5e3,n=Ak.join(e.locksDir,"root-move.lock");for(;;)try{return await Sa(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await fh(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function et(e,t,i,n){let r=await Tk(e,t);try{if(await ba(e.projectRoot),await xk(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Ea(r)}}import{createHash as $a}from"crypto";import{spawn as Ih}from"node:child_process";import{promises as X}from"fs";import $ from"path";import{createHash as kh}from"crypto";import{createReadStream as Ik}from"fs";async function xc(e){let t=kh("sha256");for await(let i of Ik(e))t.update(i);return t.digest("hex")}function U(e){return kh("sha256").update(e).digest("hex")}var Ia={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},$c=1e3,_k=8*1024*1024,jk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ok=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$k=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Hk=new Set(["schema","include","exclude","hash"]),Fk=new Set(["provider","gitSelection","physicalSelection","projection"]),Dk=new Set(["provider","selection"]),Lk=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Mk=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Bk=new Set(["schema","status","before","after"]),qk=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Vk=new Set(["path","hash","size","type","gitObjectId"]),Wk=new Set(["path","size","type","reason"]),zk=new Set(["ref","hash","count"]),Jk=new Set(["change-created","legacy-migration","explicit"]),Gk=new Set(["file","directory","other"]),Uk=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"]),Ha=/^[a-f0-9]{64}$/u,_h=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Kk=new Set(["EACCES","EPERM"]),Ci=64*1024,jc=64*1024,Yk=6e4,Xk=1e3,Qk=2,Hc={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Zk={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function jh(e){let t=e.deadlineMs??Yk;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 Oe(e){return Math.max(0,e.deadlineAt-Date.now())}function _(e){return Oe(e)>=1}function Tc(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 Si(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function eS(e){let t={...Zk,...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 tS(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&&$.win32.isAbsolute(n)?$.win32.resolve(n):"C:\\Windows",a=$.win32.join(r,"System32","taskkill.exe");if(!$.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=Ih(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),Xk),u.unref()}catch{d(!1)}});for(let s=0;s<Qk;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 Fc(e,t,i,n){let r=Oe(e);if(r<1)throw Tc();let a=e.gitProcess,o=Ih(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=tS(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?Tc(m.error):Tc()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Oh(e){let t={...Hc,...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 _a(e,t,i,n=jc){let{child:r,completion:a}=Fc(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>=Ci)return;let m=Ci-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 Ic(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function _n(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}=Fc(e,t,i,n.stdin!==void 0),c=[],l=$a("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>=Ci)return;let C=Ci-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 ja(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 iS(e,t,i){if(i.length===0)return new Set;let n=await _n(e,t,["check-ignore","--no-index","-z","--stdin"],{...Hc,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=ja(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function nS(e,t,i){let{child:n,completion:r}=Fc(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>=Ci)return;let d=Ci-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 Ei(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||$.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||$.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function rS(e,t){return e.map(i=>{let n=Ei(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function aS(e){let t=$.resolve(e);for(;;){try{return await X.lstat($.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=$.dirname(t);if(i===t)return!1;t=i}}async function $h(e,t,i,n={}){let r=$.resolve(t.projectRoot),a=$.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let p=$.relative(r,$.resolve(f)).replaceAll("\\","/"),m=Ei(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 _n(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await _n(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await _n(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Hh(e){return{stageBefore:Ic(e.stagedBefore),combined:Ic(e.combined),stageAfter:Ic(e.stagedAfter)}}async function Fh(e,t,i=Hc,n={}){let r=$.resolve(t.projectRoot);if(!await aS(r))return null;let a;try{a=await _a(e,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw Si(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 $h(e,t,i,n)}catch(N){throw Si(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=ja(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=Ei(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(ja),h=rS(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:Hh(o)}}function Et(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Sh(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function oS(e,t){return!Et(e.stageBefore,e.stageAfter)||!Et(e.stageAfter,t.stageBefore)||!Et(e.combined,t.combined)||!Et(t.stageBefore,t.stageAfter)}async function Dh(e,t,i,n,r){let a;try{a=await $h(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw Si(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=Hh(a),c=Sh(o)||Sh(s),l=oS(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
144
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var sS=(1n<<256n)-1n;function cS(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Eh(e){let t=$.resolve(e.paths.projectRoot),i=$.resolve(e.paths.nativeRoot),n=$.resolve(e.paths.configFile),r=$.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=()=>Oe(e.execution)>=1?!0:(f=!0,m=!0,!1),g=k=>{let b=Buffer.from(`${k.type}\0${k.path}`,"utf8"),C=$a("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")}`)&sS,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=$.join(k,E.name),G=uS(t,I);if(I===n||I===r||Ct(i,I)||e.denylist.some(K=>Ct(K,I))||ze(G)!==null)continue;if(!h())break;let M;try{M=await X.lstat(I)}catch(K){if(!h())break;if(!ne(K)&&!ie(K))throw K;if(p=!0,g({path:G,type:"other"}),o.push({path:G,size:null,type:"file",reason:ne(K)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(G),m||!h())break;continue}if(!h())break;let z=cS(M);if(z==="directory"){if(pS(e.policy,G))continue;if(!h())break;let K;try{K=await X.realpath(I)}catch(Be){if(!h())break;if(!ne(Be)&&!ie(Be))throw Be;if(p=!0,g({path:G,type:z}),o.push({path:G,size:null,type:"directory",reason:ne(Be)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(G),m||!h())break;continue}if(!h())break;if(!W(e.physicalProjectRoot,K)||Ct(e.physicalNativeRoot,K))continue;if(g({path:G,type:z}),await e.hooks?.afterNode?.(G),!h()||(await S(I),m))break;continue}if(g({path:G,type:z}),await e.hooks?.afterNode?.(G),!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
145
- ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):U(`comet.native.physical-selection.v1
146
- ${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 Lh(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 lS(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!Lh(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 Mh(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Ch(e,t){let n=(await _a(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!_h.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return U(`gitlink:${n}`)}async function Rh(e,t){let i=await Ch(e,t),n=await nS(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await Ch(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function In(e,t){if(ze(t)!==null)return!1;let i=$.resolve(e.projectRoot,...t.split("/"));return!Ct($.resolve(e.nativeRoot),i)}function uS(e,t){return $.relative(e,t).split($.sep).join("/")}function dS(e,t){return t.map(i=>$.resolve(e,...i.split(/[\\/]/u)))}function Ct(e,t){let i=$.resolve(e),n=$.resolve(t);return n===i||W(i,n)}function ne(e){return Kk.has(e.code??"")}function ie(e){return e.code==="ENOENT"}function Dc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
147
- `)}function fS(e,t){return U(`comet.native.snapshot-policy.v1
148
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function _c(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 hS(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Ph(e){let t=Na(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?hS(r):void 0;if(a&&!a())return!1;let o=_c(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=_c(i,c,a),o===null||o.size===0)return!1}return _c(i,o,a)?.has(i.length)??!1}}function Bh(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Na(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Na(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=fS(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(Ph),excludeMatchers:i.map(Ph),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 pS(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Ah(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 jn(e,t,i){let n=JSON.stringify(i);return U(`${e}
149
- ${Buffer.byteLength(t)}:${t}
150
- ${Buffer.byteLength(n)}:${n}`)}function Oc(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Oa(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Oc(i))return e.splice(t,1),i}return null}function St(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return le(i,n)?B(i,n):B(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mS(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=$a("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()||!St(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()||!St(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 Ee(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ce(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function ki(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ge(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function qh(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=$.posix.normalize(e);if(i!==e||$.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function vS(e,t){let i=Ee(e,`Native snapshot entry ${t}`);Ce(i,Vk,`Native snapshot entry ${t}`);let n=qh(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Ha.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:Ge(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!_h.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function gS(e,t){let i=Ee(e,`Native snapshot omission ${t}`);if(Ce(i,Wk,`Native snapshot omission ${t}`),!Gk.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!Uk.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:qh(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:Ge(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function wS(e){let t=Ee(e,"Native snapshot omission overflow");if(Ce(t,zk,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ha.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 bi(e,t){let i=Ee(e,t);if(Ce(i,Mk,t),typeof i.hash!="string"||!Ha.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=Ge(i.recordCount,`${t} recordCount`),r=Ge(i.storedRecordCount,`${t} storedRecordCount`),a=Ge(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 xh(e){let t=Ee(e,"Native Git selection evidence");if(Ce(t,Lk,"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=bi(t.stageBefore,"Native Git selection stageBefore"),n=bi(t.combined,"Native Git selection combined"),r=bi(t.stageAfter,"Native Git selection stageAfter"),a=bi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=bi(t.finalCombined,"Native Git selection finalCombined"),s=bi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Et(i,r)||!Et(r,a)||!Et(n,o)||!Et(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 Th(e,t){let i=Ee(e,t);if(Ce(i,qk,t),typeof i.hash!="string"||!Ha.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=Ge(i.visitedNodeCount,`${t} visitedNodeCount`),r=Ge(i.recordCount,`${t} recordCount`),a=Ge(i.storedRecordCount,`${t} storedRecordCount`),o=Ge(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 yS(e){let t=Ee(e,"Native physical selection evidence");if(Ce(t,Bk,"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=Th(t.before,"Native physical selection before"),n=Th(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Lh(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 Gt(e){let t=Ee(e,"Native content snapshot manifest");if(Ce(t,Ok,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Jk.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=Ee(t.capture,"Native content snapshot capture");if(Ce(y,Fk,"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:xh(y.gitSelection),v=y.physicalSelection===void 0?void 0:yS(y.physicalSelection),E=null;if(y.projection!==void 0){let I=Ee(y.projection,"Native content snapshot projection");if(Ce(I,Dk,"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:xh(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=Ee(t.limits,"Native content snapshot limits");Ce(n,$k,"Native content snapshot limits");let r={maxFiles:ki(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ki(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ki(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ki(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:ki(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=Ee(t.policy,"Native snapshot policy");if(Ce(y,Hk,"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=Bh({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(vS),s=t.omitted.map(gS),c=Ge(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:wS(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>$c||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(Dc(C)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return C}async function Vh(e,t,i={}){let n=Gt(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=$.resolve(e.projectRoot),a=jh(i),o=Oh(i.gitSelectionLimits),s=await Fh(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(Mh(s).filter(v=>In(e,v))),l=[...s.gitlinks].filter(v=>c.has(v)),u=[...s.nestedRepositories].filter(v=>In(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 iS(a,r,m),g=n.entries.filter(v=>!f(v.path)&&!p(v.path)&&In(e,v.path)&&(c.has(v.path)||!h.has(v.path)));await Dh(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)||!In(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=jn(b,"git-selection",{source:"git-selection",...s.overflow}));let C=v=>{k+=1,b=jn(b,"omission",v)};for(;N.length>$c;){let v=Oa(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(;Dc(w)>n.limits.maxManifestBytes;){let v=Oa(N);if(v===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");C(v),w=y()}return Gt(w)}function NS(e,t){if(!jk.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=$.join(e.changesDir,t);if(!W(e.changesDir,i))throw new Error("Native change path escaped");return $.join(i,"runtime","baseline-manifest.json")}async function Wh(e,t={}){let i={maxFiles:t.limits?.maxFiles??Ia.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Ia.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Ia.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Ia.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=Bh(t.policy),r=jh({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Oh(t.gitSelectionLimits),o=eS(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=$.resolve(e.projectRoot),c=await X.realpath(s),l=$.resolve(e.nativeRoot),u=await X.realpath(l),d=$.resolve(e.configFile),f=$.join(s,".comet","current-change.json"),p=dS(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=jn(b,"omission",x)},E=x=>{if(N+=1,h.length<$c){h.push(x);return}if(Oc(x)){let A=Oa(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=jn(b,"git-selection",{source:"git-selection",...x})},G=x=>{k+=1,b=jn(b,"manifest-entry",{reason:"manifest-size",entry:x})},M=async(x,A)=>{m.push(x),C+=x.size,g.set(x.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},z=(x,A)=>{let T=m.findIndex(Y=>Y.path===x);if(T<0)return;let[O]=m.splice(T,1);C-=O.size,g.delete(x),E(A)},K=async(x,A,T,O)=>{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)||!W(c,Y)||Ct(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 L,j,Q;try{if(L=await mS(Y,T.size,T,r),L.status==="budget-exhausted"||!_(r))return;if(L.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(L.bytes!==T.size||Q!==Y||!St(T,L.finalStat)||!St(L.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 M({path:A,hash:L.hash,size:j.size,type:"file",...O===void 0?{}:{gitObjectId:O}},{kind:"file",target:x,realTarget:Y,stat:j})}},Be=async(x,A,T)=>{if(!_(r))return;let O,Y,L;try{if(O=await X.readlink(x,{encoding:"buffer"}),!_(r)||(L=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(!L.isSymbolicLink()||!St(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!O.equals(Y)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=O.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=$a("sha256").update("symlink\0").update(O).digest("hex");_(r)&&await M({path:A,hash:Q,size:j,type:"file"},{kind:"symlink",target:x,rawTarget:O,stat:L})},qe=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;z(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()||!St(A.stat,Q)||Q.size!==A.stat.size||Q.mtimeMs!==A.stat.mtimeMs||Q.ctimeMs!==A.stat.ctimeMs)&&z(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;z(x,{path:x,size:null,type:"other",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!St(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Q))&&z(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,O;try{if(T=await X.realpath(A.target),!_(r))return;O=await X.lstat(A.target)}catch{if(!_(r))return;z(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&O.isDirectory()&&!O.isSymbolicLink()&&St(A.stat,O)&&W(c,T)&&!Ct(u,T))){z(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!_(r))return;L=await Rh(r,T)}catch(j){if(Si(j))throw j;z(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;L.dirty?z(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&z(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"})}}},ve=await Fh(r,e,a,t.gitSelectionHooks);if(ve===null){let x=await Eh({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let O of x.records){if(O.type!=="file"&&O.type!=="symlink"||g.has(O.path))continue;if(Oe(r)<1)break;if(!Ah(n,O.path,r))continue;if(Oe(r)<1)break;let Y=$.resolve(s,...O.path.split("/")),L;try{L=await X.lstat(Y)}catch(j){if(!_(r))break;if(!ne(j)&&!ie(j))throw j;E({path:O.path,size:null,type:"file",reason:ie(j)?"changed-during-read":"unreadable"});continue}if(Oe(r)<1)break;if(O.type==="symlink"&&L.isSymbolicLink()){if(await Be(Y,O.path,L),Oe(r)<1)break;continue}if(O.type!=="file"||!L.isFile()||L.isSymbolicLink()){E({path:O.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await K(Y,O.path,L),Oe(r)<1)break}Oe(r)>=1&&await qe();let A=await Eh({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=lS(x.evidence,A.evidence);w=T.evidence;for(let O of[...x.omissions,...A.omissions,...T.omissions])h.some(Y=>Y.path===O.path&&Y.reason===O.reason)||E(O)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,T=!1;if(x){let P=Gt(x);for(let Z of P.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);T=A.size>0}let O=new Set,Y=!0;try{let P=await _n(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=ja(Z),ce=ee.indexOf(" "),oe=ce<0?null:Ei(ee.slice(ce+1));if(ce!==1||oe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&O.add(oe)}}catch(P){if(Si(P))throw P;T=!1,Y=!1,A.clear()}let L=new Set;try{let P=await _a(r,s,["ls-files","--modified","-z"],jc);for(let Z of P.toString("utf8").split("\0")){let ee=Ei(Z);ee!==null&&L.add(ee)}}catch{T=!1,Y=!1,A.clear()}let j=new Set,Q=new Set;for(let P of Mh(ve)){if(g.has(P)||!In(e,P))continue;if(Oe(r)<1)break;if(!Ah(n,P,r))continue;if(Oe(r)<1)break;let Z=$.resolve(s,...P.split("/"));if(Z===d||Z===f||p.some(ge=>Ct(ge,Z)))continue;if(ve.gitlinks.has(P)){if(m.length>=i.maxFiles){E({path:P,size:0,type:"file",reason:"file-count"});continue}let ge,ar;try{[ge,ar]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ar.isSymbolicLink()||!ar.isDirectory()||!W(c,ge)||Ct(u,ge)){E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ci=await Rh(r,ge);if(ci.dirty){E({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await M({path:P,hash:ci.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:ge,stat:ar,hash:ci.hash})}catch(ci){if(Si(ci))throw ci;E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await X.lstat(Z)}catch(ge){if(ie(ge)&&ve.tracked.has(P)){S.set(P,Z);continue}if(!ne(ge)&&!ie(ge))throw ge;E({path:P,size:null,type:"file",reason:ie(ge)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await Be(Z,P,ee);continue}if(!ee.isFile()){ve.nestedRepositories.has(P)||E({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let ce=ve.trackedObjectIds.get(P),oe=ce?A.get(P):void 0;if(T&&oe?.gitObjectId!==void 0&&oe.gitObjectId===ce&&!O.has(P)&&!L.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 Zl=Y&&!O.has(P)&&!L.has(P)?ce:void 0;await K(Z,P,ee,Zl),Zl!==void 0&&Q.add(P)}if(await qe(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Dh(r,e,a,ve,t.gitSelectionHooks?.outputChunkBytes),j.size>0||T&&Q.size>0){let P=await _a(r,s,["ls-files","--modified","-z"],jc),Z=new Set;for(let ee of P.toString("utf8").split("\0")){let ce=Ei(ee);ce!==null&&Z.add(ce)}for(let ee of j){if(!Z.has(ee))continue;let ce=m.find(oe=>oe.path===ee);z(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 ve.omissions)E(P);ve.overflow&&I(ve.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let Vv=ve===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...ve.evidence?{gitSelection:ve.evidence}:{}},Ql=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Vv,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}}:{}}),Eo=Ql();for(;Dc(Eo)>i.maxManifestBytes;){if(h.filter(A=>!Oc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let O=Oa(h);if(O===null)break;v(O)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))N+=1,G(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Eo=Ql()}return Eo}async function Lc(e,t,i={}){let r=(await kt(e.projectRoot))?.native.snapshot??bc;return Wh(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 Fa(e,t){let i=NS(e,t);await V(e.nativeRoot,i);try{let n=await mh({root:e.nativeRoot,file:i,maxBytes:_k,label:"Native baseline snapshot manifest"});return Gt(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as FS}from"crypto";import Vc from"path";var Re=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 Da,promises as $e}from"node:fs";import He from"node:path";import{TextDecoder as _S}from"node:util";import AS from"path";var RS=Co(aa(),1);var zh=(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 On(e,t){let i=$n(e,t);if(AS.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 xS(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 Jh(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=On(e,"pending_ref"),o=On(e,"trajectory_ref"),s=On(e,"context_ref"),c=On(e,"artifacts_ref"),l=On(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:zh(e,"current_step"),iteration:u,pending:zh(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:xS(e)}}var O_=256*1024;var TS=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function IS(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 Mc(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=>!TS.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 IS(t)}var Ri={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 Ma(e,t){let i=He.relative(e,t);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function jS(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function La(e,t){return B({...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 OS(e,t){return B({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ba(e,t,i){let n=Re[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=He.resolve(e),a=He.resolve(r,...n.split("/"));if(!Ma(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Gh(e){let t=await $e.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await $e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function $S(e,t){let i=He.resolve(e),n=He.resolve(t);if(!Ma(i,n))throw new Error("Native Run path is outside its change");let r=[await Gh(i)],a=i;for(let o of He.relative(i,n).split(He.sep).filter(Boolean)){a=He.join(a,o);let s;try{s=await Gh(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ma(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function Uh(e){for(let t of e){let i=await $e.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!OS(t,i)||await $e.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function HS(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 qa(e,t,i,n,r){let a=await $S(e,He.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await $e.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=jS(o),c=await $e.realpath(t);if(!Ma(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Da.O_RDONLY:Da.O_RDONLY|Da.O_NOFOLLOW|Da.O_NONBLOCK,u;try{u=await $e.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),$e.lstat(t),$e.realpath(t)]);if(await Uh(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!La(s,d)||!La(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await HS(u,i,n);await r?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([u.stat(),$e.lstat(t),$e.realpath(t)]);if(await Uh(a),!g.isFile()||g.isSymbolicLink()||S!==c||!La(s,h)||!La(s,g))throw new Error(`${n} changed while reading`);let N;try{N=new _S("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 Kh(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Bc(e){return Mc(e)}async function Pi(e,t){let i=Ba(e,"stateRef"),n=await qa(e,i,Ri.runStateBytes,"Native Run state",t);return n?Mc(Kh(n.text,"Native Run state")):null}async function Ut(e,t,i){let n=Ba(e,"trajectoryRef",t),r=await qa(e,n,Ri.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>Ri.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ri.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 Yh(e,t,i){return(await qa(e,Ba(e,"trajectoryRef",t),Ri.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Va(e,t,i){let n=await qa(e,Ba(e,"checkpointRef",t),Ri.checkpointBytes,"Native Run checkpoint",i);return n?Kh(n.text,"Native Run checkpoint"):null}var DS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function qc(e){return FS("sha256").update(e).digest("hex")}function LS(e,t){if(!DS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Vc.join(e.changesDir,t);if(!W(e.changesDir,i))throw new Error("Native change path escaped");return Vc.join(i,"runtime","trajectory.jsonl")}function MS(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 BS(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 qS(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=MS(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(`
151
- `)])}catch(d){if(!BS(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:qc(t),targetHash:qc(l),tailHash:qc(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function VS(e,t){let i=LS(e,t);await V(e.nativeRoot,i);let n=Vc.join(e.changesDir,t),r=await Yh(n,Re.trajectoryRef);return r===null?{status:"clean",file:i}:qS(i,Buffer.from(r))}async function Xh(e,t){let i=await VS(e,t);return"inspection"in i?i.inspection:i}import{createHash as JS}from"node:crypto";import{promises as za}from"node:fs";import Rt from"node:path";import{execFileSync as WS}from"child_process";import Wa from"path";function Wc(e,t){return WS("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function zS(e,t){let i=Wa.normalize(e),n=Wa.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Qh(e){try{let t=Wa.resolve(Wc(e,["rev-parse","--show-toplevel"])),n=Wc(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?Wa.resolve(n.slice(9)):t,a=null;try{a=Wc(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!zS(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var Hn=/^[a-f0-9]{64}$/u,GS=16*1024,zc=process.platform,US=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Ai(e){return US.has(e)}function ip(e,t){let i=Rt.relative(e,t);return Rt.isAbsolute(i)||i===".."||i.startsWith(`..${Rt.sep}`)?null:i.replaceAll("\\","/")||"."}function np(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function rp(e,t){if(e.length===0||np(e)||e.includes("\\")||Rt.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=Rt.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 JS("sha256").update(`${e}
152
- ${t}`).digest("hex")}async function Zh(e,t){let i=await za.realpath(t),n=await za.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=zc==="win32"?Rt.normalize(i).toLowerCase():i;return Jc(e,`${r}
153
- ${n.dev}
154
- ${n.ino}
155
- ${n.birthtimeMs}`)}async function ep(e,t){let i=await za.realpath(t),n=await za.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=zc==="win32"?Rt.normalize(i).toLowerCase():i;return Jc(e,r)}function KS(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 tp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||np(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function ap(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(tp(e.changeBranch,"Native workspace change branch"),tp(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 Ja(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"||!Hn.test(String(t.projectRootId))||!Hn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");KS(t.capturedAt),rp(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&&!Hn.test(String(t.projectRootPathId))||a&&!Hn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Hn.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(ap(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 YS(e,t){return Rt.join(e.changesDir,t,"runtime","workspace.json")}function XS(e,t){let i=ip(e.nativeRoot,YS(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return rp(i,"Native workspace file ref")}async function QS(e,t){try{let i=await ue({root:e.nativeRoot,ref:XS(e,t),maxBytes:GS});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ZS(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=ip(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([Zh("comet.native.workspace-project-root.v2",e.paths.projectRoot),Zh("comet.native.workspace-native-root.v2",e.paths.nativeRoot),ep("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),ep("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&&ap(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}
156
- ${n}
157
- ${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return Ja(c),c}async function Pt(e,t){let i=await QS(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Ja(i),i)}async function Ga(e){Ja(e.identity);let t=await ZS({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")),zc==="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 Ua(e){if(Ja(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 Ga(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Qh(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 op(e,t){let i=await Pt(e,t);if(i===null)return null;let n=await Ua({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var Kt="comet.native.v3",Yt="comet.native.v2",Xt="comet.native.v1",xi="comet.native.transition.v3",Ti="comet.native.transition.v2",Fn="comet.native.transition.v1";var cp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],tE=new Set(cp),lp=new Set([...cp,"minimum_runtime_version","revision"]),iE=new Set([...lp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),nE=new Set(["capability","operation","source","base_hash"]),rE=new Set(["shape","build","verify","archive"]),aE=new Set(["implicit","confirmed"]),oE=new Set(["pending","pass","fail"]),Zt="comet-state.yaml",Uc=/^[a-f0-9]{64}$/u,up=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sE=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ka=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"},Qt=class extends Error{constructor(i,n){super(i!==Kt||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"},Ya=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"},Xa=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"},Hj=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
158
- `);function Ln(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function dp(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 Mn(e){if(!up.test(e))throw new Error(`Invalid Native change name: ${e}`)}function cE(e){if(!up.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function fp(e,t){if(e.length===0||At.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function lE(e,t){let i=Ln(e,`spec_changes[${t}]`);if(dp(i,nE,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(cE(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"&&fp(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"||!Uc.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"||!Uc.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 uE(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 Yc(e,t){if(dp(e,t,Zt),typeof e.name!="string")throw new Error("Native change name is required");if(Mn(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"||!rE.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&&!aE.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(lE),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"||!oE.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"&&fp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!uE(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 Bn(e){let t=Ln(e,Zt);if(t.schema!==Xt)throw new Error(`Expected ${Xt}`);return{schema:Xt,...Yc(t,tE)}}function Dn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gc(e,t,i){if(e===null)return null;let n=typeof e=="string"?sE.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 dE(e){if(e==null)return null;if(typeof e!="string"||!Uc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function fE(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 qn(e){let t=Ln(e,Zt);if(t.schema!==Yt)throw new Error(`Expected ${Yt}`);if(Dn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Yt} minimum_runtime_version must be 2`);return{schema:Yt,minimum_runtime_version:2,revision:Dn(t.revision,"Native v2 revision"),...Yc(t,lp)}}function ei(e){let t=Ln(e,Zt);if(t.schema!==Kt){if(t.schema===Xt||t.schema===Yt){let o=t.schema===Xt?Bn(t):qn(t);throw new Ka(o.name,o.schema)}throw new Qt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Dn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Qt(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Dn(t.revision,"Native revision"),r=Yc(t,iE),a=dE(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Kt,minimum_runtime_version:3,revision:n,verification_protocol:fE(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Gc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Gc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Gc(t.partial_allowance,"Native partial_allowance","allowances")}}function hE(e){let t=Ln(e,Zt);if(t.schema===Xt){let r=Bn(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Kt}`}}if(t.schema===Yt){let r=qn(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Kt}`}}if(t.schema!==Kt){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 Qt(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=Dn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Qt(t.schema,i).message};let n=ei(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function F(e,t){Mn(t);let i=At.join(e.changesDir,t);if(!W(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Za(e,t){let i=At.join(F(e,t),"runtime","schema-migration.json");await V(e.nativeRoot,i);try{return await sp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function hp(e,t){let i=At.join(F(e,t),"runtime","checkpoint-journal.json");await V(e.nativeRoot,i);try{return await sp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var pE=256*1024;async function mE(e,t=At.dirname(e)){let i=At.relative(t,e).split(At.sep).join("/"),n=await ue({root:t,ref:i,maxBytes:pE}),r=(0,Kc.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 Xc(e,t){let i=At.join(F(e,t),Zt);await V(e.nativeRoot,i);let n=hE(await mE(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Za(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 vE(e,n.state),n)}async function vE(e,t){if(await Fa(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function tt(e,t){let i=await Xc(e,t);if(i.status==="migration-required")throw new Ka(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Qt(i.schema,i.minimumRuntimeVersion);return await op(e,t),i.state}var mp=["Outcome","Scope","Non-goals","Acceptance examples"],gE=[...mp,"Constraints and invariants","Decisions","Open questions","Verification expectations"],wE=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],vp={maxFileBytes:bn};function gp(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
159
- `).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 yE(e,t){let i=pp.resolve(e,...t.split(/[\\/]/u));if(!W(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Qc.realpath(e),r=await Qc.realpath(i);if(!W(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Qc.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Vn(e){return{valid:e.length===0,findings:e}}async function Zc(e,t){let i=[],n;try{n=(await ue({root:e,ref:t,maxBytes:vp.maxFileBytes})).text}catch(o){return Vn([{code:"brief-missing",message:o.message,path:t}])}let r=gp(n);for(let o of gE)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of mp)(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}),Vn(i)}async function el(e,t){let i=[],n;try{n=(await ue({root:e,ref:t,maxBytes:vp.maxFileBytes})).text}catch(a){return Vn([{code:"verification-missing",message:a.message,path:t}])}let r=gp(n);for(let a of wE)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 Vn(i)}function eo(e,t){return pp.join(e.specsDir,t,"spec.md")}async function wp(e,t){let i=[],n=F(e,t.name);for(let r of t.spec_changes){let a=eo(e,r.capability),o=null;try{await V(e.nativeRoot,a),o=await xc(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 yE(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Vn(i)}import yp from"node:path";import{createHash as NE}from"crypto";function Fe(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function bE(e,t){t.has(e)&&Fe("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)||Fe("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&Fe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Fe("symbol properties are not supported"),`[${e.map(n=>tl(n,t)).join(",")}]`}finally{t.delete(e)}}function kE(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Fe("only plain objects are supported"),t.has(e)&&Fe("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Fe("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))&&Fe("accessor properties are not supported"),`${JSON.stringify(o)}:${tl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function tl(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)||Fe("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?bE(e,t):kE(e,t);case"bigint":case"function":case"symbol":case"undefined":return Fe(`${typeof e} values are not supported`)}return Fe("unsupported value type")}function Wn(e){return tl(e,new Set)}function H(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 NE("sha256").update(`${e}
160
- ${Wn(t)}`).digest("hex")}var SE="comet.native.acceptance.v1",EE=/^acceptance-[a-f0-9]{64}$/u,CE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),RE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,PE=/^[a-f0-9]{64}$/u,AE=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function xE(e,t){return e<t?-1:e>t?1:0}var it=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),zn=Object.freeze({maxCriteria:1024}),Np="<!-- comet-native:acceptance-evidence:start -->",bp="<!-- comet-native:acceptance-evidence:end -->";function kp(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 Sp(e,t){let i=t.toString(36),n=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function TE(e){if(!PE.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=AE.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]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function IE(e,t){let i=kp(e.text,it.maxTextBytes),n=e.context.slice(0,it.maxContextItems).map(r=>kp(r,it.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 Cp(e){let t=TE({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(xE),r=n.slice(0,it.maxFailedCheckIds),a=e.criteria.slice(t,t+it.maxItems);for(let c of a){let l=[...i,IE(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?Sp(e.acceptanceHash,u):null,limits:{...it}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>it.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?Sp(e.acceptanceHash,o):null,limits:{...it}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>it.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function rl(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 il(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 Ep(e){return e.includes("-->")||e.includes("--!>")}function*Ii(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
142
+ `,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Ia(e),r=Hi(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=Ia(e),r=Hi(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};$p.Parser=Dc});var Fp=C(zr=>{"use strict";var Op=Ec(),Sk=Hr(),Wr=Fr(),Ek=ks(),Pk=L(),xk=Hc(),Hp=Bc();function Dp(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new xk.LineCounter||null,prettyErrors:e}}function Ck(t,e={}){let{lineCounter:i,prettyErrors:r}=Dp(e),n=new Hp.Parser(i?.addNewLine),a=new Op.Composer(e),o=Array.from(a.compose(n.parse(t)));if(r&&i)for(let s of o)s.errors.forEach(Wr.prettifyError(t,i)),s.warnings.forEach(Wr.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Bp(t,e={}){let{lineCounter:i,prettyErrors:r}=Dp(e),n=new Hp.Parser(i?.addNewLine),a=new Op.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Wr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Wr.prettifyError(t,i)),o.warnings.forEach(Wr.prettifyError(t,i))),o}function Rk(t,e,i){let r;typeof e=="function"?r=e:i===void 0&&e&&typeof e=="object"&&(i=e);let n=Bp(t,i);if(!n)return null;if(n.warnings.forEach(a=>Ek.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 Ak(t,e,i){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:i===void 0&&e&&(i=e),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(t===void 0){let{keepUndefined:n}=i??e??{};if(!n)return}return Pk.isDocument(t)&&!r?t.toString(i):new Sk.Document(t,r,i).toString(i)}zr.parse=Rk;zr.parseAllDocuments=Ck;zr.parseDocument=Bp;zr.stringify=Ak});var Jr=C(z=>{"use strict";var _k=Ec(),Tk=Hr(),Ik=nc(),Fc=Fr(),jk=Nr(),Mt=L(),$k=Ht(),Ok=ie(),Hk=Bt(),Dk=Ft(),Bk=_a(),Fk=$c(),Lk=Hc(),Mk=Bc(),$a=Fp(),Lp=vr();z.Composer=_k.Composer;z.Document=Tk.Document;z.Schema=Ik.Schema;z.YAMLError=Fc.YAMLError;z.YAMLParseError=Fc.YAMLParseError;z.YAMLWarning=Fc.YAMLWarning;z.Alias=jk.Alias;z.isAlias=Mt.isAlias;z.isCollection=Mt.isCollection;z.isDocument=Mt.isDocument;z.isMap=Mt.isMap;z.isNode=Mt.isNode;z.isPair=Mt.isPair;z.isScalar=Mt.isScalar;z.isSeq=Mt.isSeq;z.Pair=$k.Pair;z.Scalar=Ok.Scalar;z.YAMLMap=Hk.YAMLMap;z.YAMLSeq=Dk.YAMLSeq;z.CST=Bk;z.Lexer=Fk.Lexer;z.LineCounter=Lk.LineCounter;z.Parser=Mk.Parser;z.parse=$a.parse;z.parseAllDocuments=$a.parseAllDocuments;z.parseDocument=$a.parseDocument;z.stringify=$a.stringify;z.visit=Lp.visit;z.visitAsync=Lp.visitAsync});import{promises as zl}from"fs";import Hm from"path";var ql=Hn(Jr(),1);import{promises as Am}from"fs";import Xt from"path";import{execFileSync as qk}from"child_process";import Ha from"path";function Oa(t,e){return qk("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Vk(t,e){let i=Ha.normalize(t),r=Ha.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function We(t){try{let e=Ha.resolve(Oa(t,["rev-parse","--show-toplevel"])),r=Oa(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Ha.resolve(r.slice(9)):e,a=null;try{a=Oa(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Vk(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Lc(t,e){try{let i=Oa(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as Gk}from"node:crypto";import{promises as ze}from"node:fs";import je from"node:path";import{TextDecoder as Uk}from"node:util";import Mc from"path";var Wk=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),zk=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Jk(t){return t.toLowerCase().startsWith(".env")}function at(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>Jk(r))?"environment-file":i.some(r=>zk.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>Wk.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function qc(t,e){let i=at(e);if(i)return i;let r=Mc.resolve(t.projectRoot,...e.split("/")),n=Mc.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),a=e.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Mc.resolve(t.configFile)?"native-runtime":null}function qt(t){return t!==0&&t!==0n&&t!=="0"}function ge(t,e){return qt(t.dev)&&qt(e.dev)&&qt(t.ino)&&qt(e.ino)}function q(t,e){let i=qt(t.dev)&&qt(e.dev);if(i&&t.dev!==e.dev)return!1;let r=qt(t.ino)&&qt(e.ino);return r&&t.ino!==e.ino?!1:i&&r?!0:t.birthtime===e.birthtime}var Gr=1024*1024;function Vc(t,e){let i=je.relative(t,e);return i===""||!je.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${je.sep}`)}function Kk(t){let e=je.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||je.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),r=at(t);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${t}`);return t}function Yk(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Xk(t,e){return q({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Da(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return ge(i,r)?q(i,r):q(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Mp(t){let e=await ze.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await ze.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Qk(t,e){let i=je.resolve(t),r=je.resolve(e);if(!Vc(i,r))throw new Error("Native artifact path is outside its root");let n=[await Mp(i)],a=i;for(let o of je.relative(i,r).split(je.sep).filter(Boolean)){a=je.join(a,o);let s=await Mp(a);if(!Vc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function qp(t){for(let e of t){let i=await ze.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Xk(e,i)||await ze.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function oe(t){let e=Kk(t.ref),i=t.maxBytes===null?null:Yk(t.maxBytes??Gr),r=je.resolve(t.root,...e.split("/")),n=await Qk(t.root,je.dirname(r));await t.hooks?.afterParentChainCaptured?.();let a=await ze.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await ze.realpath(r);if(!Vc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await ze.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),ze.lstat(r),ze.realpath(r)]);if(await qp(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Da(a,c)||!Da(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.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: ${e}`);d.push(Buffer.from(h.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),ze.lstat(r),ze.realpath(r)]);if(await qp(n),!p.isFile()||p.isSymbolicLink()||m!==o||!Da(c,v)||!Da(c,p))throw new Error(`Native artifact changed while reading: ${e}`);let b=Buffer.concat(d,f),N;try{N=new Uk("utf-8",{fatal:!0}).decode(b)}catch(P){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:P})}return{ref:e,size:f,hash:t.includeHash===!1?null:Gk("sha256").update(b).digest("hex"),text:N}}finally{await s.close()}}var zc=Hn(Jr(),1);import Ba from"path";var Kr=64*1024,Fa=1024,La=64,Jc=5,Zk=[".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/**"],eS=["**/.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"],tS=[...Zk,...eS].sort((t,e)=>t.localeCompare(e,"en"));var be={include:["**/*"],exclude:[...tS],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function iS(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Ba.posix.isAbsolute(i)||Ba.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function pi(t){let e=iS(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Wp(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Gc(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Ba.posix.isAbsolute(r)||Ba.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function Ur(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function zp(t,e,i){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Ma(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Fa)throw new Error(`${e} exceeds ${Fa} characters`);let i=0;for(let r=0;r<t.length;r+=1)t[r]==="?"?i+=1:t[r]==="*"&&(i+=1,t[r+1]==="*"&&(r+=1));if(i>La)throw new Error(`${e} contains more than ${La} wildcard tokens`);return t}function Vp(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>Ma(r,e)))].sort((r,n)=>r.localeCompare(n,"en"))}function Wc(t,e,i){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function rS(t){if(t===void 0)return{...be,include:[...be.include],exclude:[...be.exclude]};let e=Ur(t,"native.snapshot");return{include:Vp(e.include,"native.snapshot.include",be.include),exclude:Vp(e.exclude,"native.snapshot.exclude",be.exclude),max_files:Wc(e.max_files,be.max_files,"native.snapshot.max_files"),max_total_bytes:Wc(e.max_total_bytes,be.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Wc(e.max_duration_ms,be.max_duration_ms,"native.snapshot.max_duration_ms")}}function nS(t){if(t===void 0)return;let e=Ur(t,"native.pending_root_move"),i=e.id,r=e.from_artifact_root,n=e.to_artifact_root,a=e.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(e.cleanup!==void 0){let s=Ur(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:pi(r),toArtifactRoot:pi(n),stage:a,...o?{cleanup:o}:{}}}function aS(t,e={}){let i=Ur(t,"native"),r=i.artifact_root??(e.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??Jc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=nS(i.pending_root_move);return{artifact_root:pi(r),language:zp(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:rS(i.snapshot),...s?{pending_root_move:s}:{}}}function oS(t){let e=Ur(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Wp(e.artifact_layout),language:zp(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function sS(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function cS(t,e,i,r,n){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!n.allowPartialProject&&t.native!==void 0)||n.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:r,...e?{native:e}:{},...i?{classic:i}:{}}}function Yr(t,e={}){let i=(0,zc.parseDocument)(t,{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=sS(n.ambient_resume),o=n.native===void 0?void 0:aS(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=n.classic===void 0?void 0:oS(n.classic),c=cS(n,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function qa(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:pi(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Jc,snapshot:{...be,include:[...be.include],exclude:[...be.exclude]}}}}import{createHash as uS}from"crypto";import{promises as za}from"fs";import Vt from"path";import{constants as Va,promises as hi}from"fs";var Je=class extends Error{reason;constructor(e,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=e}};function Uc(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Jp(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Xr(t){return{dev:t.dev,ino:t.ino,birthtime:Uc(t)}}function Wa(t,e){let i=Xr(t),r=Xr(e);return ge(i,r)?q(i,r):q(i,r)&&Uc(t)===Uc(e)&&Jp(t)===Jp(e)&&t.size===e.size}async function mi(t,e,i={}){if(!Number.isSafeInteger(e)||e<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 hi.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Je("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Je("too-large",`${r} exceeds ${e} bytes`);let o=await hi.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Xr(a)});let s=process.platform==="win32"?Va.O_RDONLY:Va.O_RDONLY|Va.O_NOFOLLOW|Va.O_NONBLOCK,c;try{c=await hi.open(t,s)}catch(l){throw l.code==="ELOOP"?new Je("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),hi.lstat(t,{bigint:n}),hi.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Wa(a,l)||!Wa(a,u))throw new Je("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Xr(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-h,{bytesRead:P}=await c.read(v,0,Math.min(v.length,N),null);if(P===0)break;if(h+=P,h>e)throw new Je("too-large",`${r} exceeds ${e} bytes`);f.push(Buffer.from(v.subarray(0,P)))}await i.hooks?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([c.stat({bigint:n}),hi.lstat(t,{bigint:n}),hi.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||b!==o||!Wa(a,p)||!Wa(a,m))throw new Je("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Xr(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:b}}finally{await c.close()}}function lS(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Kc(t,e){let i=Vt.relative(t,e);return i===""||!Vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Vt.sep}`)}async function Gp(t,e){let i=Vt.resolve(t),r=await za.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return za.realpath(i)}async function Up(t,e,i,r){let n=t;for(let a=0;a<i.length;a++){n=Vt.join(n,i[a]);let o;try{o=await za.lstat(n)}catch(u){if(lS(u))return{exists:!1,kind:"missing"};throw u}let s=Vt.relative(t,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 za.realpath(n);if(!Kc(e,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 Di(t,e,i){let r=Gc(e,i.label),n=Vt.resolve(t),a=await Gp(n,i.label),o=r.split("/"),s=Vt.resolve(n,...o);if(!Kc(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Up(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Wt(t,e,i,r){let n=await Di(t,e,{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 Gp(n.projectRoot,r.label);return mi(n.target,i,{...r,verify:async(o,s)=>{if(!Kc(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Up(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Qr=".comet/config.yaml";function dS(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Yc(t,e={}){return(await Ja(t,e)).document}async function fS(t){try{return(await Wt(t,Qr,Kr,{label:Qr})).bytes}catch(e){if(dS(e))return null;throw e}}function pS(t){return t?{exists:!0,sha256:uS("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Ja(t,e={}){let i=await fS(t);return{document:i?Yr(i.toString("utf8"),e):null,identity:pS(i)}}var ej=16*1024;import{existsSync as Yp,promises as zt}from"fs";import V from"path";import wS from"os";var Ga=".comet/config.yaml",yS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Zc(t){try{return await zt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function NS(t){try{let e=await zt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Fi(t,e){let i=V.relative(t,e);return i===""||!V.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${V.sep}`)}async function Bi(t){let e=[],i=t;for(;!await Zc(i);){let n=V.dirname(i);if(n===i)break;e.push(V.basename(i)),i=n}let r=await zt.realpath(i);return V.resolve(r,...e.reverse())}async function el(t){try{return(await zt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ua(t){let e=V.resolve(t);try{(await zt.stat(e)).isDirectory()||(e=V.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let i=e,r=V.resolve(wS.homedir());for(;;){if(!(e===r&&i!==r)){let o=V.join(e,...Ga.split("/")),s=e===i||await NS(o);if(await Zc(o)&&s)return e}if(await Zc(V.join(e,".git")))return e;let a=V.dirname(e);if(a===e)return i;e=a}}function Ka(t){return pi(t)}async function bS(t,e){let i=Ka(e),r=V.resolve(t,...i.split("/")),n=await zt.realpath(t),a=await Bi(r);if(!Fi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Ya(t,e){let i=Ka(e),r=await bS(t,i),n=V.join(r,"comet");if(await el(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Bi(r),Bi(n)]);if(!Fi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=V.resolve(t),c=V.join(s,".comet","runtime","native");if(await el(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([zt.realpath(s),Bi(c)]);if(!Fi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:V.join(t,...Ga.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:V.join(n,"specs"),changesDir:V.join(n,"changes"),archiveDir:V.join(n,"archive"),runtimeDir:c,changesRuntimeDir:V.join(c,"changes"),locksDir:V.join(c,"locks"),transactionsDir:V.join(c,"transactions")}}function Qp(t){if(!yS.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Li(t,e){Qp(e);let i=V.join(t.changesRuntimeDir,e);if(!B(t.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Zp(t,e){Qp(e);let i=V.join(t.changesDir,e,"runtime");if(!B(t.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function G(t,e){let i=Li(t,e);if(Yp(i))return i;let r=Zp(t,e);return Yp(r)?r:i}async function Xp(t){try{let e=await zt.lstat(t);return e.isDirectory()&&!e.isSymbolicLink()?"directory":"invalid"}catch(e){if(e.code==="ENOENT")return"missing";throw e}}async function tl(t,e){let i=Li(t,e),r=Zp(t,e),[n,a]=await Promise.all([Xp(i),Xp(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 Jt(t,e){if(!e.startsWith("runtime/")||V.isAbsolute(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${e}`);let i=V.resolve(t,...e.slice(8).split("/"));if(!B(t,i))throw new Error(`Native Runtime ref escaped: ${e}`);return i}function se(t,e){let i=V.resolve(e);if(B(t.runtimeDir,i))return t.runtimeDir;if(B(t.nativeRoot,i))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function B(t,e){return Fi(V.resolve(t),V.resolve(e))}async function W(t,e){let i=V.resolve(t),r=V.resolve(e);if(!Fi(i,r))throw new Error(`Path is outside the Native root: ${e}`);if(await el(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([Bi(i),Bi(r)]);if(!Fi(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return r}var il=be;var Xa=Ma;function SS(t="docs",e="en"){return qa(t,e)}async function ot(t){let e=(await Yc(t))?.config??null;return e?.native?e:null}async function Qa(t){let e=await ot(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function eh(t){let e=await Ua(t.startPath),i=await ot(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Ga} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=t.explicitArtifactRoot?Ka(t.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??SS(r??"docs"),a=await Ya(e,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as eP}from"fs";import tP from"path";import{AsyncLocalStorage as ES}from"async_hooks";import{randomUUID as rh}from"crypto";import{promises as $e}from"fs";import nh from"os";import we from"path";var th=16*1024,ah=".coordinator",PS=5e3,ih=new ES,Za=new Map;function xS(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function CS(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${e}`);return i}function oh(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function rl(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return ge(i,r)?q(i,r):q(i,r)&&t.size===e.size}function nl(t,e){return rl(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function wt(t){let e,i;try{let r=await mi(t,th,{bigint:!0,label:"Native lock"});e=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Je?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${th} bytes: ${t}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:r}):new Error(`Native lock changed while reading: ${t}`,{cause:r}):r}return{file:t,owner:CS(JSON.parse(e.toString("utf8")),t),identity:oh(i)}}async function RS(t){return(await wt(t))?.owner??null}function sh(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==nh.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=$S(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function AS(t,e){try{await $e.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await $e.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function al(t,e){let i=await wt(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!nl(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await $e.mkdir(e,{recursive:!0});let r=we.join(e,`${we.basename(t.file)}.${t.owner.id}.${rh()}.removed`);try{await $e.rename(t.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await wt(r);if(!n||n.owner.id!==t.owner.id||!rl(n.identity,t.identity))throw await AS(r,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await $e.rm(r,{force:!0}),"removed"}function ch(t){return{id:rh(),pid:process.pid,hostname:nh.hostname(),createdAt:new Date().toISOString(),operation:t}}async function lh(t,e){let i;try{i=await $e.open(t,"wx")}catch(r){if(r.code==="EEXIST"){let n=await RS(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(e,null,2)+`
143
+ `,"utf8"),await i.sync(),oh(await i.stat({bigint:!0}))}finally{await i.close()}}async function _S(t,e){let i=await W(t.runtimeDir,t.locksDir);await $e.mkdir(i,{recursive:!0});let r=await W(t.runtimeDir,we.join(i,ah));await $e.mkdir(r,{recursive:!0});let n=ch(e),a=we.join(r,`.${n.id}.tmp`),o=we.join(r,`${n.id}.claim`);try{let s=await lh(a,n);await $e.rename(a,o);let c=await wt(o);if(!c||!rl(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await $e.rm(a,{force:!0})}}async function TS(t){let e=we.dirname(t.file),i=!1,r=we.basename(t.file);for(let n of await $e.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=we.join(e,n.name);if(we.resolve(a)!==we.resolve(t.file))try{let o=await wt(a),s=sh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await al(o,e);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function uh(t){let e=await wt(t.file);if(e){if(e.owner.id!==t.owner.id||!nl(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await al(e,we.dirname(t.file))}}async function IS(t,e){let i=Date.now()+PS;for(;;){let r=await _S(t,e);if(!await TS(r))return r;if(await uh(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function jS(t){let e=Za.get(t)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=e.then(()=>r);return Za.set(t,n),await e,()=>{i(),Za.get(t)===n&&Za.delete(t)}}async function dh(t,e,i){let r=we.resolve(t.locksDir),n=ih.getStore();if(n?.has(r))return i();let a=await jS(r);try{let o=await IS(t,e),s=new Map(n??[]);return s.set(r,o),await ih.run(s,async()=>{try{return await i()}finally{await uh(o)}})}finally{a()}}async function eo(t,e,i){return dh(t,`acquire ${e}`,async()=>{let r=await W(t.runtimeDir,t.locksDir);await $e.mkdir(r,{recursive:!0});let n=await W(t.runtimeDir,we.join(r,xS(e))),a=ch(i),o=await lh(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:r,owner:a,identity:o}})}async function to(t){await wt(t.file)&&await dh({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${we.basename(t.file)}`,async()=>{let e=await wt(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!nl(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=we.join(t.locksDir,ah);await al(e,i)})}function $S(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function fh(t){return sh(await wt(t))}import RE from"node:path";import ph from"node:path";import{createHash as OS}from"crypto";function Ge(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function HS(t,e){e.has(t)&&Ge("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let r=0;r<t.length;r+=1)Object.prototype.hasOwnProperty.call(t,r)||Ge("sparse arrays are not supported");return(i.length!==t.length||i.some((r,n)=>r!==String(n)))&&Ge("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Ge("symbol properties are not supported"),`[${t.map(r=>ol(r,e)).join(",")}]`}finally{e.delete(t)}}function DS(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Ge("only plain objects are supported"),e.has(t)&&Ge("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Ge("symbol properties are not supported"),e.add(t);try{let r=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Ge("accessor properties are not supported"),`${JSON.stringify(o)}:${ol(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function ol(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Ge("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?HS(t,e):DS(t,e);case"bigint":case"function":case"symbol":case"undefined":return Ge(`${typeof t} values are not supported`)}return Ge("unsupported value type")}function en(t){return ol(t,new Set)}function F(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return OS("sha256").update(`${t}
144
+ ${en(e)}`).digest("hex")}var BS="comet.native.acceptance.v1",FS=/^acceptance-[a-f0-9]{64}$/u,LS=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),MS=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,qS=/^[a-f0-9]{64}$/u,VS=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function WS(t,e){return t<e?-1:t>e?1:0}var yt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),tn=Object.freeze({maxCriteria:1024}),hh="<!-- comet-native:acceptance-evidence:start -->",mh="<!-- comet-native:acceptance-evidence:end -->";function vh(t,e){if(Buffer.byteLength(t,"utf8")<=e)return{value:t,truncated:!1};let i="",r=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(r+a>e)break;i+=n,r+=a}return{value:i,truncated:!0}}function gh(t,e){let i=e.toString(36),r=F("comet.native.acceptance-cursor.v1",{acceptanceHash:t,offset:e});return`native-acceptance-v1.${t}.${i}.${r}`}function zS(t){if(!qS.test(t.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(t.cursor===void 0||t.cursor===null)return 0;let e=VS.exec(t.cursor);if(!e)throw new Error("Native acceptance cursor is invalid");if(e[1]!==t.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(e[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=t.total||i.toString(36)!==e[2])throw new Error("Native acceptance cursor offset is invalid");if(e[3]!==F("comet.native.acceptance-cursor.v1",{acceptanceHash:t.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function JS(t,e){let i=vh(t.text,yt.maxTextBytes),r=t.context.slice(0,yt.maxContextItems).map(n=>vh(n,yt.maxContextItemBytes));return{id:t.id,kind:t.kind,source:t.source,context:r.map(n=>n.value),text:i.value,contextTruncated:t.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:e}}function yh(t){let e=zS({acceptanceHash:t.acceptanceHash,total:t.criteria.length,cursor:t.cursor}),i=[],r=[...new Set(t.failedCheckIds??[])].sort(WS),n=r.slice(0,yt.maxFailedCheckIds),a=t.criteria.slice(e,e+yt.maxItems);for(let c of a){let l=[...i,JS(c,t.verificationStatuses?.get(c.id)??"unverified")],u=e+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:t.acceptanceHash,total:t.criteria.length,offset:e,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<t.criteria.length?gh(t.acceptanceHash,u):null,limits:{...yt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>yt.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(t.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=e+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:t.acceptanceHash,total:t.criteria.length,offset:e,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<t.criteria.length?gh(t.acceptanceHash,o):null,limits:{...yt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>yt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function cl(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function sl(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let r=i[1][0];return e===null?{marker:r,length:i[1].length}:r===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function wh(t){return t.includes("-->")||t.includes("--!>")}function*Mi(t){let e=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
161
145
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
162
- `,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=il(l,t);else if(i)Ep(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=il(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Ep(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 _E(e){return[...Ii(e)].map(({line:t,body:i})=>({line:t,body:i}))}function nl(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function jE(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function al(e,t,i,n=[]){let r=nl(i),a=t.replaceAll("\\","/").trim(),o=n.map(nl);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-${H(SE,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function ol(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 OE(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of Ii(e)){r=s+1;let c=o?rl(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 Rp(e,t="brief.md",i=zn.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=OE(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of Ii(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 Ii(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(),ol(a.map(c=>al("brief-example",t,c.join(`
163
- `))),"Brief")}function Pp(e,t="spec.md",i=zn.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(al("spec-scenario",t,[a.title,...a.body].join(`
164
- `),a.context)),a=null}};for(let{line:s,body:c}of Ii(e)){let l=c?rl(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=nl(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(),ol(n,"Specification")}function Ap(e,t="spec.md",i=zn.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(al("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 Ii(e)){let d=u?rl(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||il(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(),ol(n,"Specification mandatory requirements")}function $E(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||jE(i)||yp.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=yp.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(!RE.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function HE(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=>!CE.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.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,n)=>{let r=HE(i,n),a=r.acceptance_id;if(typeof a!="string"||!EE.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 $E(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 Tp(e){let t=_E(e);if(t.some(({line:l,body:u})=>!u&&(l===Np||l===bp)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===Np?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===bp?[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(`
165
- `).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=FE(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function FE(e){let t=xp([...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 Ip from"node:path";var DE="comet.native.contract.v1",LE="comet.native.acceptance-set.v1",_p=/^[a-f0-9]{64}$/u,Jn={maxAcceptanceCriteria:zn.maxCriteria};function jp(e,t){let i=Ip.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})||Ip.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 H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
166
- `))}function ME(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(_p))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(_p))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=jp(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 BE(e,t){return $p(e.id,t.id)}function $p(e,t){return e<t?-1:e>t?1:0}function Hp(e){let t=jp(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(ME).sort((d,f)=>$p(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=Rp(e.briefMarkdown,t,Jn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Pp(f,d.source,Jn.maxAcceptanceCriteria-a.length)),a.push(...Ap(f,d.source,Jn.maxAcceptanceCriteria-a.length)));if(a.sort(BE),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Jn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Jn.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=H(LE,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(DE,u)}}var to={maxSpecs:64,maxFileBytes:bn,maxTotalBytes:4*1024*1024};async function _i(e){if(e.specChanges.length>to.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ue({root:e.changeDir,ref:e.briefRef,maxBytes:to.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 ue({root:e.changeDir,ref:r.source,maxBytes:to.maxFileBytes});if(i+=a.size,i>to.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:Hp({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{randomUUID as qE}from"crypto";import{promises as io}from"fs";import Dp from"path";var sl="comet.selection.v2",VE=16*1024;function cl(e){return Dp.join(e,".comet","current-change.json")}function WE(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Fp(e){return e===null||typeof e=="string"}function Lp(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(!WE(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&&!Fp(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:sl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==sl)throw new Error(`current change selection schema must be ${sl}`);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(!Fp(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 Mp(e){let t;try{let n=cl(e),{bytes:r}=await Wt(n,VE,{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",...Lp(t)}}async function Bp(e,t){let i=Lp(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let n=cl(e),r=`${n}.${qE()}.tmp`;await io.mkdir(Dp.dirname(n),{recursive:!0});try{await io.writeFile(r,`${JSON.stringify(i.selection,null,2)}
167
- `,"utf8"),await io.rename(r,n)}catch(a){throw await io.rm(r,{force:!0}),a}}var pO=16*1024;async function qp(e){let t=await Mp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Mn(t.selection.change),t.selection)}async function Vp(e,t){return et(e,`select change ${t}`,async()=>{Mn(t),await tt(e,t),await Bp(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}import zE from"path";function ll(e,t){return zE.resolve(e,...t.split(/[\\/]/u))}async function Wp(e,t){let i=[],n=F(e,t.name),r=ll(n,Re.stateRef),a;try{a=await Pi(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=ll(n,a.trajectoryRef),s=await Xh(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 Ut(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=ll(n,a.checkpointRef);try{let u=await Va(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 zC from"path";import{isDeepStrictEqual as Am}from"util";var JE=/\b(Bearer|Basic)\s+[^\s"']+/giu,GE=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,UE=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,KE=/\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,YE=/("(?:[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,XE=/(["'])((?:[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,QE=/\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 De(e){return e.replace(JE,"$1 [REDACTED]").replace(GE,"[REDACTED PRIVATE KEY]").replace(UE,"$1[REDACTED]@").replace(KE,"[REDACTED TOKEN]").replace(YE,'$1"[REDACTED]"').replace(XE,"$1$2$1$3$4[REDACTED]$4").replace(QE,"$1$2[REDACTED]")}var ji={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var ZE=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function eC(e,t){return e<t?-1:e>t?1:0}function tC(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"||!ZE.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(eC)}function ul(e=[]){return tC(e,"Native repair failed check IDs",ji.maxFailedCheckIds,!0)}function zp(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function iC(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:zp(e.failedAcceptanceIds,t.failedAcceptanceIds)&&zp(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function dl(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(iC(n,a))break;i+=1,n=a}return i}import sm from"node:path";import{createHash as Qp}from"node:crypto";import Jp from"path";var fl="comet.native.implementation-scope.v2",Zp="comet.native.content-snapshot-projection.v1",Gn="comet.native.content-snapshot-projection.v1",em="comet.native.implementation-scope.v2",nC="comet.native.unresolved-scope-id.v1",rC="comet.native.scope-detail-overflow.v1",aC="comet.native.snapshot-projection-overflow.v2",vl=/^[a-f0-9]{64}$/u,ii=1024*1024,oC=128,sC=128;function se(e,t){return e<t?-1:e>t?1:0}function hl(e){if(!vl.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cC(e,t){return e===t?0:e===null?-1:t===null?1:se(e,t)}function Tt(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=Jp.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Jp.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function tm(e,t){return e==="."?e:Tt(e,t)}function Oi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lC(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:Tt(e.path,`${t} path`),hash:e.hash,size:Oi(e.size,`${t} size`),type:"file"}}function uC(e,t){return{path:tm(e.path,`${t} path`),size:e.size===null?null:Oi(e.size,`${t} size`),type:e.type,reason:e.reason}}function dC(e,t){return se(e.path,t.path)||se(e.hash,t.hash)||e.size-t.size}function fC(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 Un(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
168
- `,"utf8")}function xt(e,t,i){let n=`${t}
169
- ${Wn(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function hC(e){if(Un(e)<=ii)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=Qp("sha256");a.update(`${aC}
170
- `),e.omissionOverflow&&xt(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,xt(a,"omission",f)},s=f=>{n+=1,r+=1,xt(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(;Un(u)>ii;){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 pl(e){let t=Gt(e),i=t.entries.map((r,a)=>lC(r,`Snapshot entry ${a}`));if(i.sort(dC),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)=>uC(r,`Snapshot omission ${a}`));return n.sort(fC),hC({schema:Zp,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 ao(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:Tt(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 oo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Gp(e){return e?{hash:e.hash,size:e.size}:null}function im(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:Gp(c),after:Gp(l)})}}function pC(e,t){return{...e,attributedTo:t.filter(i=>oo(i,e.path))}}function nt(e,t){return{id:`scope:${H(nC,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function mC(e,t){let i=t.omitted.map(n=>nt({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(nt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(nt({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 Up(e,t){return mC(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function ml(e,t){return se(e.kind,t.kind)||se(e.source,t.source)||cC(e.path,t.path)||se(e.id,t.id)}function vC(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(ml)}function gC(e){return[...new Set(e.map((t,i)=>Tt(t,`Git path ${i}`)))].sort(se)}function nm(e){if(typeof e.contractHash!="string"||!vl.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ao(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:gC(e.gitChangedPaths)}}}function wC(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return im(e,t,d=>{let f=i.some(p=>oo(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<oC){let p=pC(d,i),m=Un(p);s+m<=ii?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function rm(e,t){return nt({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 yC(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:Oi(Number(t[1]),"Scope overflow change count"),unresolved:Oi(Number(t[2]),"Scope overflow unresolved count"),unattributed:Oi(Number(t[3]),"Scope overflow unattributed count")},n=ti(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(rm(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function NC(e){let t=Qp("sha256");t.update(`${rC}
171
- `);let i=0;im(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){xt(t,"change",r);let a=0;for(let o of e.declaredArtifacts)oo(o,r.path)&&(a+=1,xt(t,"change-attribution",o));xt(t,"change-end",{attributionCount:a}),a===0&&xt(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&&xt(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function am(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=wC(e,t,r,i.gitChangedPaths),s=H(Gn,e),c=H(Gn,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let v of w.omitted){if(l.length>=sC)break;l.push(nt({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=[...Up("baseline",e),...Up("current",t),...o.totalChanges===0&&a===null?[nt({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(qe=>qe.attributedTo.length===0),E=o.totalChanges-w.length,I=o.totalUnattributed-v.length,G=u-y.detailedOmissionCount,M=I+G,z=[...v.map(qe=>nt({kind:"unattributed-change",source:"implementation-scope",path:qe.path,evidence:{after:qe.after,before:qe.before,changeKind:qe.kind}},`Changed path is not covered by a declared artifact: ${qe.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||M>0?[rm(y.overflowHash,{changes:E,unattributed:I,unresolved:M})]:[]],K=vC(z),Be=y.includeGitAdvisory?f():void 0;return{schema:fl,contractHash:n,baselineProjectionRef:hl(s),baselineProjectionHash:s,currentProjectionRef:hl(c),currentProjectionHash:c,complete:K.length===0,declaredArtifacts:r,changes:w,unattributed:v,unresolvedScopes:K,noCodeReason:a,...Be?{gitAdvisory:Be}:{}}},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(Un({...y,scopeHash:S})<=ii)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?NC({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):S,b=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:g,overflowHash:k}),C={...b,scopeHash:H(em,b)};if(Un(C)>ii)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return C}function gl(e){let t=pl(e.baseline),i=pl(e.current),n=nm(e);return{authority:n,baseline:t,current:i,scope:am(t,i,n)}}var bC=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function rt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function at(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 ti(e,t){if(typeof e!="string"||!vl.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Kp(e,t,i){let n=hl(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function ro(e,t){let i=rt(e,"Native snapshot projection");if(at(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Zp)throw new Error("Native snapshot projection schema is invalid");let n=Gt({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=pl(n);if(H(Gn,i)!==H(Gn,r))throw new Error("Native snapshot projection is not canonical");let a=H(Gn,r);if(t!==void 0&&ti(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function wl(e,t){let i=rt(e,`Declared artifact ${t}`);if(at(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Tt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Yp(e,t){if(e===null)return null;let i=rt(e,t);return at(i,["hash","size"],[],t),{hash:ti(i.hash,`${t} hash`),size:Oi(i.size,`${t} size`)}}function Xp(e,t){let i=rt(e,`Implementation change ${t}`);if(at(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(wl),r=ao(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:Tt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function kC(e,t){let i=rt(e,`Unresolved scope ${t}`);at(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"?tm(i.path,`Unresolved scope ${t} path`):Tt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function no(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)=>Tt(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 so(e){let t=rt(e,"Native implementation scope"),i=[...bC].filter(w=>w!=="gitAdvisory");if(at(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==fl)throw new Error("Native implementation scope schema is invalid");let n=ti(t.contractHash,"Implementation scope contractHash"),r=ti(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Kp(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=ti(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Kp(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(wl);if(JSON.stringify(c)!==JSON.stringify(ao(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Xp),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=>oo(v,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Xp),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(kC),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:yC(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=>nt({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?[nt({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(ml))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(ml))||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=rt(t.gitAdvisory,"Implementation scope Git advisory");if(at(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=no(w.changedPaths,"Git changed paths"),E=no(w.pathsPresentInSnapshotChanges,"Git present paths"),I=no(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),G=[...E,...I].sort(se),M=new Set(l.map(z=>z.path));if(JSON.stringify(G)!==JSON.stringify(v)||(g?.changes??0)===0&&E.some(z=>!M.has(z))||I.some(z=>M.has(z)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:v,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:I}}let C={schema:fl,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=ti(t.scopeHash,"Implementation scope scopeHash");if(H(em,C)!==y)throw new Error("Implementation scope content hash mismatch");return{...C,scopeHash:y}}function SC(e){let t=rt(e,"Native implementation scope authority");if(at(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(wl);if(JSON.stringify(i)!==JSON.stringify(ao(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=no(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=nm({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 Kn(e){let t=rt(e,"Native implementation scope bundle");at(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=SC(t.authority),n=ro(t.baseline),r=ro(t.current),a=so(t.scope),o=am(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 om(e){let t=so(e.scope);return Kn({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 lm=/^[a-f0-9]{64}$/u;var EC="comet.native.acceptance-trace.v2",CC="comet.native.partial-allowance.v1",RC="comet.native.verification-evidence.v2";function ot(e,t){if(!lm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function um(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function dm(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 n=De(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function Yn(e,t){let i=sm.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})||sm.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 PC(e,t,i){let n=Yn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=ze(n),a=n.toLowerCase(),o=i?Yn(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 Nl(e){let t=Yn(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 $i(e,t){return e<t?-1:e>t?1:0}function co(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function lo(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 fm(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 cm(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 AC(e){let t=co(e,"Native acceptance trace");if(lo(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"||!lm.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=Yn(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=co(o,`Native acceptance trace entry ${s}`);if(lo(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=>Nl(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort($i))||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:Yn(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(n)!==JSON.stringify([...n].sort((o,s)=>$i(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=ot(t.traceHash,"Native acceptance trace hash");if(H(EC,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function hm(e){let t=co(e,"Native partial allowance");if(lo(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($i))||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:dm(t.change),scopeHash:ot(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:yl(t.reason,"Partial allowance reason"),confirmedSummary:yl(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:um(t.sourceRevision),confirmedAt:fm(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=ot(t.allowanceHash,"Native partial allowance hash");if(H(CC,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function bl(e){let t=co(e,"Native verification evidence");if(lo(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=ot(t.implementationScopeHash,"Native verification implementation scope hash"),n=AC(t.acceptanceTrace),r=ot(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:ot(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Nl(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort($i)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort($i);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=>Nl(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort($i)))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:dm(t.change),sourceRevision:um(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:ot(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:cm(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:PC(t.reportRef,"Native verification report ref"),reportHash:ot(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:cm(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:fm(t.createdAt,"Native verification timestamp")},d=ot(t.envelopeHash,"Native verification envelope hash");if(H(RC,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function kl(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 pm="repairStagnation",Ne={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},TC=/^[a-f0-9]{64}$/u;var IC=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),_C=["data","runId","sequence","timestamp","type"],mm=["disposition","overrideSummaryHash","signatureHash"],jC=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],vm=12;function El(e,t){return e<t?-1:e>t?1:0}function gm(e,t,i){let n=Object.keys(e).sort(El);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function uo(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"||!TC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function OC(e){if(!Array.isArray(e)||e.length>ji.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(El)}function wm(e){if(typeof e!="string"||e.length===0||e.length>Ne.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 Sl(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Ne.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ne.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>Ne.maxTextCharacters&&(!r||e.length>Ne.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Ne.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>Ne.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Sl(s,t+1,i,`${n}[${c}]`));return}let a=uo(e,n),o=Object.keys(a);if(o.length>Ne.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ne.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ne.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Sl(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function $C(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 HC(e,t,i){let n=uo(e,`Native repair trajectory event ${t+1}`);if(gm(n,_C,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if($C(n.timestamp),typeof n.type!="string"||!IC.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(wm(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 Sl(n.data,0,r,"Native trajectory event data"),uo(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Cl(e){let t=uo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(El),n=i.length===mm.length&&i.every((l,u)=>l===mm[u]);n||gm(t,jC,"Native repair trajectory projection");let r=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(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Xn(t.contractHash,"Native repair trajectory contract hash"),s=OC(t.failedAcceptanceIds),c=ul(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 FC(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 DC(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??vm;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=dl({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<ji.warningAtConsecutiveFailures?"continue":a<ji.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function LC(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??vm;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 ym(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ne.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=wm(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=HC(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ne.maxTotalDataNodes||c>Ne.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=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,pm)){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=Cl(f[pm]);if(FC(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),DC(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");LC(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>ji.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function Nm(e){return ym(e).history}function bm(e){let t=ym(e).latestProjection;return t?{...t}:null}var Hi={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:[]},Rl=U("comet-native-runtime:v3:semantic-repair-budget"),MC=[{skillVersion:"2",skillHash:U("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:U("comet-native-runtime:v1")}];function km(e){return e.skillVersion===Hi.definition.metadata.version&&e.skillHash===Rl||MC.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Sm(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 xm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],JC=new Set(xm),Tm=new Set([...xm,"minimum_runtime_version","revision"]),GC=new Set([...Tm,"operation"]),UC=512*1024,Pl=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),KC=new Set([...Pl,"implementationScopeHash","repairScopeHash","repairStagnation"]),Al=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 Tl(e,t){return zC.join(F(e,t),"runtime","transition.json")}function ho(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Il(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 fo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xl(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=>!KC.has(u)),a=[...Pl].find(u=>!Object.hasOwn(i,u)),o=Pl.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(kl(i.summary,"Native transition journal event summary"),De(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&&(kl(i.noCodeReason,"Native transition journal event no-code reason"),De(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")?Cl(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 YC(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 xl({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return xl(e,t)}function _l(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?YC(e.eventData,e.evidenceHash):xl(e.eventData,e.evidenceHash),r=Bc(e.nextRun),a=e.previousRun===null?null:Bc(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function Em(e,t,i=!1){if(e.skill!==Hi.definition.metadata.name||(i?!km(e):e.skillVersion!==Hi.definition.metadata.version||e.skillHash!==Rl)||e.orchestration!==Hi.definition.orchestration.mode||e.pendingRef!==Re.pendingRef||e.trajectoryRef!==Re.trajectoryRef||e.contextRef!==Re.contextRef||e.artifactsRef!==Re.artifactsRef||e.checkpointRef!==Re.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Cm(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 Rm(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 jl(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Em(a,"next Run",n||r!==null),Rm(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(Em(r,"previous Run",!0),Rm(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(!Am(Cm(r),Cm(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function XC(e,t,i){return U(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Im(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Pm(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Ol(e,t,i,n,r=!1){let a=i.eventData,o=Pm(e),s=Pm(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&&Am(e.spec_changes,t.spec_changes),l=Sm({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=XC(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 QC(e,t){let i=ho(e);if(Il(i,GC),i.schema!==xi)throw new Error(`Expected Native transition schema ${xi}`);let n=fo(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 ${xi} minimum_runtime_version must be ${3}`);let r=fo(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=_l(i,t),o=ei(i.previousState),s=ei(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Ol(o,s,a,i.operation),jl(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:xi,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 ZC(e,t){let i=ho(e);if(Il(i,JC),i.schema!==Fn)throw new Error(`Expected Native transition schema ${Fn}`);let n=_l(i,t,!0),r=Bn(i.previousState),a=Bn(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Ol(r,a,n,Im(r,a,n.eventData),!0),jl(r,a,n,!0),{schema:Fn,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 eR(e,t){let i=ho(e);if(Il(i,Tm),i.schema!==Ti)throw new Error(`Expected Native transition schema ${Ti}`);if(fo(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ti} minimum_runtime_version must be 2`);let r=fo(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=_l(i,t,!0),o=qn(i.previousState),s=qn(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Ol(o,s,a,Im(o,s,a.eventData),!0),jl(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ti,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 tR(e,t){let i=ho(e);if(i.schema===xi)return{status:"current",journal:QC(i,t)};if(i.schema===Fn)return{status:"migration-required",journal:ZC(i,t)};if(i.schema===Ti)return{status:"migration-required",journal:eR(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function iR(e,t){let i=Tl(e,t);await V(e.nativeRoot,i);try{let n=await Je({root:e.nativeRoot,file:i,maxBytes:UC,label:`Native transition journal ${t}`});return tR(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function _m(e,t){let i=await iR(e,t);if(!i)return null;if(i.status==="migration-required")throw new Al(t);return i.journal}var nR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rR(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 jm(e){let i=(e.findings??[]).filter(u=>!Ai(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||nR.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:rR(e.state)}}import Qn from"path";var Om=8,aR={"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 oR(e){let t=aR[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"}:Ai(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 sR(e,t,i){if(!i.path)return null;let n;if(Qn.isAbsolute(i.path)?n=Qn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=Qn.resolve(F(e,t.name),...i.path.split(/[\\/]/u)):n=Qn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!W(e.projectRoot,n))return null;let r=Qn.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function cR(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 $m(e){return e.findings.map(t=>{let i=oR(t.code);return{code:t.code,message:t.message,severity:i.severity,path:sR(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:cR(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 Hm(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,Om),truncated:t.length>Om}}import Wm from"path";import Fi from"path";var _t={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Di=/^[a-f0-9]{64}$/u;function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mo(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 It(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 Fm(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function $l(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function lR(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Fi.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Fi.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Dm(e,t){return Fi.join(F(e,t),"runtime","checkpoints","progress.json")}function Zn(e,t){return Fi.join(F(e,t),"runtime","checkpoint-journal.json")}function Lm(e,t,i){if(!Di.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Fi.join(F(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function uR(e){if(!Di.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Hl(e,t,i){let n=await Je({root:e,file:t,maxBytes:_t.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function dR(e,t){let i=po(e,`checkpoint manifest artifact ${t}`);mo(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=lR(It(i.path,`checkpoint artifact ${t} path`,4096)),r=ze(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Di.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:$l(i.size,`checkpoint artifact ${t} size`)}}function Fl(e,t){let i=po(e,"Native checkpoint manifest");if(mo(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>_t.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(dR),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=$l(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>_t.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 Mm(e){return U(JSON.stringify(Fl(e,e.change)))}function Bm(e,t){let i=po(e,"Native progress checkpoint");if(mo(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=Fm(i.previousRevision,"Native checkpoint previousRevision"),a=Fm(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=It(i.manifestHash,"Native checkpoint manifestHash",64);if(!Di.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=uR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=It(i.inputHash,"Native checkpoint inputHash",64);if(!Di.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=It(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=$l(i.artifactCount,"Native checkpoint artifactCount");if(u>_t.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=It(i.summary,"Native checkpoint summary"),f=It(i.nextAction,"Native checkpoint nextAction");if(De(d)!==d||De(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:It(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 fR(e,t){let i=po(e,"Native checkpoint journal");if(mo(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=ei(i.previousState),r=ei(i.nextState),a=Bm(i.checkpoint,t),o=Fl(i.manifest,t),s=It(i.inputHash,"Native checkpoint journal inputHash",64),c=U(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Di.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!==Mm(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 hR(e,t,i){let n=Fi.resolve(e.projectRoot,...t.split("/"));if(!W(e.projectRoot,n)||W(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=sc(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await Je({root:e.projectRoot,file:n,maxBytes:_t.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 pR(e,t){let i=Dm(e,t);await V(e.nativeRoot,i);try{return Bm(await Hl(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function mR(e,t,i){let n=Lm(e,t,i);await V(e.nativeRoot,n);let r=await Hl(e.nativeRoot,n,"Native checkpoint manifest"),a=Fl(r,t);if(qm(e,a),Mm(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Dl(e,t){let i=Zn(e,t);await V(e.nativeRoot,i);try{let n=fR(await Hl(e.nativeRoot,i,"Native checkpoint journal"),t);return qm(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function qm(e,t){for(let i of t.artifacts){let n=sc(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Vm(e){let t;try{t=await pR(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:Dm(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 mR(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 hR(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:Lm(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}var zm=240,Jm=8,vo=50;function Gm(e){let t=Array.from(e);return t.length<=zm?e:`${t.slice(0,zm-1).join("")}…`}function vR(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function gR(e){let t=[...new Set(e.map(vR))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Jm),reasonCount:e.length,codesTruncated:t.length>Jm};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,vo),reasonsTruncated:e.length>vo}}}async function Um(e){let t=null;try{let s=await Dl(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Zn(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:Zn(e.paths,e.state.name)}}let i=await Vm({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=gR(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:_t.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Gm(i.checkpoint.summary),nextAction:Gm(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:Wm.relative(e.paths.projectRoot,Wm.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:_t.maxArtifacts}}import{promises as nA}from"node:fs";import Av from"node:path";import Km from"node:path";var wR="comet.native.archive-preflight.v1",yR="comet.native.archive-preflight.v1",NR="comet.native.archive-operation.v1",bR=/^[a-f0-9]{64}$/u,Ym=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function go(e,t){return e<t?-1:e>t?1:0}function SR(e,t){if(typeof e!="string"||!bR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function st(e,t){return e===null?null:SR(e,t)}function ER(e,t){let i=Km.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Km.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 CR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function RR(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 PR(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=st(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=st(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=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"!=(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 AR(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 xR(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!kR.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(go);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function TR(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(go)}function Xm(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(PR).sort((l,u)=>go(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:H(NR,l)})),n=AR(e.evidence),r=RR(e.workspace),a=[...new Set([...xR(e.findingCodes??[]),...TR({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(go),o=CR(e.revision),s=ER(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:wR,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:H(yR,c)}}import{createHash as IR}from"node:crypto";import Qm from"node:path";var _R="comet.native.conflict-radar.v1",me=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}),jR="comet.native.conflict-radar.v1",OR="comet.native.conflict-radar-signals.v1",$R=/^[a-f0-9]{64}$/u,tv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,HR=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),FR=new Set(["capability","operation","baseHash"]),DR=new Set(["path","kind"]);function Li(e,t){return e<t?-1:e>t?1:0}function Ll(e){return Buffer.byteLength(e,"utf8")}function Ml(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 Bl(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(Ll(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function LR(e,t){let i=Bl(e,t,me.maxArtifactPathBytes),n=Qm.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)||Qm.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 iv(e,t){if(typeof e!="string"||!$R.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MR(e,t){let i=Ml(e,FR,t),n=Bl(i.capability,`${t} capability`,me.maxCapabilityBytes);if(!tv.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:iv(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 BR(e,t){let i=Ml(e,DR,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:LR(i.path,`${t} path`),kind:i.kind}}function qR(e,t){let i=Ml(e,HR,`Conflict radar change ${t}`),n=Bl(i.name,`Conflict radar change ${t} name`,me.maxNameBytes);if(!tv.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>me.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>me.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>MR(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>Li(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)=>BR(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>Li(c.path,l.path)||Li(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:iv(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function VR(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>me.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(qR).sort((r,a)=>Li(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)>me.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>me.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function WR(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 zR(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 JR(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function GR(e,t){let i=[],n=IR("sha256").update(`${OR}
172
- [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Wn(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<me.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(WR(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=zR(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:JR(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Zm(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function UR(e,t){return Zm(e.classification)-Zm(t.classification)||Li(e.left,t.left)||Li(e.right,t.right)}function ev(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:_R,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 nv(e){let t=VR(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(GR(t[s],t[c]));i.sort(UR);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=H(jR,{changes:t,relationships:n}),a=i.slice(0,me.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=ev(t,i,a,r);for(;a.length>0&&Ll(JSON.stringify(o))>me.maxSerializedBytes;)a=a.slice(0,-1),o=ev(t,i,a,r);if(Ll(JSON.stringify(o))>me.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as RP}from"node:crypto";import{promises as Me}from"node:fs";import Ue from"node:path";import rv from"node:path";var av="comet.native.check-receipt.v1",KR="comet.native.check-receipt.v1",Mi="scoped-text-safety",ql=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),YR=/^[a-f0-9]{64}$/u,XR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QR="comet.native.checker-policy.v1",ZR="comet.native.check-input.v1",eP=2048,ov=H(QR,{policy:Mi,version:ql,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),tP=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),sv=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],lv=["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"],iP=new Set(lv);function ri(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ai(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 ct(e,t){if(typeof e!="string"||!YR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ni(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uv(e,t){let i=ni(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function cv(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function nP(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>eP||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=rv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||rv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function rP(e){let t=ri(e,"Native check receipt checker");ai(t,["policy","version","hash","limits"],"Native check receipt checker");let i=ri(t.limits,"Native check receipt limits");if(ai(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Mi||t.version!==ql||t.hash!==ov||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Mi,version:ql,hash:ov,limits:{...Pe}}}function aP(e){let t=ri(e,"Native check receipt contract");return ai(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ct(t.expectedHash,"Native check expected contract hash"),beforeHash:ct(t.beforeHash,"Native check before contract hash"),afterHash:ct(t.afterHash,"Native check after contract hash")}}function oP(e){let t=ri(e,"Native check receipt implementation");return ai(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ct(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:ct(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ct(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ct(t.afterSnapshotHash,"Native check after snapshot hash")}}function sP(e){let t=ri(e,"Native check receipt counts");ai(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:ni(t.filesSelected,"Native check filesSelected"),filesScanned:ni(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:ni(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:ni(t.bytesScanned,"Native check bytesScanned"),issueCount:ni(t.issueCount,"Native check issueCount"),recordedIssueCount:ni(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Pe.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function cP(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||sv.indexOf(e.kind)-sv.indexOf(t.kind)}function lP(e){if(!Array.isArray(e)||e.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=ri(n,`Native check issue ${r}`);if(ai(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!tP.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:nP(a.path,`Native check issue ${r} path`),line:uv(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(cP);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function uP(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!iP.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=lv.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 dP(e){return H(ZR,e)}function dv(e){let t=ri(e,"Native check receipt");if(ai(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==av)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!XR.test(t.change))throw new Error("Native check receipt change name is invalid");let i=uv(t.sourceRevision,"Native check source revision"),n=rP(t.checker),r=aP(t.contract),a=oP(t.implementation),o=dP({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ct(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=cv(t.startedAt,"Native check receipt startedAt"),c=cv(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=sP(t.counts),u=lP(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=uP(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>Pe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Pe.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:av,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=ct(t.receiptHash,"Native check receipt content hash");if(H(KR,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var Wl="comet.native.verification-receipt.v3",fP=Wl,hP="comet.native.declared-artifacts.v1",pP=/^[a-f0-9]{64}$/u,mP=/^acceptance-[a-f0-9]{64}$/u,vP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gP=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,wP=4096,yP=256,NP=1024;function Bi(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 jt(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 lt(e,t){if(typeof e!="string"||!pP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Le(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=De(e).trim();if(!i||i.length>wP||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Vl(e,t){let i=Le(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 er(e,t,i=Le,n=!1,r=yP){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 bP(e,t){if(typeof e!="string"||!mP.test(e))throw new Error(`${t} is invalid`);return e}function kP(e){let t=Bi(e,"Native verification receipt bindings");if(jt(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!vP.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:lt(t.contractHash,"Native verification receipt contract hash"),scopeHash:lt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:lt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:lt(t.artifactHash,"Native verification receipt artifact hash")}}function SP(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=gP.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function EP(e,t,i,n){let r=Bi(t,`Native ${e} evidence`);if(e==="automated-check"){if(jt(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=Vl(r.startedAt,"Native automated-check start time"),o=Vl(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=Bi(r.worktree,"Native automated-check worktree");if(jt(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=Bi(r.afterFence,"Native automated-check after fence");if(jt(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:Le(r.executable,"Native automated-check executable"),args:er(r.args,"Native automated-check arguments",Le,!0),cwd:Le(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:Le(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:lt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:lt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:lt(r.outputHash,"Native automated-check output hash"),outputSummary:Le(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){jt(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=SP(r.checkReceiptRef);if(lt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:er(r.subjects,"Native static inspection subjects",Le,n==="required-check"),rule:Le(r.rule,"Native static inspection rule"),resultSummary:Le(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return jt(r,["steps","observations"],"Native manual-evidence evidence"),{steps:er(r.steps,"Native manual evidence steps"),observations:er(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function CP(e){let t=Bi(e,"Native verification receipt");if(jt(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=Le(t.actor,"Native verification receipt actor"),o=er(t.acceptanceIds,"Native receipt acceptance IDs",bP,n==="required-check",NP).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:Wl,kind:i,role:n,status:r,bindings:kP(t.bindings),acceptanceIds:o,actor:a,issuedAt:Vl(t.issuedAt,"Native verification receipt issue time"),evidence:EP(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Mi||s.actor!==`native-runtime:${Mi}`))throw new Error("Native required check policy identity is invalid");return s}function fv(e){let t=Bi(e,"Native verification receipt");if(jt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Wl)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=CP(n),a=lt(t.receiptHash,"Native verification receipt hash");if(H(fP,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function zl(e){return H(hP,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var vv=/^[a-f0-9]{64}$/u,qi=ii,f$=3*qi;function Jl(e,t){let i=Ue.relative(e,t);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function PP(e,t){return B({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return le(i,n)?B(i,n):B(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function hv(e){let t=await Me.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Me.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function AP(e,t){let i=Ue.resolve(e),n=Ue.resolve(t);if(!Jl(i,n))throw new Error("Native evidence path is outside its change");let r=[await hv(i)],a=i;for(let o of Ue.relative(i,n).split(Ue.sep).filter(Boolean)){a=Ue.join(a,o);let s=await hv(a);if(!Jl(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function pv(e){for(let t of e){let i=await Me.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!PP(t,i)||await Me.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function xP(e,t,i={}){let n=await AP(t,Ue.dirname(e));await i.afterParentChainCaptured?.();let r=await Me.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Me.realpath(e);if(!Jl(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Me.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Me.lstat(e),Me.realpath(e)]);if(await pv(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!wo(s,r)||!wo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>qi)throw new Error(`Native evidence document exceeds ${qi} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let g=qi+1-d,S=await o.read(f,0,Math.min(f.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>qi)throw new Error(`Native evidence document exceeds ${qi} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Me.lstat(e),Me.realpath(e)]);if(await pv(n),!m.isFile()||m.isSymbolicLink()||h!==a||!wo(s,p)||!wo(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 gv(e,t){if(!vv.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function TP(e,t,i,n,r){if(!vv.test(i))throw new Error("Native report evidence hash is invalid");let a=await oi({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"||RP("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 Vi(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 IP(e,t,i,n,r){return Ue.join(r??F(e,t),...gv(i,n).split("/"))}async function oi(e){let t=e.changeDir??F(e.paths,e.name),i=IP(e.paths,e.name,e.kind,e.hash,t);return await V(e.paths.nativeRoot,i),xP(i,t,e.hooks)}function mv(e,t){return ro(e,t)}function _P(e,t){let i=so(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function jP(e,t,i){let n=hm(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function OP(e,t,i){let n=bl(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function $P(e,t,i,n=!1,r){let a=await Gl(e,t,i.implementationScopeRef,void 0,r);if(n&&await TP(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 wv(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 tr(e,t,i,n,r){let a=Vi(i,"scopes"),o=_P(await oi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Vi(o.baselineProjectionRef,"snapshots"),c=Vi(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([oi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>mv(d,s)),oi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>mv(d,c))]);return om({baseline:l,current:u,scope:o})}async function Gl(e,t,i,n,r){return(await tr(e,t,i,n,r)).scope}async function wv(e,t,i,n,r){let a=Vi(i,"allowances");return jP(await oi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function yo(e,t,i,n,r){let a=Vi(i,"receipts"),o=fv(await oi({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 ir(e,t,i,n,r){let a=Vi(i,"verifications"),o=OP(await oi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await $P(e,t,o,!1,r),o}var HP=4096;async function FP(e,t=me.maxChanges){try{let i=await Tn({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 yv(e,t){let i=await tt(e,t),[n,r]=await Promise.all([i.implementation_scope?Gl(e,t,i.implementation_scope):null,Pt(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 No(e,t,i={}){let r=(await FP(e,HP)).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 yv(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await yv(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=nv([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 UP,spawn as G$}from"node:child_process";import{promisify as KP}from"node:util";import{constants as Ul,promises as Ae}from"node:fs";import si from"node:path";var LP=/^[a-f0-9]{64}$/u,MP=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,nr=512*1024;function BP(e,t){return B({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function bo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return le(i,n)?B(i,n):B(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function qP(e,t){let i=si.resolve(e),n=si.resolve(t);if(!W(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...si.relative(i,n).split(si.sep).filter(Boolean)]){o&&(a=si.join(a,o));let s=await Ae.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ae.realpath(a);if(r.length>0&&!W(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 bv(e){for(let t of e){let i=await Ae.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!BP(t,i)||await Ae.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function VP(e){if(!LP.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function WP(e){let t=MP.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function zP(e,t,i){return si.join(F(e,t),...VP(i).split("/"))}async function JP(e,t,i){let n=await qP(i,si.dirname(e)),r=await Ae.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>nr)throw new Error(`Native check receipt exceeds ${nr} bytes`);let[a,o]=await Promise.all([Ae.realpath(t),Ae.realpath(e)]);if(!W(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Ul.O_RDONLY|Ul.O_NOFOLLOW|Ul.O_NONBLOCK,c=await Ae.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(),Ae.lstat(e),Ae.realpath(e)]);if(await bv(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!bo(r,l)||!bo(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=nr+1-p,k=await c.read(m,0,Math.min(m.length,N),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>nr)throw new Error(`Native check receipt exceeds ${nr} bytes`);f.push(Buffer.from(m.subarray(0,k.bytesRead)))}let[h,g,S]=await Promise.all([c.stat(),Ae.lstat(e),Ae.realpath(e)]);if(await bv(n),!g.isFile()||g.isSymbolicLink()||S!==o||!W(a,S)||!bo(l,h)||!bo(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 kv(e,t,i){let n=WP(i),r=F(e,t),a=zP(e,t,n);await V(e.nativeRoot,a);let o=dv(await JP(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var rr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var cH=64*1024;var lH=3600*1e3;var uH=KP(UP);var dH=["$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 YP=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Sv(e,t){let i=[];for(let n of YP){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 Ev(e){if(e.receipt.kind!=="static-inspection")return null;let t=await kv(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 Ot=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 XP(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 QP(e){let t=XP(e.bundle.baseline),i=await Lc(e.paths,t,{origin:"explicit",now:e.now});return gl({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function Rv(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await tr(e.paths,e.state.name,e.state.implementation_scope),i=await _i({changeDir:F(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await QP({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 Pv(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Rv(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 ZP(e){let t=await ue({root:F(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Tp(t.text)}}function eA(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 tA(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:zl(e.implementationScope.scope.declaredArtifacts)}}async function Cv(e){let t=await yo(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Sv(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 Ot([{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 Ev({paths:e.paths,state:e.state,receipt:t});if(r){let a=eA({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 iA(e){let t=tA({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Cv({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Ot)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 Cv({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Ot)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 Ot(i)}function Kl(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Yl(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Kl(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Rv(e),ir(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:Kl(e.state.verification_result,"stale"),envelope:null};let n=await ZP({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 iA({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:Kl(e.state.verification_result,"invalid"),envelope:null}}}function rA(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function xv(e){try{return await nA.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function aA(e,t){try{return(await ue({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function oA(e,t,i){let n=eo(e,i.capability);if(!W(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=Av.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await aA(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ue({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 sA(e,t){return xv(Tl(e,t))}async function Xl(e){let t=e.now??new Date,i=await tt(e.paths,e.name),n=await Pt(e.paths,e.name),r=await kt(e.paths.projectRoot),a=rA(i.name,t),o=Av.resolve(e.paths.nativeRoot,...a.split("/"));if(!W(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=>oA(e.paths,i.name,m))),Yl({paths:e.paths,state:i,now:t}),No(e.paths,i.name),Za(e.paths,i.name),hp(e.paths,i.name),sA(e.paths,i.name),xv(o)]);return Xm({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 cA(e,t){let i=F(e,t.name),n=await Pi(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 Va(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 Ut(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function lA(e,t){let i=await cA(e,t);return{committed:i,latest:bm(i),history:Nm(i)}}async function Tv(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await lA(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 w1=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function dA(e){return(await qp(e))?.change??null}function fA(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 hA(e,t){let i=F(e,t.name),n=[...(await Zc(i,t.brief)).findings,...(await wp(e,t)).findings,...await Wp(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await Fa(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 Vh(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 _i({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 _m(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 el(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 Iv(e,t,i){let n=await dA(e)===t,r;try{let w=await Xc(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 Um({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await Tv(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 _i({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 ir(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=Cp({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 No(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 Pt(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let v=await Ua({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 Ga({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 Pv({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 Xl({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 hA(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=$m({paths:e,state:r,findings:h}),S=g.filter(w=>!Ai(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:fA(r,N,k,i?.clarificationMode),archiveReady:N,inspection:a.inspection,findingSummary:Hm(g),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:jm({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:vo,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}:{}}}import vA from"path";var I1={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var M1=16*1024*1024,B1=256*1024,q1=16*1024;var RF=16*1024*1024,ko=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"},So=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 HF=10*1024*1024,$t=class extends Error{};function _v(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new $t(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function jv(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new $t(`${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 $t(`${t} requires a value`);return e.splice(n,2),r}function Ov(e){if(e.length>0)throw new $t(`Unexpected argument: ${e[0]}`)}function $v(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new $t(`${t} is required`);return i}async function Hv(e){return e?vA.resolve(e):wa(process.cwd())}async function Fv(e){let t=await eh({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Dv(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
173
- `}}function Lv(e,t){if(t instanceof $t)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof ko)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 So)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ya)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Xa)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof 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 Ot)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof rr)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 Mv(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}})+`
174
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Bv(e,t){let i=$v(e,"change name");Ov(e);let{config:n,paths:r}=await Fv(t);await Vp(r,i);let a=await Iv(r,i,{clarificationMode:n.native.clarification_mode,maxVerifyFailures:n.native.max_verify_failures});return Dv("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
175
- `)}function gA(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}})+`
176
- `}}async function qv(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{_v(r,"--json"),s=jv(r,"--project-root");let u=[...r,...a],d=await Hv(s);c=await t(u,d)}catch(u){c=Lv(e,u)}let l=o?gA(c):Mv(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
146
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&r===null,index:s},s+=1,e!==null)e=sl(l,e);else if(i)wh(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=sl(l,null);if(d!==null)e=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!wh(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 GS(t){return[...Mi(t)].map(({line:e,body:i})=>({line:e,body:i}))}function io(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function US(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function ll(t,e,i,r=[],n="content-hash"){let a=io(i),o=e.replaceAll("\\","/").trim(),s=r.map(io);if(a.length===0)throw new Error(`${t} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${t} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${F(BS,{kind:t,source:o,context:s,text:a})}`:"",kind:t,source:o,context:s,text:a}}function ul(t,e,i="content-hash"){let r=new Set;for(let n of t){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${e} contains duplicate acceptance criteria`);r.add(a)}return t}function KS(t){let e=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Mi(t)){n=s+1;let c=o?cl(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(e=s+1)):e!==null&&i===null&&(i=s))}if(r===0||e===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:e,end:i??n}}function dl(t,e="brief.md",i=tn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=KS(t);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Mi(t)){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(t)){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(),ul(o.map(l=>ll("brief-example",e,l.join(`
147
+ `),[],r)),"Brief",r)}function fl(t,e="spec.md",i=tn.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(ll("spec-scenario",e,[o.title,...o.body].join(`
148
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of Mi(t)){let u=l?cl(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=io(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(),ul(n,"Specification",r)}function pl(t,e="spec.md",i=tn.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(ll("spec-must",e,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(t)){let f=d?cl(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||sl(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(),ul(n,"Specification mandatory requirements",r)}function YS(t,e){let i=t.trim().replaceAll("\\","/");if(i.length===0||US(i)||ph.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);let r=ph.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${e} references sensitive content`);if(!MS.test(r))throw new Error(`Acceptance evidence ${e} must reference a content-addressed typed receipt`);return r}function XS(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`Acceptance evidence entry ${e} must be an object`);let i=t,r=Object.keys(i).filter(n=>!LS.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${e} has unknown field(s): ${r.join(", ")}`);return i}function Nh(t){if(!Array.isArray(t))throw new Error("Native acceptance evidence block must be a JSON array");let e=new Set;return t.map((i,r)=>{let n=XS(i,r),a=n.acceptance_id;if(typeof a!="string"||!FS.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(e.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(e.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 YS(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 bh(t){let e=GS(t);if(e.some(({line:l,body:u})=>!u&&(l===hh||l===mh)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=e.flatMap(({line:l,body:u},d)=>u&&l===hh?[d]:[]),n=e.flatMap(({line:l,body:u},d)=>u&&l===mh?[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=e.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
149
+ `).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=Nh(o),c=QS(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function QS(t){let e=Nh([...t]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(e,null,2)}var ml=Hn(Jr(),1);import{promises as eE}from"node:fs";var rn="comet.native.v4",ro="comet.native.local-execution.v4";var tE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,iE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rE=/^A[1-9][0-9]*$/u,nE=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 ke(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Se(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function fe(t,e,i){if(typeof t!="string"||!i?.empty&&t.length===0)throw new Error(`${e} must be ${i?.empty?"a string":"a non-empty string"}`);return t}function hl(t,e){return t===null?null:fe(t,e)}function qi(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function te(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function aE(t,e){return t===null?null:te(t,e,Number.MIN_SAFE_INTEGER)}function le(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function st(t,e,i){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((r,n)=>i(r,n))}function no(t,e){return st(t,e,(i,r)=>fe(i,`${e}[${r}]`))}function gi(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Vi(t,e){let i=fe(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO date or timestamp`);return i}function vl(t,e,i=!1){let r=fe(t,e);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return r}function Ue(t,e){let i=ke(t,e);return Se(i,new Set(["text","truncated"]),e),{text:fe(i.text,`${e}.text`,{empty:!0}),truncated:qi(i.truncated,`${e}.truncated`)}}function oE(t,e){let i=`Native spec_changes[${e}]`,r=ke(t,i);Se(r,new Set(["capability","operation","source"]),i);let n=fe(r.capability,`${i}.capability`);if(!iE.test(n))throw new Error(`${i}.capability is invalid`);let a=le(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:vl(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 sE(t){let e="Native workspace",i=ke(t,e);Se(i,new Set(["isolation","change_branch","target_branch","finish"]),e);let r=le(i.isolation,["current","branch","worktree"],`${e}.isolation`),n=hl(i.change_branch,`${e}.change_branch`),a=hl(i.target_branch,`${e}.target_branch`),o=i.finish===null?null:le(i.finish,["merge","push","pull-request","keep"],`${e}.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 cE(t){let e="Native loop",i=ke(t,e);Se(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let r=no(i.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return gi(r,`${e}.previous_unresolved_ids`),{stage:le(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:te(i.goal_cycle,`${e}.goal_cycle`,1),iteration:te(i.iteration,`${e}.iteration`),attempt:te(i.attempt,`${e}.attempt`),retry_epoch:te(i.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:te(i.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:te(i.no_progress_count,`${e}.no_progress_count`),execution_failure_count:te(i.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:r,next_action:hl(i.next_action,`${e}.next_action`)}}function lE(t,e){let i=`Native acceptance[${e}]`,r=ke(t,i);Se(r,new Set(["id","source","text","result","reason"]),i);let n=fe(r.id,`${i}.id`);if(!rE.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:vl(r.source,`${i}.source`),text:fe(r.text,`${i}.text`),result:le(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Ue(r.reason,`${i}.reason`)}}function uE(t,e){let i=`Native builder_handoff.checks[${e}]`,r=ke(t,i);return Se(r,new Set(["name","result","note"]),i),{name:Ue(r.name,`${i}.name`),result:le(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Ue(r.note,`${i}.note`)}}function dE(t){let e="Native builder_handoff",i=ke(t,e);Se(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"]),e);let r=no(i.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return gi(r,`${e}.addressed_acceptance_ids`),{candidate_id:fe(i.candidate_id,`${e}.candidate_id`),identity_provider:fe(i.identity_provider,`${e}.identity_provider`),builder_execution_ref:fe(i.builder_execution_ref,`${e}.builder_execution_ref`),iteration:te(i.iteration,`${e}.iteration`,1),summary:Ue(i.summary,`${e}.summary`),addressed_acceptance_ids:r,checks:st(i.checks,`${e}.checks`,uE),checks_truncated:qi(i.checks_truncated,`${e}.checks_truncated`),known_limits:st(i.known_limits,`${e}.known_limits`,(n,a)=>Ue(n,`${e}.known_limits[${a}]`)),known_limits_truncated:qi(i.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Vi(i.submitted_at,`${e}.submitted_at`)}}function fE(t,e){let i=`Native blockers[${e}]`,r=ke(t,i);Se(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=no(r.acceptance_ids,`${i}.acceptance_ids`);return gi(n,`${i}.acceptance_ids`),{owner:le(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Ue(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 pE(t,e){let i=`Native verification.checks[${e}]`,r=ke(t,i);return Se(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:fe(r.id,`${i}.id`),name:Ue(r.name,`${i}.name`),argv_display:st(r.argv_display,`${i}.argv_display`,(n,a)=>Ue(n,`${i}.argv_display[${a}]`)),argv_truncated:qi(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:vl(r.cwd_ref,`${i}.cwd_ref`,!0),status:le(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:aE(r.exit_code,`${i}.exit_code`),duration_ms:te(r.duration_ms,`${i}.duration_ms`)}}function hE(t){let e="Native verification",i=ke(t,e);Se(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let r=st(i.checks,`${e}.checks`,pE);gi(r.map(a=>a.id),`${e}.checks IDs`);let n=fe(i.identity_provider,`${e}.identity_provider`);return{candidate_id:fe(i.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:fe(i.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:te(i.iteration,`${e}.iteration`,1),attempt:te(i.attempt,`${e}.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"],`${e}.assurance`),verdict:le(i.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:r,summary:Ue(i.summary,`${e}.summary`),risks:st(i.risks,`${e}.risks`,(a,o)=>Ue(a,`${e}.risks[${o}]`)),risks_truncated:qi(i.risks_truncated,`${e}.risks_truncated`),completed_at:Vi(i.completed_at,`${e}.completed_at`)}}function mE(t,e){let i=`Native history[${e}]`,r=ke(t,i);Se(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=no(r.unresolved_ids,`${i}.unresolved_ids`);return gi(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:Ue(r.summary,`${i}.summary`),completed_at:Vi(r.completed_at,`${i}.completed_at`)}}function vE(t){let e="Native history_overflow.outcome_counts",i=ke(t,e),r=["pass","fail","blocked","execution-error","recovery"];return Se(i,new Set(r),e),{pass:te(i.pass,`${e}.pass`),fail:te(i.fail,`${e}.fail`),blocked:te(i.blocked,`${e}.blocked`),"execution-error":te(i["execution-error"],`${e}.execution-error`),recovery:te(i.recovery,`${e}.recovery`)}}function gE(t){let e="Native history_overflow",i=ke(t,e);Se(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let r=te(i.dropped_entries,`${e}.dropped_entries`),n=i.first_dropped_at===null?null:Vi(i.first_dropped_at,`${e}.first_dropped_at`),a=i.last_dropped_at===null?null:Vi(i.last_dropped_at,`${e}.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=vE(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 wE(t){let e=new Set(t.acceptance.map(i=>i.id));for(let i of t.loop.previous_unresolved_ids)if(!e.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of t.blockers)for(let r of i.acceptance_ids)if(!e.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(t.builder_handoff&&!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function yE(t){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let i=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(i!==null&&t.loop.stage!==i)throw new Error(`Native status ${t.status} requires loop stage ${i}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function gl(t){let e=ke(t,"Native portable state");if(Se(e,nE,"Native portable state"),e.schema!==rn)throw new Error(`Native portable state schema must be ${rn}`);let i=fe(e.name,"Native state name");if(!tE.test(i))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=st(e.spec_changes,"Native spec_changes",oE);gi(r.map(s=>s.capability),"Native spec change capabilities");let n=st(e.acceptance,"Native acceptance",lE);gi(n.map(s=>s.id),"Native acceptance IDs");let a=st(e.history,"Native history",mE);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:rn,name:i,language:le(e.language,["en","zh-CN"],"Native state language"),phase:le(e.phase,["shape","build","verify","archive"],"Native state phase"),status:le(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:te(e.state_version,"Native state_version",1),brief:"brief.md",spec_changes:r,workspace:sE(e.workspace),loop:cE(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:dE(e.builder_handoff),blockers:st(e.blockers,"Native blockers",fE),verification:e.verification===null?null:hE(e.verification),history:a,history_overflow:gE(e.history_overflow),verification_result:le(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:le(e.verification_report,["verification.md"],"Native verification_report"),archived:qi(e.archived,"Native archived"),created_at:Vi(e.created_at,"Native created_at")};return wE(o),yE(o),o}function NE(t,e){let i=(0,ml.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${e} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Sh(t){let e=await eE.readFile(t,"utf8");return gl(NE(e,"Native portable state"))}var Nt="comet.native.v3",bt="comet.native.v2",kt="comet.native.v1",Wi="comet.native.transition.v3",zi="comet.native.transition.v2",nn="comet.native.transition.v1";var Eh="comet.native.portable-migration.v1",bE=new Set(["schema","id","change","fromSchema","status","createdAt"]),kE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SE=/^[a-z0-9][a-z0-9-]{7,127}$/u,EE=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),PE=new Set([kt,bt,Nt]);function xE(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function CE(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function xh(t){let e=xE(t,"Native portable migration transaction"),i=Object.keys(e).filter(r=>!bE.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(e.schema!==Eh)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!SE.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!kE.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!PE.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!EE.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Eh,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:CE(e.createdAt,"Native portable migration transaction createdAt")}}var Ch="comet.native.archive-transaction.v4",Rh="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",AE=new RegExp(`^portable-archive-(${Rh})\\.json$`,"u"),_E=new RegExp(`^portable-migration-(${Rh})\\.json$`,"u"),TE=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,IE=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jE=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),$E=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),OE=new Set(["capability","operation","source","content"]),Ah=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function _h(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Th(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${i} fields are invalid`)}function HE(t,e){let i=`Native portable Archive spec_changes[${e}]`,r=_h(t,i);if(Th(r,OE,i),typeof r.capability!="string"||!Ah.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function DE(t){let e=_h(t,"Native portable Archive transaction");if(Th(e,$E,"Native portable Archive transaction"),e.schema!==Ch)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!TE.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Ah.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!IE.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!jE.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=e.spec_changes.map(HE);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(e.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Ch,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:i,created_at:e.created_at}}function wl(t){let e=AE.exec(t);if(e)return{kind:"archive",change:e[1]};let i=_E.exec(t);return i?{kind:"migration",change:i[1]}:null}async function Ih(t,e){let i=wl(e);if(!i)return null;let r=await oe({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=RE.join(t.transactionsDir,e);if(i.kind==="archive"){let s=DE(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=xh(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}function jh(t){return t.kind==="archive"||t.journal.status!=="committed"}import Et from"path";import{TextDecoder as WE}from"util";import{createHash as BE}from"node:crypto";import{constants as ao,promises as Re}from"node:fs";import Ke from"node:path";import{TextDecoder as FE}from"node:util";function so(t,e){let i=Ke.relative(t,e);return i===""||!Ke.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ke.sep}`)}function $h(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function LE(t,e){return q({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function ME(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function oo(t,e){return q({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function yl(t,e){let i=await Re.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await Re.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Oh(t,e,i){let r=Ke.resolve(t),n=Ke.resolve(e);if(!so(r,n))throw new Error(`${i} is outside its managed root`);let a=[await yl(r,i)],o=r;for(let s of Ke.relative(r,n).split(Ke.sep).filter(Boolean)){await St(a,i),o=Ke.join(o,s);let c=await yl(o,i);if(!so(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(t,e){for(let i of t){let r=await Re.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!LE(i,r)||await Re.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function qE(t,e,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ct(t){let e=$h(t.maxBytes),i=Ke.resolve(t.file),r=await Oh(t.root,Ke.dirname(i),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>yl(Ke.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await St(r,t.label);let a=await Re.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=ME(a),s=await Re.realpath(i);if(!so(r[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>so(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ao.O_RDONLY:ao.O_RDONLY|ao.O_NOFOLLOW|ao.O_NONBLOCK,l=await Re.open(i,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[d,f]=await Promise.all([Re.lstat(i),Re.realpath(i)]);if(await St(r,t.label),await St(n,t.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!oo(o,u)||!oo(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await qE(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),Re.lstat(i),Re.realpath(i)]);if(await St(r,t.label),await St(n,t.label),!p.isFile()||p.isSymbolicLink()||m!==s||!oo(o,v)||!oo(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:BE("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Hh(t){let e=await ct(t),i;try{i=new FE("utf-8",{fatal:!0}).decode(e.bytes)}catch(r){throw new Error(`${t.label} is not valid UTF-8`,{cause:r})}return{...e,text:i}}async function an(t){let e=await Oh(t.root,t.directory,t.label),i;if(t.maxEntries===void 0)i=await Re.readdir(t.directory,{withFileTypes:!0});else{let r=$h(t.maxEntries);i=[];let n=await Re.opendir(t.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${t.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await St(e,t.label),{entries:i,verify:()=>St(e,t.label)}}var zE=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),JE=new Set(["id","type","source","target","staged","backup"]),GE=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),UE=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Fh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var KE=256*1024,g$=1024*1024,w$=16*1024;var y$=64*1024*1024;var YE=new WE("utf-8",{fatal:!0});function lo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function uo(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Lh(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Nl(t,e){if(typeof t!="string"||t.length===0||Et.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function co(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Dh(t,e){if(Nl(t,e),t.includes("\\")||t!==Et.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function XE(t,e){let i=lo(t,`transaction operations[${e}]`);if(uo(i,JE,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Nl(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Nl(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function Mh(t){let e=lo(t,"Native Archive transaction journal");if(uo(e,GE,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Fh.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Lh(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(co(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=lo(s,`Archive transaction operations[${c}]`);if(uo(l,UE,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Dh(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Dh(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&co(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(co(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);co(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function QE(t){let e=lo(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Mh(e);if(uo(e,zE,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Fh.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Et.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Et.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Lh(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(XE),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function ZE(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Et.join(t.transactionsDir,e)}function qh(t,e){let i=ZE(t,e);return{directory:i,journal:Et.join(i,"transaction.json"),events:Et.join(i,"events.jsonl"),staged:Et.join(i,"staged"),backups:Et.join(i,"backups")}}async function bl(t,e){let i=qh(t,e);return await Promise.all(Object.values(i).map(r=>W(t.runtimeDir,r))),i}async function kl(t,e,i={}){let r=await bl(t,e),n=await ct({root:t.runtimeDir,file:r.journal,maxBytes:KE,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(YE.decode(n.bytes)),o=QE(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function iP(t,e,i){let r;try{r=await eP.readdir(t.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await kl(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(wl(n.name))try{let a=await Ih(t,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(jh(a))return!0}catch{return!0}return!1}async function rP(t,e){let i=Date.now()+5e3,r=tP.join(t.locksDir,"root-move.lock");for(;;)try{return await eo(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await fh(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function lt(t,e,i,r){let n=await rP(t,e);try{if(await Qa(t.projectRoot),await iP(t,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await to(n)}}import{createHash as vo}from"crypto";import{spawn as Qh}from"node:child_process";import{promises as Y}from"fs";import O from"path";import{createHash as Vh}from"crypto";import{createReadStream as nP}from"fs";async function Sl(t){let e=Vh("sha256");for await(let i of nP(t))e.update(i);return e.digest("hex")}function U(t){return Vh("sha256").update(t).digest("hex")}var fo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Al=1e3,aP=8*1024*1024,oP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),cP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),lP=new Set(["schema","include","exclude","hash"]),uP=new Set(["provider","gitSelection","physicalSelection","projection"]),dP=new Set(["provider","selection"]),fP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),pP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),hP=new Set(["schema","status","before","after"]),mP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),vP=new Set(["path","hash","size","type","gitObjectId"]),gP=new Set(["path","size","type","reason"]),wP=new Set(["ref","hash","count"]),yP=new Set(["change-created","legacy-migration","explicit"]),NP=new Set(["file","directory","other"]),bP=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"]),go=/^[a-f0-9]{64}$/u,Zh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,kP=new Set(["EACCES","EPERM"]),Qi=64*1024,Cl=64*1024,SP=6e4,EP=1e3,PP=2,_l={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},xP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function em(t){let e=t.deadlineMs??SP;if(!Number.isSafeInteger(e)||e<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+e,gitProcess:t.gitProcess??{command:"git"}}}function Ye(t){return Math.max(0,t.deadlineAt-Date.now())}function j(t){return Ye(t)>=1}function El(t){let e=t===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:t});return Object.assign(e,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Yi(t){return t.code==="GIT_SNAPSHOT_TIMEOUT"}function CP(t){let e={...xP,...t};if(!Number.isSafeInteger(e.maxNodes)||e.maxNodes<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxPathBytes)||e.maxPathBytes<1||e.maxPathBytes>e.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return e}async function RP(t,e){if(e.terminateTree){await e.terminateTree(t);return}let i=t.pid;if(i===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&O.win32.isAbsolute(r)?O.win32.resolve(r):"C:\\Windows",a=O.win32.join(n,"System32","taskkill.exe");if(!O.win32.isAbsolute(a))throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.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=Qh(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),EP),u.unref()}catch{d(!1)}});for(let s=0;s<PP;s+=1)if(await o()){t.kill("SIGKILL");return}throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.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}t.kill("SIGKILL")}function Tl(t,e,i,r){let n=Ye(t);if(n<1)throw El();let a=t.gitProcess,o=Qh(a.command,[...a.argsPrefix??[],"-C",e,...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=RP(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?El(v.error):El()}return{code:h,spawnError:s}});return{child:o,completion:f}}function tm(t){let e={..._l,...t};if(!Number.isSafeInteger(e.maxRecords)||e.maxRecords<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxRecordBytes)||e.maxRecordBytes<1||e.maxRecordBytes>e.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return e}async function po(t,e,i,r=Cl){let{child:n,completion:a}=Tl(t,e,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 Pl(t){return{hash:t.digest,recordCount:t.recordCount,storedRecordCount:t.records.length,stdoutBytes:t.stdoutBytes,overflow:t.overflow}}function sn(t,e,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}=Tl(t,e,i,r.stdin!==void 0),c=[],l=vo("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 ho(t){let e=t.toString("utf8");if(!Buffer.from(e,"utf8").equals(t))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return e}async function AP(t,e,i){if(i.length===0)return new Set;let r=await sn(t,e,["check-ignore","--no-index","-z","--stdin"],{..._l,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=ho(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function _P(t,e,i){let{child:r,completion:n}=Tl(t,e,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(t){let e=t.endsWith("/")?t.slice(0,-1):t;return e.length===0||e.includes("\\")||O.posix.isAbsolute(e)||/^[A-Za-z]:/u.test(e)||O.posix.normalize(e)!==e||e===".."||e.startsWith("../")||e.includes("\0")?null:e}function TP(t,e){return t.map(i=>{let r=Xi(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${e} path`);return r})}async function IP(t){let e=O.resolve(t);for(;;){try{return await Y.lstat(O.join(e,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=O.dirname(e);if(i===e)return!1;e=i}}async function im(t,e,i,r={}){let n=O.resolve(e.projectRoot),a=O.join(n,".comet","current-change.json"),s=["--",".",...[e.nativeRoot,e.runtimeDir,e.configFile,a].map(f=>{let h=O.relative(n,O.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 sn(t,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await sn(t,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await sn(t,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function rm(t){return{stageBefore:Pl(t.stagedBefore),combined:Pl(t.combined),stageAfter:Pl(t.stagedAfter)}}async function nm(t,e,i=_l,r={}){let n=O.resolve(e.projectRoot);if(!await IP(n))return null;let a;try{a=await po(t,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 im(t,e,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=ho(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(ho),p=TP(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:rm(o)}}function Yt(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function Wh(t){return t.stageBefore.overflow||t.combined.overflow||t.stageAfter.overflow}function jP(t,e){return!Yt(t.stageBefore,t.stageAfter)||!Yt(t.stageAfter,e.stageBefore)||!Yt(t.combined,e.combined)||!Yt(e.stageBefore,e.stageAfter)}async function am(t,e,i,r,n){let a;try{a=await im(t,e,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=rm(a),c=Wh(o)||Wh(s),l=jP(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
150
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var $P=(1n<<256n)-1n;function OP(t){return t.isFile()?"file":t.isDirectory()?"directory":t.isSymbolicLink()?"symlink":"other"}async function zh(t){let e=O.resolve(t.paths.projectRoot),i=O.resolve(t.paths.nativeRoot),r=O.resolve(t.paths.runtimeDir),n=O.resolve(t.paths.configFile),a=O.join(e,".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=()=>Ye(t.execution)>=1?!0:(h=!0,p=!0,!1),b=k=>{let E=Buffer.from(`${k.type}\0${k.path}`,"utf8"),y=vo("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")}`)&$P,d+=1,f+=E.byteLength,Buffer.byteLength(k.path,"utf8")>t.limits.maxPathBytes||f>t.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===e&&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===e&&ne(J))throw J;v||=re(J),h||=ne(J),p=!0;break}if(!m()||S===null)break;if(u+=1,u>t.limits.maxNodes){h=!0,p=!0;break}let H=O.join(k,S.name),I=DP(e,H);if(H===n||H===a||Xe(i,H)||Xe(r,H)||t.denylist.some(J=>Xe(J,H))||at(I)!==null)continue;if(!m())break;let ue;try{ue=await Y.lstat(H)}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 t.hooks?.afterNode?.(I),p||!m())break;continue}if(!m())break;let X=OP(ue);if(X==="directory"){if(MP(t.policy,I))continue;if(!m())break;let J;try{J=await Y.realpath(H)}catch(it){if(!m())break;if(!ne(it)&&!re(it))throw it;if(v=!0,b({path:I,type:X}),s.push({path:I,size:null,type:"directory",reason:ne(it)?"unreadable":"changed-during-read"}),await t.hooks?.afterNode?.(I),p||!m())break;continue}if(!m())break;if(!B(t.physicalProjectRoot,J)||Xe(t.physicalNativeRoot,J))continue;if(b({path:I,type:X}),await t.hooks?.afterNode?.(I),!m()||(await N(H),p))break;continue}if(b({path:I,type:X}),await t.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(e),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
151
+ ${JSON.stringify({maxNodes:t.limits.maxNodes,maxBytes:t.limits.maxBytes,maxPathBytes:t.limits.maxPathBytes})}`):U(`comet.native.physical-selection.v1
152
+ ${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 om(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function HP(t,e){let i=t.overflow||e.overflow,r=t.unstable||e.unstable||!om(t,e),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:t,after:e}:null}}function sm(t){return[...new Set([...t.tracked,...t.untracked])].sort((e,i)=>e.localeCompare(i,"en"))}async function Jh(t,e){let r=(await po(t,e,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Zh.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return U(`gitlink:${r}`)}async function Gh(t,e){let i=await Jh(t,e),r=await _P(t,e,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Jh(t,e);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function on(t,e){if(at(e)!==null)return!1;let i=O.resolve(t.projectRoot,...e.split("/"));return!Xe(O.resolve(t.nativeRoot),i)&&!Xe(O.resolve(t.runtimeDir),i)}function DP(t,e){return O.relative(t,e).split(O.sep).join("/")}function BP(t,e){return e.map(i=>O.resolve(t,...i.split(/[\\/]/u)))}function Xe(t,e){let i=O.resolve(t),r=O.resolve(e);return r===i||B(i,r)}function ne(t){return kP.has(t.code??"")}function re(t){return t.code==="ENOENT"}function Il(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
153
+ `)}function FP(t,e){return U(`comet.native.snapshot-policy.v1
154
+ ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function xl(t,e,i){let r=new Set(e),n=[...e];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=t[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 LP(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Uh(t){let e=Xa(t,"Native snapshot pattern"),i=[];for(let r=0;r<e.length;r+=1){let n=e[r];n==="*"&&e[r+1]==="*"?(r+=1,e[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?LP(n):void 0;if(a&&!a())return!1;let o=xl(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=xl(i,c,a),o===null||o.size===0)return!1}return xl(i,o,a)?.has(i.length)??!1}}function cm(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>Xa(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(t.exclude.map(n=>Xa(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let r=FP(e,i);if("hash"in t&&t.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:r},includeMatchers:e.map(Uh),excludeMatchers:i.map(Uh),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 MP(t,e){return t?.excludedDirectoryPrefixes.includes(e)??!1}function Kh(t,e,i){if(!t)return!0;let r=()=>j(i),n=!1;for(let a of t.includeMatchers){if(!r())return!1;if(a(e,r)){n=!0;break}}if(!n)return!1;for(let a of t.excludeMatchers)if(!r()||a(e,r))return!1;return!0}function cn(t,e,i){let r=JSON.stringify(i);return U(`${t}
155
+ ${Buffer.byteLength(e)}:${e}
156
+ ${Buffer.byteLength(r)}:${r}`)}function Rl(t){return t.reason==="git-enumeration-limit"||t.reason==="git-selection-changed"||t.reason==="physical-enumeration-limit"||t.reason==="physical-selection-changed"}function mo(t){for(let e=t.length-1;e>=0;e-=1){let i=t[e];if(!Rl(i))return t.splice(e,1),i}return null}function Kt(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return ge(i,r)?q(i,r):q(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function qP(t,e,i,r){if(!j(r))return{status:"budget-exhausted"};let n;try{n=await Y.open(t,"r")}catch(c){if(!j(r))return{status:"budget-exhausted"};throw c}if(!j(r))return await n.close(),{status:"budget-exhausted"};let a=vo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,e+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()||!Kt(i,c))return{status:"changed"};for(;;){if(!j(r))return{status:"budget-exhausted"};let l=e+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()||!Kt(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>e)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Oe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function He(t,e,i){let r=Object.keys(t).find(n=>!e.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Ki(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ut(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function lm(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=O.posix.normalize(t);if(i!==t||O.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function VP(t,e){let i=Oe(t,`Native snapshot entry ${e}`);He(i,vP,`Native snapshot entry ${e}`);let r=lm(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!go.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:r,hash:i.hash,size:ut(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Zh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function WP(t,e){let i=Oe(t,`Native snapshot omission ${e}`);if(He(i,gP,`Native snapshot omission ${e}`),!NP.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!bP.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:lm(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:ut(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function zP(t){let e=Oe(t,"Native snapshot omission overflow");if(He(e,wP,"Native snapshot omission overflow"),typeof e.hash!="string"||!go.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:Ki(e.count,"Native snapshot omission overflow count")}}function Ui(t,e){let i=Oe(t,e);if(He(i,pP,e),typeof i.hash!="string"||!go.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let r=ut(i.recordCount,`${e} recordCount`),n=ut(i.storedRecordCount,`${e} storedRecordCount`),a=ut(i.stdoutBytes,`${e} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function Yh(t){let e=Oe(t,"Native Git selection evidence");if(He(e,fP,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=Ui(e.stageBefore,"Native Git selection stageBefore"),r=Ui(e.combined,"Native Git selection combined"),n=Ui(e.stageAfter,"Native Git selection stageAfter"),a=Ui(e.finalStageBefore,"Native Git selection finalStageBefore"),o=Ui(e.finalCombined,"Native Git selection finalCombined"),s=Ui(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Yt(i,n)||!Yt(n,a)||!Yt(r,o)||!Yt(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Xh(t,e){let i=Oe(t,e);if(He(i,mP,e),typeof i.hash!="string"||!go.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let r=ut(i.visitedNodeCount,`${e} visitedNodeCount`),n=ut(i.recordCount,`${e} recordCount`),a=ut(i.storedRecordCount,`${e} storedRecordCount`),o=ut(i.encodedBytes,`${e} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function JP(t){let e=Oe(t,"Native physical selection evidence");if(He(e,hP,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=Xh(e.before,"Native physical selection before"),r=Xh(e.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!om(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(e.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 wi(t){let e=Oe(t,"Native content snapshot manifest");if(He(e,sP,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!yP.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let y=Oe(e.capture,"Native content snapshot capture");if(He(y,uP,"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:Yh(y.gitSelection),w=y.physicalSelection===void 0?void 0:JP(y.physicalSelection),g=null;if(y.projection!==void 0){let S=Oe(y.projection,"Native content snapshot projection");if(He(S,dP,"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:Yh(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 e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Oe(e.limits,"Native content snapshot limits");He(r,cP,"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(e.policy!==void 0){let y=Oe(e.policy,"Native snapshot policy");if(He(y,lP,"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=cm({include:y.include,exclude:y.exclude,hash:y.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(VP),s=e.omitted.map(WP),c=ut(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:zP(e.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>Al||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let 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:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Il(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function um(t,e,i={}){let r=wi(e);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=O.resolve(t.projectRoot),a=em(i),o=tm(i.gitSelectionLimits),s=await nm(a,t,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(sm(s).filter(w=>on(t,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>on(t,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 AP(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!h(w.path)&&on(t,w.path)&&(c.has(w.path)||!p.has(w.path)));await am(a,t,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)||!on(t,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=cn(k,"git-selection",{source:"git-selection",...s.overflow}));let E=w=>{P+=1,k=cn(k,"omission",w)};for(;N.length>Al;){let w=mo(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(;Il(x)>r.limits.maxManifestBytes;){let w=mo(N);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(w),x=y()}return wi(x)}function GP(t,e){if(!oP.test(e))throw new Error(`Invalid Native change name: ${e}`);return O.join(G(t,e),"baseline-manifest.json")}async function dm(t,e={}){let i={maxFiles:e.limits?.maxFiles??fo.maxFiles,maxFileBytes:e.limits?.maxFileBytes??fo.maxFileBytes,maxTotalBytes:e.limits?.maxTotalBytes??fo.maxTotalBytes,maxManifestBytes:e.limits?.maxManifestBytes??fo.maxManifestBytes,...e.limits?.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},r=cm(e.policy),n=em({...e,deadlineMs:e.deadlineMs??i.maxDurationMs}),a=tm(e.gitSelectionLimits),o=CP(e.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=O.resolve(t.projectRoot),c=await Y.realpath(s),l=O.resolve(t.nativeRoot),u=await Y.realpath(l),d=O.resolve(t.runtimeDir),f=O.resolve(t.configFile),h=O.join(s,".comet","current-change.json"),v=BP(s,e.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=cn(E,"omission",_)},S=_=>{if(P+=1,m.length<Al){m.push(_);return}if(Rl(_)){let A=mo(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),m.push(_);return}g(_)},H=_=>{P+=_.count,k+=_.count,E=cn(E,"git-selection",{source:"git-selection",..._})},I=_=>{k+=1,E=cn(E,"manifest-entry",{reason:"manifest-size",entry:_})},ue=async(_,A)=>{p.push(_),y+=_.size,b.set(_.path,A),x||(x=!0,await e.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},X=(_,A)=>{let T=p.findIndex(K=>K.path===_);if(T<0)return;let[D]=p.splice(T,1);y-=D.size,b.delete(_),S(A)},J=async(_,A,T,D)=>{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)||!B(c,K)||Xe(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 qP(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||!Kt(T,M.finalStat)||!Kt(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 ue({path:A,hash:M.hash,size:$.size,type:"file",...D===void 0?{}:{gitObjectId:D}},{kind:"file",target:_,realTarget:K,stat:$})}},it=async(_,A,T)=>{if(!j(n))return;let D,K,M;try{if(D=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()||!Kt(T,M)||M.mtimeMs!==T.mtimeMs||M.ctimeMs!==T.ctimeMs||!D.equals(K)){S({path:A,size:null,type:"other",reason:"changed-during-read"});return}let $=D.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=vo("sha256").update("symlink\0").update(D).digest("hex");j(n)&&await ue({path:A,hash:Z,size:$,type:"file"},{kind:"symlink",target:_,rawTarget:D,stat:M})},Me=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()||!Kt(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()||!Kt(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,D;try{if(T=await Y.realpath(A.target),!j(n))return;D=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&&D.isDirectory()&&!D.isSymbolicLink()&&Kt(A.stat,D)&&B(c,T)&&!Xe(u,T))){X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!j(n))return;M=await Gh(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"})}}},xe=await nm(n,t,a,e.gitSelectionHooks);if(xe===null){let _=await zh({execution:n,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:e.physicalSelectionHooks});await e.physicalSelectionHooks?.afterInitialSelection?.();for(let D of _.records){if(D.type!=="file"&&D.type!=="symlink"||b.has(D.path))continue;if(Ye(n)<1)break;if(!Kh(r,D.path,n))continue;if(Ye(n)<1)break;let K=O.resolve(s,...D.path.split("/")),M;try{M=await Y.lstat(K)}catch($){if(!j(n))break;if(!ne($)&&!re($))throw $;S({path:D.path,size:null,type:"file",reason:re($)?"changed-during-read":"unreadable"});continue}if(Ye(n)<1)break;if(D.type==="symlink"&&M.isSymbolicLink()){if(await it(K,D.path,M),Ye(n)<1)break;continue}if(D.type!=="file"||!M.isFile()||M.isSymbolicLink()){S({path:D.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(K,D.path,M),Ye(n)<1)break}Ye(n)>=1&&await Me();let A=await zh({execution:n,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),T=HP(_.evidence,A.evidence);w=T.evidence;for(let D of[..._.omissions,...A.omissions,...T.omissions])m.some(K=>K.path===D.path&&K.reason===D.reason)||S(D)}else{await e.gitSelectionHooks?.afterInitialSelection?.();let _=e.incrementalBaseline,A=new Map,T=!1;if(_){let R=wi(_);for(let Q of R.entries)Q.gitObjectId!==void 0&&A.set(Q.path,Q);T=A.size>0}let D=new Set,K=!0;try{let R=await sn(n,s,["ls-files","-v","-z"],{...a,...e.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:e.gitSelectionHooks.outputChunkBytes}});if(R.overflow)T=!1,K=!1,A.clear();else for(let Q of R.records){let ee=ho(Q),ve=ee.indexOf(" "),de=ve<0?null:Xi(ee.slice(ve+1));if(ve!==1||de===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&D.add(de)}}catch(R){if(Yi(R))throw R;T=!1,K=!1,A.clear()}let M=new Set;try{let R=await po(n,s,["ls-files","--modified","-z"],Cl);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 sm(xe)){if(b.has(R)||!on(t,R))continue;if(Ye(n)<1)break;if(!Kh(r,R,n))continue;if(Ye(n)<1)break;let Q=O.resolve(s,...R.split("/"));if(Q===f||Q===h||Xe(d,Q)||v.some(Ce=>Xe(Ce,Q)))continue;if(xe.gitlinks.has(R)){if(p.length>=i.maxFiles){S({path:R,size:0,type:"file",reason:"file-count"});continue}let Ce,$n;try{[Ce,$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()||!B(c,Ce)||Xe(u,Ce)){S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Pi=await Gh(n,Ce);if(Pi.dirty){S({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await ue({path:R,hash:Pi.hash,size:0,type:"file"},{kind:"gitlink",target:Q,realTarget:Ce,stat:$n,hash:Pi.hash})}catch(Pi){if(Yi(Pi))throw Pi;S({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await Y.lstat(Q)}catch(Ce){if(re(Ce)&&xe.tracked.has(R)){N.set(R,Q);continue}if(!ne(Ce)&&!re(Ce))throw Ce;S({path:R,size:null,type:"file",reason:re(Ce)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await it(Q,R,ee);continue}if(!ee.isFile()){xe.nestedRepositories.has(R)||S({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let ve=xe.trackedObjectIds.get(R),de=ve?A.get(R):void 0;if(T&&de?.gitObjectId!==void 0&&de.gitObjectId===ve&&!D.has(R)&&!M.has(R)){if(p.length>=i.maxFiles){S({path:R,size:de.size,type:"file",reason:"file-count"});continue}if(de.size>i.maxFileBytes){S({path:R,size:de.size,type:"file",reason:"file-size"});continue}if(y+de.size>i.maxTotalBytes){S({path:R,size:de.size,type:"file",reason:"total-size"});continue}p.push({...de}),y+=de.size,$.add(R);continue}let Yu=K&&!D.has(R)&&!M.has(R)?ve:void 0;await J(Q,R,ee,Yu),Yu!==void 0&&Z.add(R)}if(await Me(),await e.gitSelectionHooks?.afterContentRevalidation?.(),await am(n,t,a,xe,e.gitSelectionHooks?.outputChunkBytes),$.size>0||T&&Z.size>0){let R=await po(n,s,["ls-files","--modified","-z"],Cl),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(de=>de.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(de=>de.path===ee);ve&&delete ve.gitObjectId}}for(let R of xe.omissions)S(R);xe.overflow&&H(xe.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let cw=xe===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...xe.evidence?{gitSelection:xe.evidence}:{}},Ku=()=>({schema:"comet.native.content-snapshot.v1",origin:e.origin??"explicit",capture:cw,createdAt:(e.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}}:{}}),as=Ku();for(;Il(as)>i.maxManifestBytes;){if(m.filter(A=>!Rl(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T=0;T<A;T+=1){let D=mo(m);if(D===null)break;g(D)}}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");as=Ku()}return as}async function jl(t,e,i={}){let n=(await ot(t.projectRoot))?.native.snapshot??il;return dm(t,{...i,policy:e.policy,incrementalBaseline:e,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 wo(t,e){let i=GP(t,e),r=se(t,i);await W(r,i);try{let n=await Hh({root:r,file:i,maxBytes:aP,label:"Native baseline snapshot manifest"});return wi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as ux}from"crypto";import dx from"path";var De=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 yo,promises as Qe}from"node:fs";import Ze from"node:path";import{TextDecoder as ax}from"node:util";import tx from"path";var ZP=Hn(Jr(),1);var nO=4*1024*1024;var fm=(t,e)=>{let i=t[e];return i==null?null:String(i)};function un(t,e){let i=t[e];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return i}function ln(t,e){let i=un(t,e);if(tx.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return i}function ix(t){let e=t.run_retries??"{}",i;try{i=typeof e=="string"?JSON.parse(e):e}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 pm(t){if(!t.run_id)return null;let e=un(t,"run_id"),i=un(t,"skill"),r=un(t,"skill_version"),n=un(t,"skill_hash"),a=ln(t,"pending_ref"),o=ln(t,"trajectory_ref"),s=ln(t,"context_ref"),c=ln(t,"artifacts_ref"),l=ln(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:i,skillVersion:r,skillHash:n,orchestration:t.orchestration,currentStep:fm(t,"current_step"),iteration:u,pending:fm(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:ix(t)}}var ZO=256*1024;var rx=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function nx(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)},i=pm(e);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function $l(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Run state: stored value must be an object");let e=t,i=Object.keys(e).find(r=>!rx.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(e.currentStep!==null&&(typeof e.currentStep!="string"||e.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(e.pending!==null&&(typeof e.pending!="string"||e.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!e.retries||typeof e.retries!="object"||Array.isArray(e.retries))throw new Error("Invalid Run state: retries must be an object");return nx(e)}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 bo(t,e){let i=Ze.relative(t,e);return i===""||!Ze.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ze.sep}`)}function ox(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function No(t,e){return q({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}function sx(t,e){return q({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function ko(t,e,i){let r=De[e];if(i!==void 0&&i!==r)throw new Error(`Native Run ${e} ref must be ${r}`);let n=Ze.resolve(t),a=Ze.resolve(n,...r.slice(8).split("/"));if(!bo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function hm(t){let e=await Qe.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${t}`);return{path:t,realPath:await Qe.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function cx(t,e){let i=Ze.resolve(t),r=Ze.resolve(e);if(!bo(i,r))throw new Error("Native Run path is outside its change");let n=[await hm(i)],a=i;for(let o of Ze.relative(i,r).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s;try{s=await hm(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!bo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function mm(t){for(let e of t){let i=await Qe.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!sx(e,i)||await Qe.realpath(e.path)!==e.realPath)throw new Error(`Native Run parent changed during I/O: ${e.path}`)}}async function lx(t,e,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${i} exceeds ${e} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function So(t,e,i,r,n){let a=await cx(t,Ze.dirname(e));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Qe.lstat(e)}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=ox(o),c=await Qe.realpath(e);if(!bo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?yo.O_RDONLY:yo.O_RDONLY|yo.O_NOFOLLOW|yo.O_NONBLOCK,u;try{u=await Qe.open(e,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),Qe.lstat(e),Qe.realpath(e)]);if(await mm(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!No(s,d)||!No(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await lx(u,i,r);await n?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([u.stat(),Qe.lstat(e),Qe.realpath(e)]);if(await mm(a),!m.isFile()||m.isSymbolicLink()||b!==c||!No(s,p)||!No(s,m))throw new Error(`${r} changed while reading`);let N;try{N=new ax("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 vm(t,e){try{return JSON.parse(t)}catch(i){throw new Error(`${e} contains invalid JSON`,{cause:i})}}function Ol(t){return $l(t)}async function er(t,e){let i=ko(t,"stateRef"),r=await So(t,i,Zi.runStateBytes,"Native Run state",e);return r?$l(vm(r.text,"Native Run state")):null}async function yi(t,e,i){let r=ko(t,"trajectoryRef",e),n=await So(t,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 gm(t,e,i){return(await So(t,ko(t,"trajectoryRef",e),Zi.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Eo(t,e,i){let r=await So(t,ko(t,"checkpointRef",e),Zi.checkpointBytes,"Native Run checkpoint",i);return r?vm(r.text,"Native Run checkpoint"):null}var fx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Hl(t){return ux("sha256").update(t).digest("hex")}function px(t,e){if(!fx.test(e))throw new Error(`Invalid Native change name: ${e}`);return dx.join(G(t,e),"trajectory.jsonl")}function hx(t){let e=t.split(/\n/u),i=0;for(let r=0;r<e.length;r+=1){let n=e[r].endsWith("\r")?e[r].slice(0,-1):e[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 mx(t,e){if(/Unexpected end|Unterminated string/iu.test(t.message))return!0;let i=/position (\d+)/iu.exec(t.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,e.length-1)}function vx(t,e){let i=e.lastIndexOf(10),r=e.subarray(0,i+1),n=hx(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:t,line:n.line,message:n.message};if(i===e.length-1)return{status:"clean",file:t};let a=e.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([e,Buffer.from(`
157
+ `)])}catch(d){if(!mx(d,o))return{status:"invalid",file:t,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:t,reason:c,line:s,originalHash:Hl(e),targetHash:Hl(l),tailHash:Hl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function gx(t,e){let i=px(t,e);await W(se(t,i),i);let r=G(t,e),n=await gm(r,De.trajectoryRef);return n===null?{status:"clean",file:i}:vx(i,Buffer.from(n))}async function wm(t,e){let i=await gx(t,e);return"inspection"in i?i.inspection:i}import{createHash as yx}from"node:crypto";import{promises as Po}from"node:fs";import Pt from"node:path";var dn=/^[a-f0-9]{64}$/u,ym=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Nx=16*1024,Bl=process.platform,bx=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function tr(t){return bx.has(t)}function km(t,e){let i=Pt.relative(t,e);return Pt.isAbsolute(i)||i===".."||i.startsWith(`..${Pt.sep}`)?null:i.replaceAll("\\","/")||"."}function Sm(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function Em(t,e){if(t.length===0||Sm(t)||t.includes("\\")||Pt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let i=Pt.posix.normalize(t);if(i!==t||i===".."||i.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return i}function Fl(t,e){return yx("sha256").update(`${t}
158
+ ${e}`).digest("hex")}async function Nm(t,e){let i=await Po.realpath(e),r=await Po.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Bl==="win32"?Pt.normalize(i).toLowerCase():i;return Fl(t,`${n}
159
+ ${r.dev}
160
+ ${r.ino}
161
+ ${r.birthtimeMs}`)}async function bm(t,e){let i=await Po.realpath(e),r=await Po.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Bl==="win32"?Pt.normalize(i).toLowerCase():i;return Fl(t,n)}function kx(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function Dl(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Sm(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function Pm(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Dl(t.changeBranch,"Native workspace change branch"),Dl(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Sx(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(e).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!ym.test(e.baseCommit)||typeof e.targetCommit!="string"||!ym.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Dl(e.targetBranch,"Native workspace Git target branch")}function xo(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(e).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!dn.test(String(e.projectRootId))||!dn.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");kx(e.capturedAt),Em(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!dn.test(String(e.projectRootPathId))||a&&!dn.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!dn.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&Sx(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Pm(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function Ex(t,e){return Pt.join(G(t,e),"workspace.json")}function Px(t,e){let i=Ex(t,e),r=se(t,i),n=km(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Em(n,"Native workspace file ref")}}async function xx(t,e){try{let i=Px(t,e),r=await oe({root:i.root,ref:i.ref,maxBytes:Nx});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function xm(t,e){let i=We(t.projectRoot),r={projectRoot:Pt.resolve(t.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await xt(t,e);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 fn({paths:t,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 Cx(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=km(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let i=We(t.paths.projectRoot),r=i.isGitWorktree?Lc(t.paths.projectRoot,"HEAD"):null,n=t.binding?.targetBranch??i.currentBranch,a=n==null?null:Lc(t.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([Nm("comet.native.workspace-project-root.v2",t.paths.projectRoot),Nm("comet.native.workspace-native-root.v2",t.paths.nativeRoot),bm("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),bm("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),d=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&Pm(t.binding);let f={capturedAt:d,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:Fl("comet.native.workspace-session.v2",`${s}
162
+ ${c}
163
+ ${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...f,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...f};return xo(h),h}async function xt(t,e){let i=await xx(t,e);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(xo(i),i)}async function Co(t){xo(t.identity);let e=await Cx({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),i=[],r=[];return e.nativeRootRef!==t.identity.nativeRootRef&&i.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&i.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&i.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&i.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&i.push("native-root-legacy-identity")),Bl==="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 fn(t){if(xo(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Co(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=We(t.paths.projectRoot);return t.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!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:t.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 Cm(t,e){let i=await xt(t,e);if(i===null)return null;let r=await fn({paths:t,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var _m=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],_x=new Set(_m),Tm=new Set([..._m,"minimum_runtime_version","revision"]),Tx=new Set([...Tm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Ix=new Set(["capability","operation","source","base_hash"]),jx=new Set(["shape","build","verify","archive"]),$x=new Set(["implicit","confirmed"]),Ox=new Set(["pending","pass","fail"]),bi="comet-state.yaml",Ml=/^[a-f0-9]{64}$/u,Im=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hx=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ro=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"},Ni=class extends Error{constructor(i,r){super(i!==Nt||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"},Ao=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"},pn=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"},_o=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"},Y0=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
164
+ `);function mn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jm(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function vn(t){if(!Im.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Dx(t){if(!Im.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function $m(t,e){if(t.length===0||Xt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Bx(t,e){let i=mn(t,`spec_changes[${e}]`);if(jm(i,Ix,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Dx(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"&&$m(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"||!Ml.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"||!Ml.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 Fx(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Vl(t,e){if(jm(t,e,bi),typeof t.name!="string")throw new Error("Native change name is required");if(vn(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!jx.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!$x.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(Bx),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 t.verification_result!="string"||!Ox.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&$m(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!Fx(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Ji(t){let e=mn(t,bi);if(e.schema!==kt)throw new Error(`Expected ${kt}`);return{schema:kt,...Vl(e,_x)}}function hn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ll(t,e,i){if(t===null)return null;let r=typeof t=="string"?Hx.exec(t):null;if(!r||r[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function Lx(t){if(t==null)return null;if(typeof t!="string"||!Ml.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function Mx(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Gi(t){let e=mn(t,bi);if(e.schema!==bt)throw new Error(`Expected ${bt}`);if(hn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${bt} minimum_runtime_version must be 2`);return{schema:bt,minimum_runtime_version:2,revision:hn(e.revision,"Native v2 revision"),...Vl(e,Tm)}}function Gt(t){let e=mn(t,bi);if(e.schema!==Nt){if(e.schema===kt||e.schema===bt){let o=e.schema===kt?Ji(e):Gi(e);throw new Ro(o.name,o.schema)}throw new Ni(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=hn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ni(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let r=hn(e.revision,"Native revision"),n=Vl(e,Tx),a=Lx(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Nt,minimum_runtime_version:3,revision:r,verification_protocol:Mx(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Ll(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ll(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ll(e.partial_allowance,"Native partial_allowance","allowances")}}function qx(t){let e=mn(t,bi);if(e.schema===kt){let n=Ji(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Nt}`}}if(e.schema===bt){let n=Gi(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Nt}`}}if(e.schema!==Nt){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Ni(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let i=hn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Ni(e.schema,i).message};let r=Gt(e);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function pe(t,e){vn(e);let i=Xt.join(t.changesDir,e);if(!B(t.changesDir,i))throw new Error("Native change path escaped");return i}async function To(t,e){let i=G(t,e),r=Xt.join(i,"schema-migration.json");await W(B(t.runtimeDir,r)?t.runtimeDir:t.nativeRoot,r);try{return await Am.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Om(t,e){let i=G(t,e),r=Xt.join(i,"checkpoint-journal.json");await W(B(t.runtimeDir,r)?t.runtimeDir:t.nativeRoot,r);try{return await Am.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var Vx=256*1024;async function Wx(t,e=Xt.dirname(t)){let i=Xt.relative(e,t).split(Xt.sep).join("/"),r=await oe({root:e,ref:i,maxBytes:Vx}),n=(0,ql.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function Wl(t,e){let i=Xt.join(pe(t,e),bi);await W(t.nativeRoot,i);let r=qx(await Wx(i,t.nativeRoot));if(r.state&&r.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await To(t,e)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(r.status==="current"&&r.state&&await zx(t,r.state),r)}async function zx(t,e){if(await wo(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function dt(t,e){let i=await Wl(t,e);if(i.status==="migration-required")throw new Ro(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ni(i.schema,i.minimumRuntimeVersion);return await Cm(t,e),i.state}var Dm=["Outcome","Scope","Non-goals","Acceptance examples"],Jx=[...Dm,"Constraints and invariants","Decisions","Open questions","Verification expectations"],Gx=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Bm={maxFileBytes:Gr};function Fm(t){let e=new Map,i=null,r=[],n=()=>{i!==null&&e.set(i,r.join(`
165
+ `).trim())};for(let a of t.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),e}async function Ux(t,e){let i=Hm.resolve(t,...e.split(/[\\/]/u));if(!B(t,i))throw new Error(`Artifact escapes Native change: ${e}`);let r=await zl.realpath(t),n=await zl.realpath(i);if(!B(r,n))throw new Error(`Artifact symlink escapes Native change: ${e}`);if(!(await zl.stat(n)).isFile())throw new Error(`Artifact is not a file: ${e}`);return n}function gn(t){return{valid:t.length===0,findings:t}}async function Jl(t,e){let i=[],r;try{r=(await oe({root:t,ref:e,maxBytes:Bm.maxFileBytes})).text}catch(o){return gn([{code:"brief-missing",message:o.message,path:e}])}let n=Fm(r);for(let o of Jx)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:e});for(let o of Dm)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:e});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:e}),gn(i)}async function Gl(t,e){let i=[],r;try{r=(await oe({root:t,ref:e,maxBytes:Bm.maxFileBytes})).text}catch(a){return gn([{code:"verification-missing",message:a.message,path:e}])}let n=Fm(r);for(let a of Gx)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:e}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:e});return gn(i)}function Io(t,e){return Hm.join(t.specsDir,e,"spec.md")}async function Lm(t,e){let i=[],r=pe(t,e.name);for(let n of e.spec_changes){let a=Io(t,n.capability),o=null;try{await W(t.nativeRoot,a),o=await Sl(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 Ux(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return gn(i)}import Mm from"node:path";var Kx="comet.native.contract.v1",Yx="comet.native.acceptance-set.v1",qm=/^[a-f0-9]{64}$/u,wn={maxAcceptanceCriteria:tn.maxCriteria};function Vm(t,e){let i=Mm.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Mm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized project-relative ref`);return t}function Wm(t){return F("comet.native.contract-content.v1",t.replace(/\r\n?/gu,`
166
+ `))}function Xx(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.capability))throw new Error(`Invalid Native contract capability: ${t.capability}`);if(t.operation!=="create"&&t.operation!=="replace"&&t.operation!=="remove")throw new Error(`Invalid Native contract operation for ${t.capability}`);if(t.operation==="remove"){if(t.source!==null||t.markdown!==null||!t.baseHash?.match(qm))throw new Error(`Remove contract ${t.capability} requires only a base hash`);return{snapshot:{capability:t.capability,operation:"remove",source:null,baseHash:t.baseHash,contentHash:null},markdown:null}}if(t.source===null||t.markdown===null)throw new Error(`${t.operation} contract ${t.capability} requires source content`);if(t.operation==="create"&&t.baseHash!==null)throw new Error(`Create contract ${t.capability} requires a null base hash`);if(t.operation==="replace"&&!t.baseHash?.match(qm))throw new Error(`Replace contract ${t.capability} requires a base hash`);let e=Vm(t.source,`Contract source for ${t.capability}`);return{snapshot:{capability:t.capability,operation:t.operation,source:e,baseHash:t.baseHash,contentHash:Wm(t.markdown)},markdown:t.markdown}}function Qx(t,e){return zm(t.id,e.id)}function zm(t,e){return t<e?-1:t>e?1:0}function Jm(t){let e=Vm(t.briefSource??"brief.md","Native brief source"),i=t.specs.map(Xx).sort((d,f)=>zm(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=[e,...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=dl(t.briefMarkdown,e,wn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...fl(f,d.source,wn.maxAcceptanceCriteria-a.length)),a.push(...pl(f,d.source,wn.maxAcceptanceCriteria-a.length)));if(a.sort(Qx),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:e,contentHash:Wm(t.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=F(Yx,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:F(Kx,u)}}var jo={maxSpecs:64,maxFileBytes:Gr,maxTotalBytes:4*1024*1024};async function ir(t){if(t.specChanges.length>jo.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let e=await oe({root:t.changeDir,ref:t.briefRef,maxBytes:jo.maxFileBytes}),i=e.size,r=[];for(let n of t.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 oe({root:t.changeDir,ref:n.source,maxBytes:jo.maxFileBytes});if(i+=a.size,i>jo.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:Jm({briefSource:e.ref,briefMarkdown:e.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{randomUUID as Zx}from"crypto";import{promises as $o}from"fs";import Um from"path";var Ul="comet.selection.v2",eC=16*1024;function Kl(t){return Um.join(t,".comet","current-change.json")}function tC(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Gm(t){return t===null||typeof t=="string"}function Km(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!tC(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!Gm(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ul,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Ul)throw new Error(`current change selection schema must be ${Ul}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!Gm(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function Ym(t){let e;try{let r=Kl(t),{bytes:n}=await mi(r,eC,{label:"current change selection"});e=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",...Km(e)}}async function Xm(t,e){let i=Km(JSON.stringify(e));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=Kl(t),n=`${r}.${Zx()}.tmp`;await $o.mkdir(Um.dirname(r),{recursive:!0});try{await $o.writeFile(n,`${JSON.stringify(i.selection,null,2)}
167
+ `,"utf8"),await $o.rename(n,r)}catch(a){throw await $o.rm(n,{force:!0}),a}}import{promises as yC}from"node:fs";import Ql from"node:path";var gH=["$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 iC=/\b(Bearer|Basic)\s+[^\s"']+/giu,rC=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,nC=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,aC=/\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,oC=/("(?:[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,sC=/(["'])((?:[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,cC=/\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 Be(t){return t.replace(iC,"$1 [REDACTED]").replace(rC,"[REDACTED PRIVATE KEY]").replace(nC,"$1[REDACTED]@").replace(aC,"[REDACTED TOKEN]").replace(oC,'$1"[REDACTED]"').replace(sC,"$1$2$1$3$4[REDACTED]$4").replace(cC,"$1$2[REDACTED]")}import{promises as hC}from"node:fs";import Qm from"node:path";function Oo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ho(t,e,i){let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ft(t,e,i=!1){if(typeof t!="string"||!i&&t.length===0)throw new Error(`${e} must be ${i?"a string":"a non-empty string"}`);return t}function Zm(t,e){return t===null?null:ft(t,e)}function Bo(t,e,i=0){if(!Number.isSafeInteger(t)||t<i)throw new Error(`${e} must be a safe integer greater than or equal to ${i}`);return t}function mC(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function vC(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function Do(t,e,i){if(typeof t!="string"||!e.includes(t))throw new Error(`${i} must be one of: ${e.join(", ")}`);return t}function Yl(t,e){if(t===null)return null;let i=ft(t,e);if(Number.isNaN(Date.parse(i)))throw new Error(`${e} must be an ISO timestamp`);return i}function Xl(t,e){let i=ft(t,e);if(!Qm.isAbsolute(i))throw new Error(`${e} must be absolute`);return Qm.resolve(i)}function gC(t,e){let i=`Native local checks[${e}]`,r=Oo(t,i);if(Ho(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)=>ft(l,`${i}.argv[${u}]`,!0)),a=Do(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Yl(r.startedAt,`${i}.startedAt`),s=Yl(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=Bo(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:ft(r.id,`${i}.id`),name:ft(r.name,`${i}.name`),operationId:ft(r.operationId,`${i}.operationId`),status:a,repeatable:vC(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Bo(r.executionCount,`${i}.executionCount`),argv:n,cwd:Xl(r.cwd,`${i}.cwd`),exitCode:mC(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:ft(r.log,`${i}.log`)}}function wC(t){let e="Native local execution state",i=Oo(t,e);if(Ho(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),i.schema!==ro)throw new Error(`Native local execution schema must be ${ro}`);let r=Oo(i.workspace,"Native local workspace");Ho(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Oo(i.execution,"Native local execution");Ho(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Yl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:ft(o.operationId,"Native local execution.operationId"),stage:Do(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Do(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Zm(o.executionId,"Native local execution.executionId"),status:Do(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Bo(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(gC);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:ro,change:ft(i.change,"Native local change"),basedOnStateVersion:Bo(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Xl(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Xl(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Zm(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function ev(t){let e;try{e=await hC.readFile(t,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(e)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return wC(i)}var NC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bC="comet-state.yaml",kC="state.json";function tv(t,e){if(!NC.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=Ql.join(t.changesDir,e);if(!B(t.changesDir,i))throw new Error("Native change path escaped");return i}function iv(t,e){return Ql.join(tv(t,e),bC)}function SC(t,e){return Ql.join(Li(t,e),kC)}async function Fo(t,e){try{let i=await yC.readFile(iv(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Zl(t,e){return Sh(iv(t,e))}async function rv(t){let e=await Zl(t.paths,t.name),i=SC(t.paths,t.name);try{let r=await ev(i);return r===null?{state:e,local:null,localStatus:"missing"}:r.change!==e.name||r.basedOnStateVersion!==e.state_version?{state:e,local:null,localStatus:"stale"}:{state:e,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:e,local:null,localStatus:"missing"}:{state:e,local:null,localStatus:"invalid"}}}var zD=16*1024;async function nv(t){let e=await Ym(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(vn(e.selection.change),e.selection)}async function av(t,e){return lt(t,`select change ${e}`,async()=>{vn(e),await Fo(t,e)?await Zl(t,e):await dt(t,e),await Xm(t.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:e,branch:null})})}async function ov(t,e){let i=[],r=G(t,e.name),n=Jt(r,De.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(e.run_id!==null||e.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(e.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==e.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${e.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!==e.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${e.phase}`,path:n});let o=Jt(r,a.trajectoryRef),s=await wm(t,e.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 yi(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=Jt(r,a.checkpointRef);try{let u=await Eo(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 mR from"path";import{isDeepStrictEqual as yu}from"util";var rr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var EC=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function PC(t,e){return t<e?-1:t>e?1:0}function xC(t,e,i,r){if(!Array.isArray(t)||t.length>i||!r&&t.length===0)throw new Error(`${e} exceeds its count boundary`);let n=t.map(a=>{if(typeof a!="string"||!EC.test(a))throw new Error(`${e} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(PC)}function eu(t=[]){return xC(t,"Native repair failed check IDs",rr.maxFailedCheckIds,!0)}function sv(t,e){let i=new Set(e);return t.every(r=>i.has(r))}function CC(t,e){return t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0||e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0?t.signatureHash!==e.signatureHash:sv(t.failedAcceptanceIds,e.failedAcceptanceIds)&&sv(t.failedCheckIds,e.failedCheckIds)&&(t.failedAcceptanceIds.length<e.failedAcceptanceIds.length||t.failedCheckIds.length<e.failedCheckIds.length)}function tu(t,e){let i=1,r=t;for(let n=e.length-1;n>=0;n-=1){let a=e[n];if(CC(r,a))break;i+=1,r=a}return i}import Cv from"node:path";import{createHash as mv}from"node:crypto";import cv from"path";var iu="comet.native.implementation-scope.v2",vv="comet.native.content-snapshot-projection.v1",yn="comet.native.content-snapshot-projection.v1",gv="comet.native.implementation-scope.v2",RC="comet.native.unresolved-scope-id.v1",AC="comet.native.scope-detail-overflow.v1",_C="comet.native.snapshot-projection-overflow.v2",ou=/^[a-f0-9]{64}$/u,Si=1024*1024,TC=128,IC=128;function he(t,e){return t<e?-1:t>e?1:0}function ru(t){if(!ou.test(t))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${t}.json`}function jC(t,e){return t===e?0:t===null?-1:e===null?1:he(t,e)}function Zt(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.endsWith("/")||/^[a-zA-Z]:/u.test(t))throw new Error(`${e} must be a normalized project-relative path`);let i=cv.posix.normalize(t);if(i!==t||i==="."||i===".."||i.startsWith("../")||cv.posix.isAbsolute(i))throw new Error(`${e} must stay inside the project root`);return t}function wv(t,e){return t==="."?t:Zt(t,e)}function nr(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative safe integer`);return t}function $C(t,e){if(t.type!=="file")throw new Error(`${e} must describe a file`);if(typeof t.hash!="string"||t.hash.length===0)throw new Error(`${e} hash must be non-empty`);return{path:Zt(t.path,`${e} path`),hash:t.hash,size:nr(t.size,`${e} size`),type:"file"}}function OC(t,e){return{path:wv(t.path,`${e} path`),size:t.size===null?null:nr(t.size,`${e} size`),type:t.type,reason:t.reason}}function HC(t,e){return he(t.path,e.path)||he(t.hash,e.hash)||t.size-e.size}function DC(t,e){return he(t.path,e.path)||he(t.reason,e.reason)||he(t.type,e.type)||(t.size??-1)-(e.size??-1)}function bn(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
168
+ `,"utf8")}function Qt(t,e,i){let r=`${e}
169
+ ${en(i)}`;t.update(`${Buffer.byteLength(r,"utf8")}:`),t.update(r)}function BC(t){if(bn(t)<=Si)return t;let e=[...t.entries],i=[...t.omitted],r=t.omittedCount,n=t.omissionOverflow?.count??0,a=mv("sha256");a.update(`${_C}
170
+ `),t.omissionOverflow&&Qt(a,"existing-overflow",t.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Qt(a,"omission",f)},s=f=>{r+=1,n+=1,Qt(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=()=>({...t,complete:r===0,entries:e,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;bn(u)>Si;){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(e.length>0){let h=Math.max(1,Math.ceil(e.length/4));for(let v of e.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 nu(t){let e=wi(t),i=e.entries.map((n,a)=>$C(n,`Snapshot entry ${a}`));if(i.sort(HC),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=e.omitted.map((n,a)=>OC(n,`Snapshot omission ${a}`));return r.sort(DC),BC({schema:vv,origin:e.origin,...e.capture?{capture:e.capture}:{},complete:e.complete,limits:{maxFiles:e.limits.maxFiles,maxFileBytes:e.limits.maxFileBytes,maxTotalBytes:e.limits.maxTotalBytes,maxManifestBytes:e.limits.maxManifestBytes,...e.limits.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},...e.policy?{policy:e.policy}:{},entries:i,omitted:r,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:{ref:e.omissionOverflow.ref,hash:e.omissionOverflow.hash,count:e.omissionOverflow.count}}:{}})}function kn(t){let e=new Map;for(let[i,r]of t.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:Zt(r.path,`Declared artifact ${i} path`),kind:r.kind},a=e.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);e.set(n.path,n)}return[...e.values()].sort((i,r)=>he(i.path,r.path)||he(i.kind,r.kind))}function Sn(t,e){return t.kind==="file"?t.path===e:e===t.path||e.startsWith(`${t.path}/`)}function lv(t){return t?{hash:t.hash,size:t.size}:null}function su(t,e,i){let r=0,n=0;for(;r<t.entries.length||n<e.entries.length;){let a=t.entries[r],o=e.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&&!e.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:lv(c),after:lv(l)})}}function yv(t,e){return{...t,attributedTo:e.filter(i=>Sn(i,t.path))}}function cu(t){let e=kn(t.declaredArtifacts),i=[];return su(t.baseline,t.current,r=>{i.push(yv(r,e))}),i}function Ct(t,e){return{id:`scope:${F(RC,t)}`,kind:t.kind,source:t.source,path:t.path,reason:e}}function FC(t,e){let i=e.omitted.map(r=>Ct({kind:"snapshot-omission",source:t,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${t} snapshot omitted ${r.path}: ${r.reason}`));return e.complete||i.push(Ct({kind:"snapshot-incomplete",source:t,path:null,evidence:{omittedCount:e.omittedCount}},`${t} snapshot is incomplete`)),e.omissionOverflow&&i.push(Ct({kind:"snapshot-omission-overflow",source:t,path:null,evidence:{count:e.omissionOverflow.count,hash:e.omissionOverflow.hash,ref:e.omissionOverflow.ref}},`${t} snapshot has ${e.omissionOverflow.count} unlisted omissions`)),i}function uv(t,e){return FC(t,{...e,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function au(t,e){return he(t.kind,e.kind)||he(t.source,e.source)||jC(t.path,e.path)||he(t.id,e.id)}function LC(t){return[...new Map(t.map(i=>[i.id,i])).values()].sort(au)}function Nv(t){return[...new Set(t.map((e,i)=>Zt(e,`Git path ${i}`)))].sort(he)}function dv(t,e){if(typeof t!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(t))throw new Error(`${e} must be a Git commit object id`);return t}function MC(t,e){if(typeof t!="string"||t.length===0||t.trim()!==t||t.includes("\\")||t.includes("\0")||t.startsWith("-"))throw new Error(`${e} must be a valid Git branch name`);return t}function bv(t){if(!t||t.provider!=="git")throw new Error("Native external drift provider is invalid");let e=Nv(t.paths);if(e.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:dv(t.baseCommit,"Native external drift base commit"),targetBranch:MC(t.targetBranch,"Native external drift target branch"),targetCommit:dv(t.targetCommit,"Native external drift target commit"),paths:e}}function kv(t){if(typeof t.contractHash!="string"||!ou.test(t.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:t.contractHash,declaredArtifacts:kn(t.declaredArtifacts),noCodeReason:t.noCodeReason?.trim()||null,...t.gitChangedPaths===void 0?{}:{gitChangedPaths:Nv(t.gitChangedPaths)},...t.externalDrift===void 0?{}:{externalDrift:bv(t.externalDrift)}}}function qC(t,e,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return su(t,e,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<TC){let p=yv(h,i),m=bn(p);l+m<=Si?(a.push(p),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Sv(t,e){return Ct({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:e.changes,hash:t,unattributedCount:e.unattributed,unresolvedCount:e.unresolved}},`Implementation scope summarized ${e.changes} additional change details and ${e.unresolved} unresolved details (${e.unattributed} unattributed); overflow hash ${t}`)}function VC(t){let e=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(t.reason);if(!e)throw new Error("Implementation scope detail overflow is invalid");let i={changes:nr(Number(e[1]),"Scope overflow change count"),unresolved:nr(Number(e[2]),"Scope overflow unresolved count"),unattributed:nr(Number(e[3]),"Scope overflow unattributed count")},r=ki(e[4],"Scope detail overflow hash");if(JSON.stringify(t)!==JSON.stringify(Sv(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function WC(t){let e=mv("sha256");e.update(`${AC}
171
+ `);let i=0;su(t.baseline,t.current,n=>{if(i>=t.detailedChangeCount){Qt(e,"change",n);let a=0;for(let o of t.declaredArtifacts)Sn(o,n.path)&&(a+=1,Qt(e,"change-attribution",o));Qt(e,"change-end",{attributionCount:a}),a===0&&Qt(e,"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",t.baseline],["current",t.current]])for(let o of a.omitted)r>=t.detailedOmissionCount&&Qt(e,"snapshot-omission",{source:n,...o}),r+=1;return e.digest("hex")}function Ev(t,e,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=qC(t,e,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(H=>Sn(H,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=F(yn,t),c=F(yn,e),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,w]of[["baseline",t],["current",e]])for(let g of w.omitted){if(l.length>=IC)break;l.push(Ct({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=t.omitted.length+e.omitted.length,f=[...uv("baseline",t),...uv("current",e),...o.totalChanges===0&&a===null?[Ct({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(Me=>Me.attributedTo.length===0&&!u.has(Me.path)),S=o.totalChanges-w.length,H=o.totalUnattributed-g.length,I=d-x.detailedOmissionCount,ue=H+I,X=[...g.map(Me=>Ct({kind:"unattributed-change",source:"implementation-scope",path:Me.path,evidence:{after:Me.after,before:Me.before,changeKind:Me.kind}},`Changed path is not covered by a declared artifact: ${Me.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...ue>0?[Sv(x.overflowHash,{changes:S,unattributed:H,unresolved:ue})]:[]],J=LC(X),it=x.includeGitAdvisory?h():void 0;return{schema:iu,contractHash:r,baselineProjectionRef:ru(s),baselineProjectionHash:s,currentProjectionRef:ru(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:J,noCodeReason:a,...it?{gitAdvisory:it}:{},...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})<=Si)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?WC({baseline:t,current:e,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:m}):N,E=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:k}),y={...E,scopeHash:F(gv,E)};if(bn(y)>Si)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return y}function lu(t){let e=nu(t.baseline),i=nu(t.current),r=kv(t);return{authority:r,baseline:e,current:i,scope:Ev(e,i,r)}}var zC=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function pt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ht(t,e,i,r){let n=new Set([...e,...i]),a=Object.keys(t).filter(s=>!n.has(s)),o=e.filter(s=>!(s in t));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 ki(t,e){if(typeof t!="string"||!ou.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function fv(t,e,i){let r=ru(e);if(t!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Lo(t,e){let i=pt(t,"Native snapshot projection");if(ht(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==vv)throw new Error("Native snapshot projection schema is invalid");let r=wi({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=nu(r);if(F(yn,i)!==F(yn,n))throw new Error("Native snapshot projection is not canonical");let a=F(yn,n);if(e!==void 0&&ki(e,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function uu(t,e){let i=pt(t,`Declared artifact ${e}`);if(ht(i,["path","kind"],[],`Declared artifact ${e}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${e} kind is invalid`);return{path:Zt(i.path,`Declared artifact ${e} path`),kind:i.kind}}function pv(t,e){if(t===null)return null;let i=pt(t,e);return ht(i,["hash","size"],[],e),{hash:ki(i.hash,`${e} hash`),size:nr(i.size,`${e} size`)}}function hv(t,e){let i=pt(t,`Implementation change ${e}`);if(ht(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${e}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${e} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${e} attributedTo must be an array`);let r=i.attributedTo.map(uu),n=kn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${e} attribution must be sorted and unique`);let a=pv(i.before,`Implementation change ${e} before`),o=pv(i.after,`Implementation change ${e} 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 ${e} before/after state is invalid`);return{path:Zt(i.path,`Implementation change ${e} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function JC(t,e){let i=pt(t,`Unresolved scope ${e}`);ht(i,["id","kind","source","path","reason"],[],`Unresolved scope ${e}`);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 ${e} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${e} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${e} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${e} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${e} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?wv(i.path,`Unresolved scope ${e} path`):Zt(i.path,`Unresolved scope ${e} path`),reason:i.reason}}function Nn(t,e){if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error(`${e} must be an array of paths`);let i=t.map((n,a)=>Zt(n,`${e} ${a}`)),r=[...new Set(i)].sort(he);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${e} must be sorted and unique`);return i}function Pv(t){let e=pt(t,"Native implementation external drift");if(ht(e,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),e.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Nn(e.paths,"Native external drift paths");return bv({provider:"git",baseCommit:e.baseCommit,targetBranch:e.targetBranch,targetCommit:e.targetCommit,paths:i})}function Mo(t){let e=pt(t,"Native implementation scope"),i=[...zC].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(ht(e,i,["gitAdvisory","externalDrift"],"Native implementation scope"),e.schema!==iu)throw new Error("Native implementation scope schema is invalid");let r=ki(e.contractHash,"Implementation scope contractHash"),n=ki(e.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=fv(e.baselineProjectionRef,n,"Implementation scope baseline projection"),o=ki(e.currentProjectionHash,"Implementation scope currentProjectionHash"),s=fv(e.currentProjectionRef,o,"Implementation scope current projection");if(typeof e.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(e.declaredArtifacts)||!Array.isArray(e.changes)||!Array.isArray(e.unattributed)||!Array.isArray(e.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=e.declaredArtifacts.map(uu);if(JSON.stringify(c)!==JSON.stringify(kn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=e.changes.map(hv),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=e.unattributed.map(hv),h=e.externalDrift===void 0?void 0:Pv(e.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=e.unresolvedScopes.map(JC),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:VC(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=e.noCodeReason,k=[...p.map(g=>Ct({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?[Ct({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(au))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(k.sort(au))||e.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let y;if(e.gitAdvisory!==void 0){let g=pt(e.gitAdvisory,"Implementation scope Git advisory");if(ht(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"),H=Nn(g.pathsPresentInSnapshotChanges,"Git present paths"),I=Nn(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),ue=[...H,...I].sort(he);if(JSON.stringify(ue)!==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:H,pathsAbsentFromSnapshotChanges:I}}let x={schema:iu,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:e.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:P,...y?{gitAdvisory:y}:{},...h?{externalDrift:h}:{}},w=ki(e.scopeHash,"Implementation scope scopeHash");if(F(gv,x)!==w)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:w}}function GC(t){let e=pt(t,"Native implementation scope authority");if(ht(e,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(e.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=e.declaredArtifacts.map(uu);if(JSON.stringify(i)!==JSON.stringify(kn(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;e.gitChangedPaths!==void 0&&(r=Nn(e.gitChangedPaths,"Native implementation scope authority Git paths"));let n=e.externalDrift===void 0?void 0:Pv(e.externalDrift),a=kv({contractHash:e.contractHash,declaredArtifacts:i,noCodeReason:e.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==e.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function En(t){let e=pt(t,"Native implementation scope bundle");ht(e,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=GC(e.authority),r=Lo(e.baseline),n=Lo(e.current),a=Mo(e.scope),o=Ev(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 xv(t){let e=Mo(t.scope);return En({authority:{contractHash:e.contractHash,declaredArtifacts:e.declaredArtifacts,noCodeReason:e.noCodeReason,...e.gitAdvisory?{gitChangedPaths:e.gitAdvisory.changedPaths}:{},...e.externalDrift?{externalDrift:e.externalDrift}:{}},baseline:t.baseline,current:t.current,scope:e})}var Av=/^[a-f0-9]{64}$/u;var UC="comet.native.acceptance-trace.v2",KC="comet.native.partial-allowance.v1",YC="comet.native.verification-evidence.v2";function Rt(t,e){if(!Av.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function _v(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native evidence source revision must be a positive integer");return t}function Tv(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native evidence change name: ${t}`);return t}function du(t,e,i=2e3){let r=Be(t).trim();if(r.length===0||r.length>i)throw new Error(`${e} must be between 1 and ${i} characters`);return r}function Pn(t,e){let i=Cv.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Cv.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized relative ref`);return t}function XC(t,e,i){let r=Pn(t,e);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=at(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(`${e} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function fu(t){let e=Pn(t,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(e))throw new Error("Verification receipt ref must identify a typed v3 receipt");return e}function ar(t,e){return t<e?-1:t>e?1:0}function qo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Vo(t,e,i){let r=new Set(e),n=Object.keys(t).filter(o=>!r.has(o)),a=e.filter(o=>!(o in t));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 Iv(t,e){if(typeof t!="string")throw new Error(`${e} is invalid`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} is invalid`);return t}function Rv(t,e,i){if(typeof t!="string")throw new Error(`Native ${e} evidence ref is invalid`);let r=`runtime/evidence/${e}/${i}.json`;if(t!==r)throw new Error(`Native ${e} evidence ref/hash mismatch`);return t}function QC(t){let e=qo(t,"Native acceptance trace");if(Vo(e,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),e.schema!=="comet.native.acceptance-trace.v2"||typeof e.nativeRootRef!="string"||typeof e.criteriaHash!="string"||!Av.test(e.criteriaHash)||!Number.isSafeInteger(e.total)||!Number.isSafeInteger(e.evidenced)||!Number.isSafeInteger(e.skipped)||!Array.isArray(e.entries))throw new Error("Native acceptance trace is invalid");let i=Pn(e.nativeRootRef,"Native root ref"),r=e.entries.map((o,s)=>{let c=qo(o,`Native acceptance trace entry ${s}`);if(Vo(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=>fu(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:du(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||e.total!==r.length||e.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||e.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:e.criteriaHash,total:e.total,evidenced:e.evidenced,skipped:e.skipped,entries:r},a=Rt(e.traceHash,"Native acceptance trace hash");if(F(UC,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function jv(t){let e=qo(t,"Native partial allowance");if(Vo(e,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),e.schema!=="comet.native.partial-allowance.v1"||typeof e.change!="string"||typeof e.scopeHash!="string"||!Array.isArray(e.scopeIds)||e.scopeIds.length===0||e.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(e.scopeIds)!==JSON.stringify([...new Set(e.scopeIds)].sort(ar))||typeof e.reason!="string"||typeof e.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Tv(e.change),scopeHash:Rt(e.scopeHash,"Native partial allowance scopeHash"),scopeIds:e.scopeIds,reason:du(e.reason,"Partial allowance reason"),confirmedSummary:du(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:_v(e.sourceRevision),confirmedAt:Iv(e.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==e.reason||i.confirmedSummary!==e.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Rt(e.allowanceHash,"Native partial allowance hash");if(F(KC,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function pu(t){let e=qo(t,"Native verification evidence");if(Vo(e,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),e.schema!=="comet.native.verification-evidence.v2"||typeof e.change!="string"||e.result!=="pass"&&e.result!=="fail"||e.freshness!=="complete"&&e.freshness!=="partial"||typeof e.implementationScopeHash!="string"||typeof e.reportRef!="string"||!Array.isArray(e.requiredReceiptRefs)||!Array.isArray(e.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Rt(e.implementationScopeHash,"Native verification implementation scope hash"),r=QC(e.acceptanceTrace),n=Rt(e.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=e.partialAllowanceRef!==null||e.partialAllowanceHash!==null;if(e.partialAllowanceRef===null!=(e.partialAllowanceHash===null)||e.freshness==="complete"&&a||e.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=e.partialAllowanceHash===null?null:Rt(e.partialAllowanceHash,"Native verification allowance hash"),s=e.receiptRefs.map(f=>fu(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=e.requiredReceiptRefs.map(f=>fu(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ar)))throw new Error("Native required receipt refs must be canonical");if(e.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Tv(e.change),sourceRevision:_v(e.sourceRevision),result:e.result,freshness:e.freshness,contractHash:Rt(e.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Rv(e.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:XC(e.reportRef,"Native verification report ref"),reportHash:Rt(e.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Rv(e.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Iv(e.createdAt,"Native verification timestamp")},d=Rt(e.envelopeHash,"Native verification envelope hash");if(F(YC,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function hu(t,e){if(typeof t!="string"||t.trim().length===0||t.length>4096)throw new Error(`${e} must be between 1 and 4096 characters`)}var $v="repairStagnation",_e={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},eR=/^[a-f0-9]{64}$/u;var tR=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),iR=["data","runId","sequence","timestamp","type"],Ov=["disposition","overrideSummaryHash","signatureHash"],rR=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Hv=12;function vu(t,e){return t<e?-1:t>e?1:0}function Dv(t,e,i){let r=Object.keys(t).sort(vu);if(r.length!==e.length||r.some((n,a)=>n!==e[a]))throw new Error(`${i} fields are invalid`)}function Wo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function xn(t,e){if(typeof t!="string"||!eR.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function nR(t){if(!Array.isArray(t)||t.length>rr.maxFailedAcceptanceIds||t.some(e=>typeof e!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(e)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(t)].sort(vu)}function Bv(t){if(typeof t!="string"||t.length===0||t.length>_e.maxRunIdCharacters||Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return t}function mu(t,e,i,r,n=!1){if(i.nodes+=1,i.nodes>_e.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(e>_e.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(t===null||typeof t=="boolean")){if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`${r} contains a non-finite number`);return}if(typeof t=="string"){if(t.length>_e.maxTextCharacters&&(!n||t.length>_e.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=t.length,i.characters>_e.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof t!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(t))throw new Error(`${r} contains a cycle`);i.ancestors.add(t);try{if(Array.isArray(t)){if(t.length>_e.maxArrayEntries)throw new Error(`${r} contains an oversized array`);t.forEach((s,c)=>mu(s,e+1,i,`${r}[${c}]`));return}let a=Wo(t,r),o=Object.keys(a);if(o.length>_e.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>_e.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>_e.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");mu(a[s],e+1,i,`${r}.${s}`,e===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(t)}}}function aR(t){if(typeof t!="string"||t.length>64)throw new Error("Native repair trajectory timestamp is invalid");let e=new Date(t);if(!Number.isFinite(e.valueOf())||e.toISOString()!==t)throw new Error("Native repair trajectory timestamp is invalid");return t}function oR(t,e,i){let r=Wo(t,`Native repair trajectory event ${e+1}`);if(Dv(r,iR,`Native repair trajectory event ${e+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==e+1)throw new Error("Native repair trajectory sequence is invalid");if(aR(r.timestamp),typeof r.type!="string"||!tR.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Bv(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 mu(r.data,0,n,"Native trajectory event data"),Wo(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function gu(t){let e=Wo(t,"Native repair trajectory projection"),i=Object.keys(e).sort(vu),r=i.length===Ov.length&&i.every((l,u)=>l===Ov[u]);r||Dv(e,rR,"Native repair trajectory projection");let n=xn(e.signatureHash,"Native repair trajectory signature hash");if(e.disposition!=="continue"&&e.disposition!=="warn"&&e.disposition!=="manual-stop"&&e.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=e.overrideSummaryHash===null?null:xn(e.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&e.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:e.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=xn(e.contractHash,"Native repair trajectory contract hash"),s=nR(e.failedAcceptanceIds),c=eu(e.failedCheckIds);if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:e.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:e.maxVerifyFailures}}function sR(t,e){if(e.overrideSummaryHash===null){if(t.previousPhase!=="verify"||t.nextPhase!=="build"||t.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(e.disposition!=="continue"||t.previousPhase!=="build"||t.nextPhase!=="verify"||t.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function cR(t,e){let i=e.filter(s=>s.kind==="failure"),r=i.length+1,n=t.maxVerifyFailures??Hv;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=tu({signatureHash:t.signatureHash,...t.contractHash===null?{}:{failedAcceptanceIds:t.failedAcceptanceIds,failedCheckIds:t.failedCheckIds}},i),o=r>=n?"hard-stop":a<rr.warningAtConsecutiveFailures?"continue":a<rr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(t.disposition!==o||t.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function lR(t,e,i){let r=e.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??Hv;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==t.signatureHash||r.at(-1)?.signatureHash!==t.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(e.some(a=>a.kind==="override"&&a.signatureHash===t.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Fv(t){if(!Array.isArray(t.trajectory)||t.trajectory.length>_e.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let e=Bv(t.runId);if(!Number.isSafeInteger(t.committedTrajectoryOffset)||t.committedTrajectoryOffset<0||t.committedTrajectoryOffset>t.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<t.committedTrajectoryOffset;l+=1){let u=oR(t.trajectory[l],l,e),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>_e.maxTotalDataNodes||c>_e.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,$v)){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=gu(f[$v]);if(sR(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),cR(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");lR(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 Lv(t){return Fv(t).history}function Mv(t){let e=Fv(t).latestProjection;return e?{...e}: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:[]},wu=U("comet-native-runtime:v3:scope-reopen"),uR=[{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 qv(t){return t.skillVersion===or.definition.metadata.version&&t.skillHash===wu||uR.some(e=>e.skillVersion===t.skillVersion&&e.skillHash===t.skillHash)}function Vv(t){return U(JSON.stringify({summary:t.summary,returnToBuild:t.returnToBuild??!1,confirmed:t.confirmed??!1,artifacts:[...t.artifacts??[]].sort(),noCodeReason:t.noCodeReason??null,verificationResult:t.verificationResult??null,verificationReport:t.verificationReport??null,allowPartialScopeHash:t.allowPartialScopeHash??null,partialReason:t.partialReason??null,repairOverrideSignature:t.repairOverrideSignature??null,repairOverrideSummary:t.repairOverrideSummary??null}))}var Uv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],vR=new Set(Uv),Kv=new Set([...Uv,"minimum_runtime_version","revision"]),gR=new Set([...Kv,"operation"]),wR=512*1024,Nu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),yR=new Set([...Nu,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),bu=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 Su(t,e){return mR.join(G(t,e),"transition.json")}function Jo(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal must be an object");return t}function Eu(t,e){let i=Object.keys(t).find(r=>!e.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function zo(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ku(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal event data is invalid");let i=t,r=Object.keys(i),n=r.find(u=>!yR.has(u)),a=[...Nu].find(u=>!Object.hasOwn(i,u)),o=Nu.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!==e)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(hu(i.summary,"Native transition journal event summary"),Be(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&&(hu(i.noCodeReason,"Native transition journal event no-code reason"),Be(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")?gu(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:e,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 NR(t,e){if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,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 ku({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},e)}return ku(t,e)}function Pu(t,e,i=!1){if(t.change!==e)throw new Error("Native transition journal change mismatch");if(typeof t.id!="string"||t.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof t.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(t.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?NR(t.eventData,t.evidenceHash):ku(t.eventData,t.evidenceHash),n=Ol(t.nextRun),a=t.previousRun===null?null:Ol(t.previousRun);return{id:t.id,evidenceHash:t.evidenceHash,createdAt:t.createdAt,previousRun:a,nextRun:n,eventData:r}}function Wv(t,e,i=!1){if(t.skill!==or.definition.metadata.name||(i?!qv(t):t.skillVersion!==or.definition.metadata.version||t.skillHash!==wu)||t.orchestration!==or.definition.orchestration.mode||t.pendingRef!==De.pendingRef||t.trajectoryRef!==De.trajectoryRef||t.contextRef!==De.contextRef||t.artifactsRef!==De.artifactsRef||t.checkpointRef!==De.checkpointRef)throw new Error(`Native transition journal ${e} metadata or storage refs are invalid`)}function zv(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,retries:t.retries}}function Jv(t,e){if(t.status!=="running")throw new Error(`Native transition journal ${e} status must be running`);if(t.pending!==null)throw new Error(`Native transition journal ${e} pending action must be null`)}function xu(t,e,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Wv(o,"next Run",r||a!==null),Jv(o,"next Run"),o.runId!==e.run_id||o.currentStep!==e.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||t.phase==="shape"||e.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(t.run_id!==null||t.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Wv(a,"previous Run",!0),Jv(a,"previous Run"),t.run_id!==a.runId||a.currentStep!==t.phase||e.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(!yu(zv(a),zv(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function bR(t,e,i){return U(JSON.stringify({operation:"spec-rebase",change:t,summary:e,specChanges:i}))}function Yv(t,e,i){return t.phase!=="shape"&&e.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Gv(t){return"implementation_scope"in t?{implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance}:null}function Cu(t,e,i,r,n=!1){let a=i.eventData,o=Gv(t),s=Gv(e);if(a.previousPhase!==t.phase||a.nextPhase!==e.phase)throw new Error("Native transition journal event phases do not match its states");if(t.archived||e.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=t.name===e.name&&t.language===e.language&&t.brief===e.brief&&t.approval===e.approval&&("approved_contract_hash"in t?"approved_contract_hash"in e&&t.approved_contract_hash===e.approved_contract_hash:!("approved_contract_hash"in e))&&t.created_at===e.created_at&&yu(t.spec_changes,e.spec_changes);if(t.phase==="shape"||e.phase!=="build"||e.verification_result!=="pending"||e.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=t.name===e.name&&t.language===e.language&&t.brief===e.brief&&t.approval===e.approval&&("approved_contract_hash"in t?"approved_contract_hash"in e&&t.approved_contract_hash===e.approved_contract_hash:!("approved_contract_hash"in e))&&t.created_at===e.created_at&&t.run_id===e.run_id&&yu(t.spec_changes,e.spec_changes),l=Vv({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(t.phase==="archive"&&t.verification_result==="pass"||t.phase==="verify"&&t.verification_result==="pending")||e.phase!=="build"||e.verification_result!=="pending"||e.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=bR(t.name,a.summary,e.spec_changes),l=U(`spec-rebase:${t.name}:${a.summary}`);if(t.phase==="shape"||e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||e.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in e&&(e.implementation_scope!==null||e.verification_evidence!==null||e.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(t.phase==="shape"){if(e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||e.verification_result!=="pending"||t.verification_report!==null||e.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(t.phase==="build"){if(e.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||e.verification_result!=="pending"||e.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(t.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||e.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!==a.verificationResult||e.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 kR(t,e){let i=Jo(t);if(Eu(i,gR),i.schema!==Wi)throw new Error(`Expected Native transition schema ${Wi}`);let r=zo(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=zo(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=Pu(i,e),o=Gt(i.previousState),s=Gt(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native transition journal state mismatch");if(Cu(o,s,a,i.operation),xu(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:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function SR(t,e){let i=Jo(t);if(Eu(i,vR),i.schema!==nn)throw new Error(`Expected Native transition schema ${nn}`);let r=Pu(i,e,!0),n=Ji(i.previousState),a=Ji(i.nextState);if(n.name!==e||a.name!==e)throw new Error("Native transition journal state mismatch");return Cu(n,a,r,Yv(n,a,r.eventData),!0),xu(n,a,r,!0),{schema:nn,id:r.id,change:e,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function ER(t,e){let i=Jo(t);if(Eu(i,Kv),i.schema!==zi)throw new Error(`Expected Native transition schema ${zi}`);if(zo(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=zo(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Pu(i,e,!0),o=Gi(i.previousState),s=Gi(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native v2 transition journal state mismatch");if(Cu(o,s,a,Yv(o,s,a.eventData),!0),xu(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:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function PR(t,e){let i=Jo(t);if(i.schema===Wi)return{status:"current",journal:kR(i,e)};if(i.schema===nn)return{status:"migration-required",journal:SR(i,e)};if(i.schema===zi)return{status:"migration-required",journal:ER(i,e)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function xR(t,e){let i=Su(t,e),r=se(t,i);await W(r,i);try{let n=await ct({root:r,file:i,maxBytes:wR,label:`Native transition journal ${e}`});return PR(JSON.parse(n.bytes.toString("utf8")),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Xv(t,e){let i=await xR(t,e);if(!i)return null;if(i.status==="migration-required")throw new bu(e);return i.journal}var CR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function RR(t){return/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)}function AR(t){return t?t.map(RR).join(" "):null}function _R(t){if(t===null)return null;let e=t.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!e||e[0]!=="comet"?null:e.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 Fe(t,e,i,r={}){return{input:t,flags:e,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function TR(t){return t.map(e=>Fe(e,[],null))}function IR(t){let e=["comet","native","next",t.name,"--summary","<summary>"],i=[Fe("summary",["--summary"],"<summary>")];if(t.phase==="shape")return e.push("--confirmed"),i.push(Fe("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:e,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(t.phase==="build"){e.push("--artifact","<project-relative-path>"),i.push(Fe("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Fe("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return t.approval!=="confirmed"&&(e.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(Fe("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:e,requiredInputs:r,inputOptions:i}}return t.phase==="verify"?(e.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Fe("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Fe("verification-report",["--report"],"<change-relative-path>")),{commandArgs:e,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:e,requiredInputs:[],inputOptions:[]}}function me(t,e){let i=e.commandArgs===void 0?_R(e.command??null):e.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:t.name,phase:t.phase,revision:t.revision,disposition:e.disposition,action:e.action,command:e.command===void 0?AR(i??null):e.command,commandArgs:i??null,requiresUserDecision:e.requiresUserDecision??!1,requiredInputs:e.requiredInputs??[],inputOptions:e.inputOptions??TR(e.requiredInputs??[])}}function Go(t){let i=(t.findings??[]).filter(d=>!tr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||CR.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(t.done)return me(t.state,{disposition:"done",action:"none",commandArgs:null});if(a)return me(t.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Fe("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return me(t.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return me(t.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return me(t.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return me(t.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",t.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Fe("summary",["--summary"],"<summary>")]});if(n)return me(t.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(t.evidenceRetreat){let d=["comet","native","next",t.state.name,"--summary","<summary>"];return me(t.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Fe("summary",["--summary"],"<summary>")]})}if(t.state.phase==="build"&&t.state.verification_result==="fail")return me(t.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return t.state.phase==="archive"?me(t.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?me(t.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",t.state.name,"--apply"],requiredInputs:l}):me(t.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(t.state.phase==="archive"){if(t.archiveReady&&t.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(t.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",t.state.name,"--expect-preflight",t.archivePreflightHash];return t.archiveConfirmation==="required"?(d.push("--confirmed"),me(t.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Fe("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):me(t.state,{disposition:"continue",action:"archive",commandArgs:d})}return me(t.state,{disposition:t.archiveReady?"continue":"blocked",action:t.archiveReady?"archive":"none",commandArgs:t.archiveReady?["comet","native","archive",t.state.name,"--dry-run"]:null,requiredInputs:t.archiveReady?[]:["archive-readiness"]})}let u=IR(t.state);return me(t.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Cn from"path";var Qv=8,jR={"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 $R(t){let e=jR[t];return e||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(t)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:t.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:t.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:t.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:t.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:tr(t)?{severity:t==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function OR(t,e,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(pe(t,e.name),...i.path.split(/[\\/]/u)):r=Cn.resolve(t.projectRoot,...i.path.split(/[\\/]/u)),!B(t.projectRoot,r))return null;let n=Cn.relative(t.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function HR(t,e,i){return t==="next"?`comet native next ${e.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:t==="status"?`comet native status ${e.name} --details`:null}function Ru(t){return t.findings.map(e=>{let i=$R(e.code);return{code:e.code,message:e.message,severity:i.severity,path:OR(t.paths,t.state,e),requiredAction:i.requiredAction,retryCommand:HR(i.retry,t.state,e.code),repairCommand:i.repair==="doctor"?`comet native doctor ${t.state.name} --repair${e.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:e.code==="brief-blocking-question"||e.code==="shape-confirmation-required"||e.code==="approval-confirmation-required"||e.code==="contract-changed-after-approval"||e.code==="verification-scope-partial"||e.code==="repair-iteration-limit"||e.code==="repair-override-exhausted"}}).sort((e,i)=>{let r={error:0,warning:1,info:2};return r[e.severity]-r[i.severity]||e.code.localeCompare(i.code)||(e.path??"").localeCompare(i.path??"")||e.message.localeCompare(i.message)})}function Au(t){let e=[...new Set(t.map(i=>i.code))];return{total:t.length,errors:t.filter(i=>i.severity==="error").length,warnings:t.filter(i=>i.severity==="warning").length,info:t.filter(i=>i.severity==="info").length,requiresUserDecision:t.some(i=>i.requiresUserDecision),codes:e.slice(0,Qv),truncated:e.length>Qv}}import sr from"path";var ti={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},cr=/^[a-f0-9]{64}$/u;function Uo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ko(t,e,i){let r=new Set(e),n=Object.keys(t).filter(o=>!r.has(o)),a=e.filter(o=>!(o in t));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 ei(t,e,i=2e3){if(typeof t!="string"||t.length===0||t.length>i)throw new Error(`${e} must be a non-empty string of at most ${i} characters`);return t}function Zv(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function _u(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function DR(t){let e=t.trim().replaceAll("\\","/");if(e.length===0||sr.isAbsolute(e)||/^(?:[A-Za-z]:|~|\/)/u.test(e)||e.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${t}`);let i=sr.posix.normalize(e);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${t}`);return i}function eg(t,e){return sr.join(G(t,e),"checkpoints","progress.json")}function Rn(t,e){return sr.join(G(t,e),"checkpoint-journal.json")}function tg(t,e,i){if(!cr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return sr.join(G(t,e),"checkpoints","manifests",`${i}.json`)}function BR(t){if(!cr.test(t))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${t}.json`}async function Tu(t,e,i){let r=await ct({root:t,file:e,maxBytes:ti.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function FR(t,e){let i=Uo(t,`checkpoint manifest artifact ${e}`);Ko(i,["path","hash","size"],`checkpoint manifest artifact ${e}`);let r=DR(ei(i.path,`checkpoint artifact ${e} path`,4096)),n=at(r);if(n)throw new Error(`checkpoint artifact ${e} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!cr.test(i.hash))throw new Error(`checkpoint artifact ${e} hash is invalid`);return{path:r,hash:i.hash,size:_u(i.size,`checkpoint artifact ${e} size`)}}function Iu(t,e){let i=Uo(t,"Native checkpoint manifest");if(Ko(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!==e)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>ti.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(FR),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=_u(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>ti.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:e,artifacts:r,totalBytes:a}}function ig(t){return U(JSON.stringify(Iu(t,t.change)))}function rg(t,e){let i=Uo(t,"Native progress checkpoint");if(Ko(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!==e)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=Zv(i.previousRevision,"Native checkpoint previousRevision"),a=Zv(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=ei(i.manifestHash,"Native checkpoint manifestHash",64);if(!cr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=BR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=ei(i.inputHash,"Native checkpoint inputHash",64);if(!cr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=ei(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=_u(i.artifactCount,"Native checkpoint artifactCount");if(u>ti.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=ei(i.summary,"Native checkpoint summary"),f=ei(i.nextAction,"Native checkpoint nextAction");if(Be(d)!==d||Be(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:ei(i.id,"Native checkpoint id",128),change:e,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function LR(t,e){let i=Uo(t,"Native checkpoint journal");if(Ko(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!==e)throw new Error("Native checkpoint journal change mismatch");let r=Gt(i.previousState),n=Gt(i.nextState),a=rg(i.checkpoint,e),o=Iu(i.manifest,e),s=ei(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!==e||n.name!==e||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==ig(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:e,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function MR(t,e,i){let r=sr.resolve(t.projectRoot,...e.split("/"));if(!B(t.projectRoot,r)||B(t.nativeRoot,r)||B(t.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${e}`);let n=qc(t,e);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${e}`);let a=await ct({root:t.projectRoot,file:r,maxBytes:ti.maxFileBytes,label:`Checkpoint artifact ${e}`,forbiddenRoots:[t.nativeRoot,t.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(e),afterOpen:()=>i?.afterOpen?.(e),beforeRead:()=>i?.beforeRead?.(e)}});return{path:e,hash:a.hash,size:a.size}}async function qR(t,e){let i=eg(t,e),r=se(t,i);await W(r,i);try{return rg(await Tu(r,i,"Native progress checkpoint"),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function VR(t,e,i){let r=tg(t,e,i),n=se(t,r);await W(n,r);let a=await Tu(n,r,"Native checkpoint manifest"),o=Iu(a,e);if(ng(t,o),ig(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function ju(t,e){let i=Rn(t,e),r=se(t,i);await W(r,i);try{let n=LR(await Tu(r,i,"Native checkpoint journal"),e);return ng(t,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function ng(t,e){for(let i of e.artifacts){let r=qc(t,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function ag(t){let e;try{e=await qR(t.paths,t.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:eg(t.paths,t.name)}]}}if(!e)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];e.stateRevision!==t.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await VR(t.paths,t.name,e.manifestHash);let a=U(JSON.stringify({summary:e.summary,nextAction:e.nextAction,artifacts:n.artifacts}));if(e.inputHash!==a||e.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 MR(t.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:tg(t.paths,t.name,e.manifestHash)})}return{checkpoint:e,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var og=240,sg=8,Yo=50;function cg(t){let e=Array.from(t);return e.length<=og?t:`${e.slice(0,og-1).join("")}…`}function WR(t){let e=t.indexOf(":");return e<0?t:t.slice(0,e)}function zR(t){let e=[...new Set(t.map(WR))],i={freshness:t.length===0||t.length===1&&t[0]==="no-checkpoint"?"fresh":"stale",codes:e.slice(0,sg),reasonCount:t.length,codesTruncated:e.length>sg};return{inspection:i,inspectionDetails:{...i,reasons:t.slice(0,Yo),reasonsTruncated:t.length>Yo}}}async function lg(t){let e=null;try{let s=await ju(t.paths,t.state.name);s&&(e={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Rn(t.paths,t.state.name)})}catch(s){e={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(t.paths,t.state.name)}}let i=await ag({paths:t.paths,name:t.state.name,stateRevision:t.state.revision}),r=e?[e.code,...i.reasons]:i.reasons,n=zR(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:e?[e,...i.findings]:i.findings,maxCheckpointArtifacts:ti.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:cg(i.checkpoint.summary),nextAction:cg(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:e?[e,...i.findings]:i.findings,maxCheckpointArtifacts:ti.maxArtifacts}}import{promises as I_}from"node:fs";import Vg from"node:path";import ug from"node:path";var JR="comet.native.archive-preflight.v1",GR="comet.native.archive-preflight.v1",UR="comet.native.archive-operation.v1",KR=/^[a-f0-9]{64}$/u,dg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Xo(t,e){return t<e?-1:t>e?1:0}function XR(t,e){if(typeof t!="string"||!KR.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function At(t,e){return t===null?null:XR(t,e)}function QR(t,e){let i=ug.posix.normalize(t);if(typeof t!="string"||t.length===0||t!==t.trim()||t.includes("\\")||ug.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized Native-relative ref`);return t}function ZR(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native archive preflight revision must be a positive integer");return t}function eA(t){if(t==null)return null;if(t.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(t.isolation!=="current"&&t.isolation!=="branch"&&t.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[e,i]of[["change",t.changeBranch],["target",t.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 ${e} branch is invalid`);if(t.finish!==null&&t.finish!=="merge"&&t.finish!=="push"&&t.finish!=="pull-request"&&t.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null||t.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(t.isolation==="current"&&t.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...t}}function tA(t,e){if(!dg.test(t.capability))throw new Error(`Native archive spec ${e} capability is invalid`);if(t.operation!=="create"&&t.operation!=="replace"&&t.operation!=="remove")throw new Error(`Native archive spec ${t.capability} operation is invalid`);let i=At(t.expectedBaseHash,`Native archive spec ${t.capability} expected base`),r=At(t.actualBaseHash,`Native archive spec ${t.capability} actual base`),n=At(t.proposedHash,`Native archive spec ${t.capability} proposed content`);if(t.operation==="create"&&i!==null)throw new Error(`Native archive create ${t.capability} must expect no canonical base`);if(t.operation!=="create"&&i===null)throw new Error(`Native archive ${t.operation} ${t.capability} requires a base hash`);if(t.operation==="remove"!=(n===null))throw new Error(`Native archive ${t.operation} ${t.capability} proposed hash is invalid`);return{capability:t.capability,operation:t.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function iA(t){if(t.result!=="pending"&&t.result!=="pass"&&t.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(t.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(t.skippedAcceptanceCount)||t.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let e={result:t.result,freshness:t.freshness,contractHash:At(t.contractHash,"Native archive contract hash"),acceptanceHash:At(t.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:At(t.implementationScopeHash,"Native archive implementation scope hash"),reportHash:At(t.reportHash,"Native archive report hash"),envelopeHash:At(t.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:At(t.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:t.skippedAcceptanceCount};if((t.freshness==="complete"||t.freshness==="partial")&&[e.contractHash,e.acceptanceHash,e.implementationScopeHash,e.reportHash,e.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(t.freshness==="partial"&&e.partialAllowanceHash===null||t.freshness==="complete"&&e.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return e}function rA(t){if(t.length>64)throw new Error("Native archive preflight has too many findings");let e=t.map(r=>{if(typeof r!="string"||!YR.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(e)].sort(Xo);if(i.length!==e.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function nA(t){let e=[];t.phase!=="archive"&&e.push("archive-phase-required"),t.archived&&e.push("change-already-archived"),t.pendingJournal&&e.push("pending-journal"),t.targetExists&&e.push("archive-target-exists"),t.evidence.result!=="pass"&&e.push("verification-not-passed"),t.evidence.freshness==="missing"&&e.push("verification-evidence-missing"),t.evidence.freshness==="invalid"&&e.push("verification-evidence-invalid"),t.evidence.freshness==="stale"&&e.push("verification-evidence-stale"),t.evidence.skippedAcceptanceCount>0&&e.push("verification-acceptance-skipped");for(let i of t.specs)i.actualBaseHash!==i.expectedBaseHash&&e.push("spec-base-conflict");return[...new Set(e)].sort(Xo)}function fg(t){if(!dg.test(t.change))throw new Error("Native archive change name is invalid");if(typeof t.stateSchema!="string"||t.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(t.specs)||t.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let e=t.specs.map(tA).sort((l,u)=>Xo(l.capability,u.capability));if(new Set(e.map(l=>l.capability)).size!==e.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=e.map(l=>({...l,operationHash:F(UR,l)})),r=iA(t.evidence),n=eA(t.workspace),a=[...new Set([...rA(t.findingCodes??[]),...nA({phase:t.phase,archived:t.archived,pendingJournal:t.pendingJournal,targetExists:t.targetExists,specs:e,evidence:r})])].sort(Xo),o=ZR(t.revision),s=QR(t.targetRef,"Native archive target");if(t.archiveConfirmation!=="automatic"&&t.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:t.stateSchema,change:t.change,archiveConfirmation:t.archiveConfirmation,revision:o,phase:t.phase,archived:t.archived,pendingJournal:t.pendingJournal,targetRef:s,targetExists:t.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:JR,change:t.change,archiveConfirmation:t.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:F(GR,c)}}import{createHash as aA}from"node:crypto";import pg from"node:path";var oA="comet.native.conflict-radar.v1",Ee=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}),sA="comet.native.conflict-radar.v1",cA="comet.native.conflict-radar-signals.v1",lA=/^[a-f0-9]{64}$/u,vg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uA=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),dA=new Set(["capability","operation","baseHash"]),fA=new Set(["path","kind"]);function lr(t,e){return t<e?-1:t>e?1:0}function $u(t){return Buffer.byteLength(t,"utf8")}function Ou(t,e,i){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${i} must be an object`);let r=t,n=Object.keys(r).filter(a=>!e.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Hu(t,e,i){if(typeof t!="string"||t.length===0||t!==t.trim())throw new Error(`${e} must be a non-empty trimmed string`);if($u(t)>i)throw new Error(`${e} exceeds its byte budget`);return t}function pA(t,e){let i=Hu(t,e,Ee.maxArtifactPathBytes),r=pg.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)||pg.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${e} must be a normalized project-relative path`);return i}function gg(t,e){if(typeof t!="string"||!lA.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function hA(t,e){let i=Ou(t,dA,e),r=Hu(i.capability,`${e} capability`,Ee.maxCapabilityBytes);if(!vg.test(r))throw new Error(`${e} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${e} operation is invalid`);let n=i.baseHash===null?null:gg(i.baseHash,`${e} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${e} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${e} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function mA(t,e){let i=Ou(t,fA,e);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${e} kind is invalid`);return{path:pA(i.path,`${e} path`),kind:i.kind}}function vA(t,e){let i=Ou(t,uA,`Conflict radar change ${e}`),r=Hu(i.name,`Conflict radar change ${e} name`,Ee.maxNameBytes);if(!vg.test(r))throw new Error(`Conflict radar change ${e} 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>Ee.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>Ee.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>hA(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)=>mA(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:gg(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function gA(t){if(!Array.isArray(t))throw new Error("Native conflict radar input must be an array");if(t.length>Ee.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let e=t.map(vA).sort((n,a)=>lr(n.name,a.name));if(new Set(e.map(n=>n.name)).size!==e.length)throw new Error("Native conflict radar contains duplicate change names");if(e.reduce((n,a)=>n+a.specs.length,0)>Ee.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(e.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ee.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return e}function wA(t,e){let i=t.baseHash!==null&&t.baseHash===e.baseHash;return{kind:"capability",certainty:t.operation==="create"||e.operation==="create"||i?"definite-conflict":"possible-overlap",capability:t.capability,leftOperation:t.operation,rightOperation:e.operation,leftBaseHash:t.baseHash,rightBaseHash:e.baseHash}}function yA(t,e){let i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),n=t.kind==="file"&&e.kind==="file"&&t.path===e.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:t,rightArtifact:e}}function NA(t,e){return t.workspaceIdentityHash===null||e.workspaceIdentityHash===null?"unknown":t.workspaceIdentityHash===e.workspaceIdentityHash?"same":"different"}function bA(t,e){let i=[],r=aA("sha256").update(`${cA}
172
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(en(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ee.maxSignalsPerRelationship&&i.push(l)},s=new Map(e.specs.map(l=>[l.capability,l]));for(let l of t.specs){let u=s.get(l.capability);u&&o(wA(l,u))}for(let l of t.declaredArtifacts)for(let u of e.declaredArtifacts){let d=yA(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:t.name,right:e.name,classification:c,workspaceRelationship:NA(t,e),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function hg(t){return t==="definite-conflict"?0:t==="possible-overlap"?1:2}function kA(t,e){return hg(t.classification)-hg(e.classification)||lr(t.left,e.left)||lr(t.right,e.right)}function mg(t,e,i,r){let n={definiteConflict:e.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:e.filter(({classification:a})=>a==="possible-overlap").length,disjoint:e.filter(({classification:a})=>a==="disjoint").length};return{schema:oA,workspaceIdentityAdvisoryOnly:!0,changeCount:t.length,relationshipCount:e.length,counts:n,relationships:i,relationshipsTruncated:i.length!==e.length,omittedRelationshipCount:e.length-i.length,radarHash:r}}function wg(t){let e=gA(t),i=[];for(let s=0;s<e.length;s+=1)for(let c=s+1;c<e.length;c+=1)i.push(bA(e[s],e[c]));i.sort(kA);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=F(sA,{changes:e,relationships:r}),a=i.slice(0,Ee.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=mg(e,i,a,n);for(;a.length>0&&$u(JSON.stringify(o))>Ee.maxSerializedBytes;)a=a.slice(0,-1),o=mg(e,i,a,n);if($u(JSON.stringify(o))>Ee.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as t_}from"node:crypto";import{promises as tt}from"node:fs";import mt from"node:path";import yg from"node:path";var Ng="comet.native.check-receipt.v1",SA="comet.native.check-receipt.v1",ur="scoped-text-safety",Du=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),EA=/^[a-f0-9]{64}$/u,PA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xA="comet.native.checker-policy.v1",CA="comet.native.check-input.v1",RA=2048,bg=F(xA,{policy:ur,version:Du,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),AA=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),kg=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Eg=["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"],_A=new Set(Eg);function ii(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ri(t,e,i,r=[]){let n=new Set([...e,...r]),a=Object.keys(t).filter(s=>!n.has(s)),o=e.filter(s=>!(s in t));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 _t(t,e){if(typeof t!="string"||!EA.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Te(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Pg(t,e){let i=Te(t,e);if(i<1)throw new Error(`${e} must be a positive integer`);return i}function Sg(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let i=new Date(t);if(!Number.isFinite(i.getTime())||i.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function TA(t,e){if(typeof t!="string"||t.length===0||Buffer.byteLength(t,"utf8")>RA||t.includes("\\")||t.includes("\0")||t.endsWith("/")||/^[a-zA-Z]:/u.test(t))throw new Error(`${e} must be a bounded normalized project-relative path`);let i=yg.posix.normalize(t);if(i!==t||i==="."||i===".."||i.startsWith("../")||yg.posix.isAbsolute(i))throw new Error(`${e} must stay inside the project root`);return t}function IA(t){let e=ii(t,"Native check receipt checker");ri(e,["policy","version","hash","limits"],"Native check receipt checker");let i=ii(e.limits,"Native check receipt limits");if(ri(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),e.policy!==ur||e.version!==Du||e.hash!==bg||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ur,version:Du,hash:bg,limits:{...Pe}}}function jA(t){let e=ii(t,"Native check receipt contract");return ri(e,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:_t(e.expectedHash,"Native check expected contract hash"),beforeHash:_t(e.beforeHash,"Native check before contract hash"),afterHash:_t(e.afterHash,"Native check after contract hash")}}function $A(t){let e=ii(t,"Native check receipt implementation");return ri(e,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:_t(e.scopeHash,"Native check scope hash"),expectedSnapshotHash:_t(e.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:_t(e.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:_t(e.afterSnapshotHash,"Native check after snapshot hash")}}function OA(t,e){let i=ii(t,`Native check batch ${e}`);ri(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${e}`);let r={filesSelected:Te(i.filesSelected,`Native check batch ${e} filesSelected`),filesScanned:Te(i.filesScanned,`Native check batch ${e} filesScanned`),binaryFilesSkipped:Te(i.binaryFilesSkipped,`Native check batch ${e} binaryFilesSkipped`),bytesScanned:Te(i.bytesScanned,`Native check batch ${e} bytesScanned`),issueCount:Te(i.issueCount,`Native check batch ${e} issueCount`),recordedIssueCount:Te(i.recordedIssueCount,`Native check batch ${e} recordedIssueCount`)};if(r.filesSelected>Pe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Pe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${e} accounting is invalid`);return r}function HA(t){let e=ii(t,"Native check receipt counts");ri(e,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Te(e.filesSelected,"Native check filesSelected"),filesScanned:Te(e.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Te(e.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Te(e.bytesScanned,"Native check bytesScanned"),issueCount:Te(e.issueCount,"Native check issueCount"),recordedIssueCount:Te(e.recordedIssueCount,"Native check recordedIssueCount"),...e.batches===void 0?{}:{batches:Array.isArray(e.batches)?e.batches.map(OA):(()=>{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>Pe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function DA(t,e){return t.path.localeCompare(e.path,"en")||t.line-e.line||kg.indexOf(t.kind)-kg.indexOf(e.kind)}function BA(t){if(!Array.isArray(t)||t.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let e=t.map((r,n)=>{let a=ii(r,`Native check issue ${n}`);if(ri(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!AA.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:TA(a.path,`Native check issue ${n} path`),line:Pg(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...e].sort(DA);if(JSON.stringify(i)!==JSON.stringify(e))throw new Error("Native check receipt issues must be canonical");return e}function FA(t){if(!Array.isArray(t)||t.some(r=>typeof r!="string"||!_A.has(r)))throw new Error("Native check receipt stale reasons are invalid");let e=t,i=Eg.filter(r=>e.includes(r));if(new Set(e).size!==e.length||JSON.stringify(i)!==JSON.stringify(e))throw new Error("Native check receipt stale reasons must be canonical");return[...e]}function LA(t){return F(CA,t)}function xg(t){let e=ii(t,"Native check receipt");if(ri(e,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),e.schema!==Ng)throw new Error("Native check receipt schema is invalid");if(typeof e.change!="string"||Buffer.byteLength(e.change,"utf8")>128||!PA.test(e.change))throw new Error("Native check receipt change name is invalid");let i=Pg(e.sourceRevision,"Native check source revision"),r=IA(e.checker),n=jA(e.contract),a=$A(e.implementation),o=LA({change:e.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(_t(e.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(e.status!=="passed"&&e.status!=="failed")throw new Error("Native check receipt status is invalid");let s=Sg(e.startedAt,"Native check receipt startedAt"),c=Sg(e.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=HA(e.counts),u=BA(e.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof e.issuesTruncated!="boolean"||e.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=FA(e.staleReasons);if(typeof e.stale!="boolean"||e.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!e.stale?"passed":"failed";if(e.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(e.status==="passed"&&(l.batches===void 0&&l.filesSelected>Pe.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>Pe.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:Ng,change:e.change,sourceRevision:i,checker:r,inputHash:o,status:e.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:e.issuesTruncated,stale:e.stale,staleReasons:d},v=_t(e.receiptHash,"Native check receipt content hash");if(F(SA,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var Fu="comet.native.verification-receipt.v3",MA=Fu,qA="comet.native.declared-artifacts.v1",VA=/^[a-f0-9]{64}$/u,WA=/^acceptance-[a-f0-9]{64}$/u,zA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,GA=4096,UA=256,KA=1024;function dr(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function ni(t,e,i){let r=Object.keys(t).sort(),n=[...e].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Tt(t,e){if(typeof t!="string"||!VA.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function et(t,e){if(typeof t!="string")throw new Error(`${e} must be text`);let i=Be(t).trim();if(!i||i.length>GA||i!==t.trim())throw new Error(`${e} is invalid`);return i}function Bu(t,e){let i=et(t,e),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${e} must be a canonical timestamp`);return i}function An(t,e,i=et,r=!1,n=UA){if(!Array.isArray(t)||t.length>n||!r&&t.length===0)throw new Error(`${e} must be a bounded non-empty array`);let a=t.map((o,s)=>i(o,`${e} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${e} has duplicates`);return a}function YA(t,e){if(typeof t!="string"||!WA.test(t))throw new Error(`${e} is invalid`);return t}function XA(t){let e=dr(t,"Native verification receipt bindings");if(ni(e,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof e.change!="string"||!zA.test(e.change)||!Number.isSafeInteger(e.sourceRevision)||e.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:e.change,sourceRevision:e.sourceRevision,contractHash:Tt(e.contractHash,"Native verification receipt contract hash"),scopeHash:Tt(e.scopeHash,"Native verification receipt scope hash"),snapshotHash:Tt(e.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Tt(e.artifactHash,"Native verification receipt artifact hash")}}function QA(t){if(typeof t!="string")throw new Error("Native static check receipt ref is invalid");let e=JA.exec(t);if(!e)throw new Error("Native static check receipt ref is invalid");return{ref:t,hash:e[1]}}function ZA(t,e,i,r){let n=dr(e,`Native ${t} evidence`);if(t==="automated-check"){if(ni(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=Bu(n.startedAt,"Native automated-check start time"),o=Bu(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(ni(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(ni(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:et(n.executable,"Native automated-check executable"),args:An(n.args,"Native automated-check arguments",et,!0),cwd:et(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:et(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Tt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Tt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Tt(n.outputHash,"Native automated-check output hash"),outputSummary:et(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(t==="static-inspection"){ni(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=QA(n.checkReceiptRef);if(Tt(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",et,r==="required-check"),rule:et(n.rule,"Native static inspection rule"),resultSummary:et(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(t==="manual-evidence")return ni(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: ${t}`)}function e_(t){let e=dr(t,"Native verification receipt");if(ni(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(e.kind)||e.role!=="required-check"&&e.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(e.status))throw new Error("Native verification receipt kind or status is invalid");let i=e.kind,r=e.role,n=e.status,a=et(e.actor,"Native verification receipt actor"),o=An(e.acceptanceIds,"Native receipt acceptance IDs",YA,r==="required-check",KA).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:Fu,kind:i,role:r,status:n,bindings:XA(e.bindings),acceptanceIds:o,actor:a,issuedAt:Bu(e.issuedAt,"Native verification receipt issue time"),evidence:ZA(i,e.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 Cg(t){let e=dr(t,"Native verification receipt");if(ni(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),e.schema!==Fu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=e,n=e_(r),a=Tt(e.receiptHash,"Native verification receipt hash");if(F(MA,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Lu(t){return F(qA,[...t].map(e=>({path:e.path,kind:e.kind})).sort((e,i)=>e.path.localeCompare(i.path)||e.kind.localeCompare(i.kind)))}var Tg=/^[a-f0-9]{64}$/u,fr=Si,BF=3*fr;function Mu(t,e){let i=mt.relative(t,e);return i===""||!mt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${mt.sep}`)}function i_(t,e){return q({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Qo(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return ge(i,r)?q(i,r):q(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Rg(t){let e=await tt.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${t}`);return{path:t,realPath:await tt.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function r_(t,e){let i=mt.resolve(t),r=mt.resolve(e);if(!Mu(i,r))throw new Error("Native evidence path is outside its change");let n=[await Rg(i)],a=i;for(let o of mt.relative(i,r).split(mt.sep).filter(Boolean)){a=mt.join(a,o);let s=await Rg(a);if(!Mu(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Ag(t){for(let e of t){let i=await tt.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!i_(e,i)||await tt.realpath(e.path)!==e.realPath)throw new Error(`Native evidence parent changed while reading: ${e.path}`)}}async function n_(t,e,i={}){let r=await r_(e,mt.dirname(t));await i.afterParentChainCaptured?.();let n=await tt.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await tt.realpath(t);if(!Mu(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await tt.open(t,"r");try{let[s,c,l]=await Promise.all([o.stat(),tt.lstat(t),tt.realpath(t)]);if(await Ag(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Qo(s,n)||!Qo(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(),tt.lstat(t),tt.realpath(t)]);if(await Ag(r),!v.isFile()||v.isSymbolicLink()||p!==a||!Qo(s,h)||!Qo(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 Ig(t,e){if(!Tg.test(e))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${t}/${e}.json`}async function a_(t,e,i,r,n){if(!Tg.test(i))throw new Error("Native report evidence hash is invalid");let a=await Ei({paths:t,name:e,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"||t_("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(t,e){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(t);if(!i||i[1]!==e)throw new Error(`Native evidence ref is invalid for ${e}`);return i[2]}function o_(t,e,i,r,n){let a=Ig(i,r);return n?mt.join(n,...a.split("/")):Jt(G(t,e),a)}async function Ei(t){let e=o_(t.paths,t.name,t.kind,t.hash,t.changeDir),i=t.changeDir??se(t.paths,e);return await W(i,e),n_(e,i,t.hooks)}function _g(t,e){return Lo(t,e)}function s_(t,e){let i=Mo(t);if(i.scopeHash!==e)throw new Error("Native implementation scope ref/hash mismatch");return i}function c_(t,e,i){let r=jv(t);if(r.change!==e||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function l_(t,e,i){let r=pu(t);if(r.change!==e||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function u_(t,e,i,r=!1,n){let a=await Zo(t,e,i.implementationScopeRef,void 0,n);if(r&&await a_(t,e,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 jg(t,e,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(t,e,i,r,n){let a=pr(i,"scopes"),o=s_(await Ei({paths:t,name:e,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=pr(o.baselineProjectionRef,"snapshots"),c=pr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ei({paths:t,name:e,kind:"snapshots",hash:s,changeDir:n}).then(d=>_g(d,s)),Ei({paths:t,name:e,kind:"snapshots",hash:c,changeDir:n}).then(d=>_g(d,c))]);return xv({baseline:l,current:u,scope:o})}async function Zo(t,e,i,r,n){return(await _n(t,e,i,r,n)).scope}async function jg(t,e,i,r,n){let a=pr(i,"allowances");return c_(await Ei({paths:t,name:e,kind:"allowances",hash:a,hooks:r,changeDir:n}),e,a)}async function Tn(t,e,i,r,n){let a=pr(i,"receipts"),o=Cg(await Ei({paths:t,name:e,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==e||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function hr(t,e,i,r,n){let a=pr(i,"verifications"),o=l_(await Ei({paths:t,name:e,kind:"verifications",hash:a,hooks:r,changeDir:n}),e,a);return await u_(t,e,o,!1,n),o}var d_=4096;async function f_(t,e=Ee.maxChanges){try{let i=await an({root:t.nativeRoot,directory:t.changesDir,label:"Native conflict changes directory",maxEntries:e});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function $g(t,e){let i=await dt(t,e),[r,n]=await Promise.all([i.implementation_scope?Zo(t,e,i.implementation_scope):null,xt(t,e).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 es(t,e,i={}){let n=(await f_(t,d_)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(e))throw new Error(`Native conflict target is not visible: ${e}`);let a=await $g(t,e),o=0,s=0;for(let c of n){if(c===e)continue;let l=await $g(t,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=wg([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 S_}from"node:child_process";import{promisify as E_}from"node:util";import{constants as qu,promises as Le}from"node:fs";import mr from"node:path";var h_=/^[a-f0-9]{64}$/u,m_=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,In=512*1024;function v_(t,e){return q({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function ts(t,e){let i={...t,birthtime:t.birthtimeMs},r={...e,birthtime:e.birthtimeMs};return ge(i,r)?q(i,r):q(i,r)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function g_(t,e){let i=mr.resolve(t),r=mr.resolve(e);if(!B(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 Le.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Le.realpath(a);if(n.length>0&&!B(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Hg(t){for(let e of t){let i=await Le.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!v_(e,i)||await Le.realpath(e.path)!==e.realPath)throw new Error(`Native check receipt parent changed while reading: ${e.path}`)}}function w_(t){if(!h_.test(t))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${t}.json`}function y_(t){let e=m_.exec(t);if(!e)throw new Error("Native check receipt ref is invalid");return e[1]}function N_(t,e,i){return Jt(G(t,e),w_(i))}async function b_(t,e,i){let r=await g_(i,mr.dirname(t)),n=await Le.lstat(t);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([Le.realpath(e),Le.realpath(t)]);if(!B(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":qu.O_RDONLY|qu.O_NOFOLLOW|qu.O_NONBLOCK,c=await Le.open(t,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(),Le.lstat(t),Le.realpath(t)]);if(await Hg(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ts(n,l)||!ts(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(),Le.lstat(t),Le.realpath(t)]);if(await Hg(r),!m.isFile()||m.isSymbolicLink()||b!==o||!B(a,b)||!ts(l,p)||!ts(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 Dg(t,e,i){let r=y_(i),n=G(t,e),a=N_(t,e,r),o=se(t,a);await W(o,a);let s=xg(await b_(a,n,o));if(s.change!==e||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var jn=class extends Error{recovery;constructor(e,i){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var TL=64*1024;var IL=3600*1e3;var jL=E_(S_);var P_=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Bg(t,e){let i=[];for(let r of P_){let n=t.bindings[r],a=e[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Fg(t){if(t.receipt.kind!=="static-inspection")return null;let e=await Dg(t.paths,t.state.name,t.receipt.evidence.checkReceiptRef);if(e.receiptHash!==t.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return e}var ai=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};function x_(t){return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...t.capture?{capture:t.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:t.complete,limits:t.limits,...t.policy?{policy:t.policy}:{},entries:t.entries,omitted:t.omitted,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:t.omissionOverflow}:{}}}async function C_(t){let e=x_(t.bundle.baseline),i=await jl(t.paths,e,{origin:"explicit",now:t.now});return lu({baseline:e,current:i,contractHash:t.bundle.scope.contractHash,declaredArtifacts:t.bundle.scope.declaredArtifacts,noCodeReason:t.bundle.scope.noCodeReason,externalDrift:t.bundle.authority.externalDrift}).scope.currentProjectionHash}async function Mg(t){if(!t.state.implementation_scope)throw new Error("Native change has no implementation scope");let e=await _n(t.paths,t.state.name,t.state.implementation_scope),i=await ir({changeDir:pe(t.paths,t.state.name),briefRef:t.state.brief,specChanges:t.state.spec_changes}),r=await C_({paths:t.paths,bundle:e,now:t.now}),n=[];return i.contract.contractHash!==e.scope.contractHash&&n.push("verification-contract-stale"),r!==e.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:e,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function qg(t){if(!t.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let e=await Mg(t),i=[...new Set(e.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function R_(t){let e=await oe({root:pe(t.paths,t.state.name),ref:t.reportRef});return{ref:e.ref,hash:e.hash,text:e.text,entries:bh(e.text)}}function A_(t){let{receipt:e,implementationScope:i}=t,r=[],n=cu({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(e.stale||e.sourceRevision!==t.sourceRevision||e.contract.expectedHash!==t.contractHash||e.contract.beforeHash!==t.contractHash||e.contract.afterHash!==t.contractHash||e.implementation.scopeHash!==i.scope.scopeHash||e.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||e.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||e.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||e.counts.filesSelected!==n.length||e.status==="passed"&&(e.counts.filesScanned+e.counts.binaryFilesSkipped!==n.length||e.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),t.result==="pass"&&e.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function __(t){return{change:t.state.name,sourceRevision:t.sourceRevision??t.state.revision,contractHash:t.contractHash,scopeHash:t.implementationScope.scope.scopeHash,snapshotHash:t.implementationScope.scope.currentProjectionHash,artifactHash:Lu(t.implementationScope.scope.declaredArtifacts)}}async function Lg(t){let e=await Tn(t.paths,t.state.name,t.ref),i=[];e.role!==t.role&&i.push(`role: expected ${t.role}, got ${e.role}`);let r=Bg(e,t.expectedBindings);if(i.push(...r.mismatches),t.acceptanceId!==void 0&&!e.acceptanceIds.includes(t.acceptanceId)&&i.push(`acceptanceId: expected ${t.acceptanceId} in [${e.acceptanceIds.join(", ")}]`),i.length>0)throw new ai([{ref:t.ref,role:t.role,...t.acceptanceId!==void 0?{acceptanceId:t.acceptanceId}:{},mismatches:i}]);if(t.result==="pass"&&e.status!=="passed")throw new Error(`Native verification receipt is ${e.status}`);let n=await Fg({paths:t.paths,state:t.state,receipt:e});if(n){let a=A_({receipt:n,sourceRevision:t.expectedBindings.sourceRevision,result:t.result,contractHash:t.contractHash,implementationScope:t.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return e}async function T_(t){let e=__({state:t.state,contractHash:t.contractHash,implementationScope:t.implementationScope,sourceRevision:t.sourceRevision}),i=[];for(let r of t.requiredReceiptRefs){let n=await Lg({...t,ref:r,expectedBindings:e,role:"required-check"}).catch(a=>{if(a instanceof ai)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 t.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Lg({...t,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:e,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof ai)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 ai(i)}function Vu(t,e){return{result:t,freshness:e,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Wu(t){if(!t.state.implementation_scope||!t.state.verification_evidence||!t.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Vu(t.state.verification_result,"missing"),envelope:null};try{let[e,i]=await Promise.all([Mg(t),hr(t.paths,t.state.name,t.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Vu(t.state.verification_result,"stale"),envelope:null};let r=await R_({paths:t.paths,state:t.state,reportRef:t.state.verification_report}),n=[...e.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==t.state.verification_result||i.implementationScopeRef!==t.state.implementation_scope||i.partialAllowanceRef!==t.state.partial_allowance||i.sourceRevision>=t.state.revision||i.contractHash!==e.bundle.scope.contractHash||i.acceptanceCriteriaHash!==e.acceptanceHash)&&n.push("verification-state-mismatch");try{await T_({paths:t.paths,state:t.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:e.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:t.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:Vu(t.state.verification_result,"invalid"),envelope:null}}}function j_(t,e){return`archive/${e.toISOString().slice(0,10)}-${t}`}async function Wg(t){try{return await I_.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function $_(t,e){try{return(await oe({root:t,ref:e})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function O_(t,e,i){let r=Io(t,i.capability);if(!B(t.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Vg.relative(t.nativeRoot,r).replaceAll("\\","/"),a=await $_(t.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await oe({root:pe(t,e),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 H_(t,e){return Wg(Su(t,e))}async function zu(t){let e=t.now??new Date,i=await dt(t.paths,t.name),r=await xt(t.paths,t.name),n=await ot(t.paths.projectRoot),a=j_(i.name,e),o=Vg.resolve(t.paths.nativeRoot,...a.split("/"));if(!B(t.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=>O_(t.paths,i.name,v))),Wu({paths:t.paths,state:i,now:e}),es(t.paths,i.name),To(t.paths,i.name),Om(t.paths,i.name),H_(t.paths,i.name),Wg(o)]);return fg({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 D_(t,e){let i=G(t,e.name),r=await er(i);if(!r||!e.run_id||r.runId!==e.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Eo(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 yi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function B_(t,e){let i=await D_(t,e);return{committed:i,latest:Mv(i),history:Lv(i)}}async function zg(t,e,i){if(e.phase!=="build"||e.verification_result!=="fail")return null;let r=await B_(t,e),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 M1=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function L_(t){return t.map(e=>/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)).join(" ")}async function M_(t){return(await nv(t))?.change??null}function q_(t,e,i=!1,r){return Go({state:t,archiveReady:e,evidenceRetreat:i}).command}async function V_(t,e){let i=pe(t,e.name),r=[...(await Jl(i,e.brief)).findings,...(await Lm(t,e)).findings,...await ov(t,e)];if(e.phase==="shape"||e.phase==="build")try{let n=await wo(t,e.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 um(t,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(e.phase==="build")try{let n=await ir({changeDir:i,briefRef:e.brief,specChanges:e.spec_changes});(e.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:e.approval===null||e.approved_contract_hash===null||e.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 Xv(t,e.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 e.verification_report?r.push(...(await Gl(i,e.verification_report)).findings):(e.phase==="verify"||e.phase==="archive"||e.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Jg(t,e,i){let r=await M_(t)===e,n=await tl(t,e),a=await xm(t,e),o;try{let g=await Wl(t,e);if(g.status==="migration-required"&&g.state)return{name:e,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 ${e} --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:e,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 ${e} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${e} is incompatible`};o=g.state}catch(g){return{name:e,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 ${e} --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=Ru({paths:t,state:o,findings:[g]}),H=Go({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:H.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Au(S),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:H,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 lg({paths:t,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await zg(t,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:pe(t,o.name),briefRef:o.brief,specChanges:o.spec_changes}),S=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let ue=await hr(t,o.name,o.verification_evidence);for(let X of ue.acceptanceTrace.entries)S.set(X.acceptanceId,X.status==="failed"?"failed":X.status==="missing"?"missing":"satisfied")}let H=yh({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:S,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),I=H.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",H.nextCursor,"--project-root",t.projectRoot]:null;u={...H,...I?{nextPageCommand:L_(I),nextPageArgs:I}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await es(t,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 xt(t,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let S=await fn({paths:t,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 Co({paths:t,identity:g});f.push(...S.findingCodes.map(H=>({code:H,message:`Native workspace advisory changed: ${H} (${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 qg({paths:t,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 zu({paths:t,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 V_(t,o),...s.findings,...d,...f,...h,...l,...m].filter((g,S,H)=>H.findIndex(I=>I.code===g.code&&I.path===g.path)===S),N=Ru({paths:t,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:q_(o,k,E,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:Au(N),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Go({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:Yo,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}:{}}}function Gg(t){let e={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[]},i=r=>({kind:r,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...e,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:i("none")};if(t.status==="await-user")return t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...e,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",t.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")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...e,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",t.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")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...e,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",t.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...e,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",t.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:{...e,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:i("none")};if(t.status==="blocked"){let r=t.blockers.some(({resolution_action:n})=>n==="retry-verifier");return{...e,disposition:"blocked",action:r?"retry-verifier":"none",commandArgs:r?["comet","native","next",t.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(t.phase==="shape")return{...e,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",t.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(t.phase==="build")return{...e,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.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(t.phase==="verify"){let r=t.loop.next_action==="await-verifier-result";return{...e,disposition:"continue",action:r?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.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:t.loop.iteration,attempt:t.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:t.loop.iteration,attempt:t.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:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:i(r?"await-verifier":"dispatch-verifier")}}return{...e,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:i("none")}}function W_(t){return t.acceptance.reduce((e,i)=>({...e,[i.result]:e[i.result]+1}),{total:t.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function z_(t,e){let i=We(t.projectRoot),r=null;return e.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==e.workspace.change_branch&&(r=`Expected branch ${e.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&e.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:t.projectRoot,isolation:e.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:e.workspace.change_branch,targetBranch:e.workspace.target_branch,finish:e.workspace.finish,message:r}}async function Ug(t){let e=await rv(t),i=e.state.status==="active"&&e.state.loop.stage!=="done",r=z_(t.paths,e.state),n=Gg(e.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:e.state.name,phase:e.state.phase,status:e.state.status,stateVersion:e.state.state_version,loop:e.state.loop,acceptance:W_(e.state),verificationResult:e.state.verification_result,blockers:e.state.blockers,builderHandoff:e.state.builder_handoff,verification:e.state.verification,history:e.state.history,historyOverflow:e.state.history_overflow,workspace:r,localExecution:{status:i?e.localStatus:"not-expected",operation:e.localStatus==="available"?e.local?.execution??null:null},continuation:a,...t.details?{details:{acceptance:e.state.acceptance,specChanges:e.state.spec_changes,workspace:e.state.workspace,verificationReport:e.state.verification_report}}:{}}}import Uu from"path";var aM={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var hM=16*1024*1024,mM=256*1024,vM=16*1024;var bM=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var sq=16*1024*1024,is=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"},rs=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 lq=8*1024*1024;var ns=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Kg=["--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."],Gu=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:Kg,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]
173
+ 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]
174
+ 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 Ju(t,e){return`${t}:
175
+ ${e.map(i=>` ${i}`).join(`
176
+ `)}`}function U_(t){let e=t.filter(r=>r!=="--help");if(e.length===0)return"";let i=e.slice(0,2).join(" ");return Gu[i]||e.length>1&&Gu[e[0]]?.subcommands?i:e[0]}function K_(t=[]){let e=U_(t),i=Gu[e];if(!i)throw new Error(`Unknown Native help topic: ${e}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Ju("Commands",i.subcommands));let n=e===""?i.options:[...i.options??[],...Kg];return n&&n.length>0&&r.push("",Ju("Options",n)),r.push("",`Output:
177
+ ${i.output}`),i.examples&&r.push("",Ju("Examples",i.examples)),e===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${r.join(`
178
+ `)}
179
+ `}}var Y_=K_().usage;var Aq=10*1024*1024,oi=class extends Error{};function Xg(t,e){let i=t.flatMap((r,n)=>r===e?[n]:[]);if(i.length>1)throw new oi(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Qg(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new oi(`${e} may only be provided once`);if(i.length===0)return;let r=i[0],n=t[r+1];if(n===void 0||n.startsWith("--"))throw new oi(`${e} requires a value`);return t.splice(r,2),n}function Zg(t){if(t.length>0)throw new oi(`Unexpected argument: ${t[0]}`)}function ew(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new oi(`${e} is required`);return i}function Yg(t,e){let i=Uu.normalize(t),r=Uu.normalize(e);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function X_(t){let e=Uu.resolve(t),i=We(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return e;let r=We(e);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Yg(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Yg(i.currentWorktreeRoot,r.currentWorktreeRoot)?e:i.currentWorktreeRoot}async function tw(t){return t?X_(t):Ua(process.cwd())}async function iw(t){let e=await eh({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function rw(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
180
+ `}}function nw(t,e){if(e instanceof oi)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof is)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof rs)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof Ao)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof pn)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof ns)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof _o)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.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:e.message}};if(e instanceof ai)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof jn)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function aw(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
181
+ `}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function ow(t,e){let i=ew(t,"change name");Zg(t);let{config:r,paths:n}=await iw(e);await av(n,i);let a=await Fo(n,i)?await Ug({paths:n,name:i}):await Jg(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return rw("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
182
+ `)}function Q_(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
183
+ `}}async function sw(t,e,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{Xg(n,"--json"),s=Qg(n,"--project-root");let u=[...n,...a],d=await tw(s);c=await e(u,d)}catch(u){c=nw(t,u)}let l=o?Q_(c):aw(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
177
184
  `)?"":`
178
- `)),l.exitCode}process.exitCode=await qv("select",Bv);
185
+ `)),l.exitCode}process.exitCode=await sw("select",ow);