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

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 (761) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +85 -56
  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 +26 -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 +128 -128
  13. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +77 -77
  14. package/assets/skills/comet/scripts/comet-guard.mjs +144 -144
  15. package/assets/skills/comet/scripts/comet-handoff.mjs +107 -107
  16. package/assets/skills/comet/scripts/comet-hook-guard.mjs +128 -128
  17. package/assets/skills/comet/scripts/comet-hook-router.mjs +143 -141
  18. package/assets/skills/comet/scripts/comet-resume-probe.mjs +100 -100
  19. package/assets/skills/comet/scripts/comet-runtime.mjs +194 -193
  20. package/assets/skills/comet/scripts/comet-state.mjs +118 -118
  21. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +95 -95
  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 +28 -68
  27. package/assets/skills/comet-build/agents/openai.yaml +5 -0
  28. package/assets/skills/comet-classic/SKILL.md +28 -22
  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 +3 -3
  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 +4 -2
  39. package/assets/skills/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  40. package/assets/skills/comet-classic/reference/workspace.md +23 -0
  41. package/assets/skills/comet-design/SKILL.md +7 -6
  42. package/assets/skills/comet-design/agents/openai.yaml +5 -0
  43. package/assets/skills/comet-hotfix/SKILL.md +10 -9
  44. package/assets/skills/comet-hotfix/agents/openai.yaml +5 -0
  45. package/assets/skills/comet-native/SKILL.md +60 -171
  46. package/assets/skills/comet-native/agents/openai.yaml +3 -0
  47. package/assets/skills/comet-native/reference/artifacts.md +24 -89
  48. package/assets/skills/comet-native/reference/clarification.md +54 -29
  49. package/assets/skills/comet-native/reference/commands.md +30 -173
  50. package/assets/skills/comet-native/reference/recovery.md +38 -88
  51. package/assets/skills/comet-native/reference/workspace.md +23 -0
  52. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +184 -152
  53. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +214 -158
  54. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +132 -123
  55. package/assets/skills/comet-native/scripts/comet-native-init.mjs +134 -124
  56. package/assets/skills/comet-native/scripts/comet-native-new.mjs +165 -158
  57. package/assets/skills/comet-native/scripts/comet-native-next.mjs +183 -152
  58. package/assets/skills/comet-native/scripts/comet-native-root.mjs +152 -147
  59. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +247 -202
  60. package/assets/skills/comet-native/scripts/comet-native-select.mjs +150 -143
  61. package/assets/skills/comet-native/scripts/comet-native-show.mjs +128 -121
  62. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +133 -151
  63. package/assets/skills/comet-native/scripts/comet-native-status.mjs +147 -140
  64. package/assets/skills/comet-open/SKILL.md +31 -11
  65. package/assets/skills/comet-open/agents/openai.yaml +5 -0
  66. package/assets/skills/comet-tweak/SKILL.md +11 -10
  67. package/assets/skills/comet-tweak/agents/openai.yaml +5 -0
  68. package/assets/skills/comet-verify/SKILL.md +9 -8
  69. package/assets/skills/comet-verify/agents/openai.yaml +5 -0
  70. package/assets/skills-zh/comet/SKILL.md +1 -1
  71. package/assets/skills-zh/comet/agents/openai.yaml +3 -0
  72. package/assets/skills-zh/comet-any/SKILL.md +2 -1
  73. package/assets/skills-zh/comet-any/agents/openai.yaml +5 -0
  74. package/assets/skills-zh/comet-archive/SKILL.md +7 -6
  75. package/assets/skills-zh/comet-archive/agents/openai.yaml +5 -0
  76. package/assets/skills-zh/comet-build/SKILL.md +28 -68
  77. package/assets/skills-zh/comet-build/agents/openai.yaml +5 -0
  78. package/assets/skills-zh/comet-classic/SKILL.md +29 -23
  79. package/assets/skills-zh/comet-classic/agents/openai.yaml +3 -0
  80. package/assets/skills-zh/{comet → comet-classic}/reference/auto-transition.md +1 -1
  81. package/assets/skills-zh/{comet → comet-classic}/reference/comet-yaml-fields.md +3 -3
  82. package/assets/skills-zh/{comet → comet-classic}/reference/context-recovery.md +5 -5
  83. package/assets/skills-zh/{comet → comet-classic}/reference/debug-gate.md +2 -2
  84. package/assets/skills-zh/{comet → comet-classic}/reference/decision-point.md +1 -1
  85. package/assets/skills-zh/{comet → comet-classic}/reference/dirty-worktree.md +1 -1
  86. package/assets/skills-zh/{comet → comet-classic}/reference/file-structure.md +1 -1
  87. package/assets/skills-zh/{comet → comet-classic}/reference/intent-frame.md +1 -1
  88. package/assets/skills-zh/{comet → comet-classic}/reference/scripts.md +4 -2
  89. package/assets/skills-zh/{comet → comet-classic}/reference/subagent-dispatch.md +1 -1
  90. package/assets/skills-zh/comet-classic/reference/workspace.md +23 -0
  91. package/assets/skills-zh/comet-design/SKILL.md +7 -6
  92. package/assets/skills-zh/comet-design/agents/openai.yaml +5 -0
  93. package/assets/skills-zh/comet-hotfix/SKILL.md +10 -9
  94. package/assets/skills-zh/comet-hotfix/agents/openai.yaml +5 -0
  95. package/assets/skills-zh/comet-native/SKILL.md +60 -171
  96. package/assets/skills-zh/comet-native/agents/openai.yaml +3 -0
  97. package/assets/skills-zh/comet-native/reference/artifacts.md +24 -89
  98. package/assets/skills-zh/comet-native/reference/clarification.md +40 -15
  99. package/assets/skills-zh/comet-native/reference/commands.md +30 -173
  100. package/assets/skills-zh/comet-native/reference/recovery.md +36 -86
  101. package/assets/skills-zh/comet-native/reference/workspace.md +23 -0
  102. package/assets/skills-zh/comet-open/SKILL.md +31 -11
  103. package/assets/skills-zh/comet-open/agents/openai.yaml +5 -0
  104. package/assets/skills-zh/comet-tweak/SKILL.md +11 -10
  105. package/assets/skills-zh/comet-tweak/agents/openai.yaml +5 -0
  106. package/assets/skills-zh/comet-verify/SKILL.md +9 -8
  107. package/assets/skills-zh/comet-verify/agents/openai.yaml +5 -0
  108. package/bin/fast-runtime-router.js +0 -4
  109. package/dist/app/cli/index.js +20 -1
  110. package/dist/app/cli/index.js.map +1 -1
  111. package/dist/app/commands/classic.d.ts.map +1 -1
  112. package/dist/app/commands/classic.js +2 -0
  113. package/dist/app/commands/classic.js.map +1 -1
  114. package/dist/app/commands/doctor.d.ts.map +1 -1
  115. package/dist/app/commands/doctor.js +8 -0
  116. package/dist/app/commands/doctor.js.map +1 -1
  117. package/dist/app/commands/eval.d.ts +9 -2
  118. package/dist/app/commands/eval.d.ts.map +1 -1
  119. package/dist/app/commands/eval.js +293 -48
  120. package/dist/app/commands/eval.js.map +1 -1
  121. package/dist/app/commands/init.d.ts.map +1 -1
  122. package/dist/app/commands/init.js +11 -2
  123. package/dist/app/commands/init.js.map +1 -1
  124. package/dist/app/commands/update.d.ts.map +1 -1
  125. package/dist/app/commands/update.js +13 -3
  126. package/dist/app/commands/update.js.map +1 -1
  127. package/dist/config/repository-layout.json +0 -8
  128. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  129. package/dist/domains/bundle/bundle-platform.js +8 -0
  130. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  131. package/dist/domains/bundle/types.d.ts +1 -1
  132. package/dist/domains/bundle/types.d.ts.map +1 -1
  133. package/dist/domains/comet-classic/classic-cli.d.ts +1 -1
  134. package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
  135. package/dist/domains/comet-classic/classic-cli.js +3 -0
  136. package/dist/domains/comet-classic/classic-cli.js.map +1 -1
  137. package/dist/domains/comet-classic/classic-current-change.d.ts.map +1 -1
  138. package/dist/domains/comet-classic/classic-current-change.js +29 -3
  139. package/dist/domains/comet-classic/classic-current-change.js.map +1 -1
  140. package/dist/domains/comet-classic/classic-guard.js +2 -2
  141. package/dist/domains/comet-classic/classic-guard.js.map +1 -1
  142. package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
  143. package/dist/domains/comet-classic/classic-hook-guard.js +14 -1
  144. package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
  145. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  146. package/dist/domains/comet-classic/classic-state-command.js +31 -8
  147. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  148. package/dist/domains/comet-classic/classic-workspace-command.d.ts +3 -0
  149. package/dist/domains/comet-classic/classic-workspace-command.d.ts.map +1 -0
  150. package/dist/domains/comet-classic/classic-workspace-command.js +45 -0
  151. package/dist/domains/comet-classic/classic-workspace-command.js.map +1 -0
  152. package/dist/domains/comet-classic/classic-workspace.d.ts +38 -0
  153. package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -0
  154. package/dist/domains/comet-classic/classic-workspace.js +315 -0
  155. package/dist/domains/comet-classic/classic-workspace.js.map +1 -0
  156. package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
  157. package/dist/domains/comet-entry/hook-adapter.js +3 -0
  158. package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
  159. package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -0
  160. package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
  161. package/dist/domains/comet-entry/hook-router-entry.js +32 -3
  162. package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
  163. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  164. package/dist/domains/comet-entry/init-workflow.js +13 -5
  165. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  166. package/dist/domains/comet-entry/project-activation.d.ts.map +1 -1
  167. package/dist/domains/comet-entry/project-activation.js +2 -1
  168. package/dist/domains/comet-entry/project-activation.js.map +1 -1
  169. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  170. package/dist/domains/comet-entry/resume-probe.js +48 -4
  171. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  172. package/dist/domains/comet-native/index.d.ts +1 -0
  173. package/dist/domains/comet-native/index.d.ts.map +1 -1
  174. package/dist/domains/comet-native/index.js +1 -0
  175. package/dist/domains/comet-native/index.js.map +1 -1
  176. package/dist/domains/comet-native/native-acceptance.d.ts +4 -3
  177. package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
  178. package/dist/domains/comet-native/native-acceptance.js +23 -18
  179. package/dist/domains/comet-native/native-acceptance.js.map +1 -1
  180. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  181. package/dist/domains/comet-native/native-archive-command.js +204 -61
  182. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  183. package/dist/domains/comet-native/native-archive-transaction.d.ts.map +1 -1
  184. package/dist/domains/comet-native/native-archive-transaction.js +28 -23
  185. package/dist/domains/comet-native/native-archive-transaction.js.map +1 -1
  186. package/dist/domains/comet-native/native-archive.d.ts +1 -0
  187. package/dist/domains/comet-native/native-archive.d.ts.map +1 -1
  188. package/dist/domains/comet-native/native-archive.js +56 -12
  189. package/dist/domains/comet-native/native-archive.js.map +1 -1
  190. package/dist/domains/comet-native/native-bounded-file.d.ts +32 -2
  191. package/dist/domains/comet-native/native-bounded-file.d.ts.map +1 -1
  192. package/dist/domains/comet-native/native-bounded-file.js +87 -6
  193. package/dist/domains/comet-native/native-bounded-file.js.map +1 -1
  194. package/dist/domains/comet-native/native-build-evidence.d.ts.map +1 -1
  195. package/dist/domains/comet-native/native-build-evidence.js +23 -1
  196. package/dist/domains/comet-native/native-build-evidence.js.map +1 -1
  197. package/dist/domains/comet-native/native-change.d.ts +1 -0
  198. package/dist/domains/comet-native/native-change.d.ts.map +1 -1
  199. package/dist/domains/comet-native/native-change.js +96 -8
  200. package/dist/domains/comet-native/native-change.js.map +1 -1
  201. package/dist/domains/comet-native/native-check-executor.d.ts +36 -0
  202. package/dist/domains/comet-native/native-check-executor.d.ts.map +1 -0
  203. package/dist/domains/comet-native/native-check-executor.js +132 -0
  204. package/dist/domains/comet-native/native-check-executor.js.map +1 -0
  205. package/dist/domains/comet-native/native-check-receipt-model.d.ts +9 -0
  206. package/dist/domains/comet-native/native-check-receipt-model.d.ts.map +1 -1
  207. package/dist/domains/comet-native/native-check-receipt-model.js +70 -8
  208. package/dist/domains/comet-native/native-check-receipt-model.js.map +1 -1
  209. package/dist/domains/comet-native/native-check-receipt-storage.d.ts.map +1 -1
  210. package/dist/domains/comet-native/native-check-receipt-storage.js +9 -8
  211. package/dist/domains/comet-native/native-check-receipt-storage.js.map +1 -1
  212. package/dist/domains/comet-native/native-check-receipt.d.ts.map +1 -1
  213. package/dist/domains/comet-native/native-check-receipt.js +123 -60
  214. package/dist/domains/comet-native/native-check-receipt.js.map +1 -1
  215. package/dist/domains/comet-native/native-checkpoint-command.d.ts.map +1 -1
  216. package/dist/domains/comet-native/native-checkpoint-command.js +0 -6
  217. package/dist/domains/comet-native/native-checkpoint-command.js.map +1 -1
  218. package/dist/domains/comet-native/native-checkpoint-storage.d.ts.map +1 -1
  219. package/dist/domains/comet-native/native-checkpoint-storage.js +27 -19
  220. package/dist/domains/comet-native/native-checkpoint-storage.js.map +1 -1
  221. package/dist/domains/comet-native/native-children.d.ts +49 -0
  222. package/dist/domains/comet-native/native-children.d.ts.map +1 -0
  223. package/dist/domains/comet-native/native-children.js +388 -0
  224. package/dist/domains/comet-native/native-children.js.map +1 -0
  225. package/dist/domains/comet-native/native-cli-help.d.ts +6 -0
  226. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -0
  227. package/dist/domains/comet-native/native-cli-help.js +192 -0
  228. package/dist/domains/comet-native/native-cli-help.js.map +1 -0
  229. package/dist/domains/comet-native/native-cli-shared.d.ts +2 -2
  230. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  231. package/dist/domains/comet-native/native-cli-shared.js +46 -24
  232. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  233. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  234. package/dist/domains/comet-native/native-cli.js +18 -11
  235. package/dist/domains/comet-native/native-cli.js.map +1 -1
  236. package/dist/domains/comet-native/native-config.d.ts +2 -1
  237. package/dist/domains/comet-native/native-config.d.ts.map +1 -1
  238. package/dist/domains/comet-native/native-config.js +2 -1
  239. package/dist/domains/comet-native/native-config.js.map +1 -1
  240. package/dist/domains/comet-native/native-continuation.d.ts.map +1 -1
  241. package/dist/domains/comet-native/native-continuation.js +175 -147
  242. package/dist/domains/comet-native/native-continuation.js.map +1 -1
  243. package/dist/domains/comet-native/native-diagnostics.d.ts.map +1 -1
  244. package/dist/domains/comet-native/native-diagnostics.js +96 -13
  245. package/dist/domains/comet-native/native-diagnostics.js.map +1 -1
  246. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  247. package/dist/domains/comet-native/native-doctor-command.js +332 -0
  248. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  249. package/dist/domains/comet-native/native-doctor.d.ts +1 -0
  250. package/dist/domains/comet-native/native-doctor.d.ts.map +1 -1
  251. package/dist/domains/comet-native/native-doctor.js +116 -22
  252. package/dist/domains/comet-native/native-doctor.js.map +1 -1
  253. package/dist/domains/comet-native/native-evidence-projection.d.ts +50 -0
  254. package/dist/domains/comet-native/native-evidence-projection.d.ts.map +1 -0
  255. package/dist/domains/comet-native/native-evidence-projection.js +284 -0
  256. package/dist/domains/comet-native/native-evidence-projection.js.map +1 -0
  257. package/dist/domains/comet-native/native-evidence-retention.d.ts.map +1 -1
  258. package/dist/domains/comet-native/native-evidence-retention.js +14 -12
  259. package/dist/domains/comet-native/native-evidence-retention.js.map +1 -1
  260. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  261. package/dist/domains/comet-native/native-evidence-storage.js +14 -11
  262. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  263. package/dist/domains/comet-native/native-findings.d.ts.map +1 -1
  264. package/dist/domains/comet-native/native-findings.js +18 -0
  265. package/dist/domains/comet-native/native-findings.js.map +1 -1
  266. package/dist/domains/comet-native/native-git-provenance.d.ts +16 -0
  267. package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -0
  268. package/dist/domains/comet-native/native-git-provenance.js +171 -0
  269. package/dist/domains/comet-native/native-git-provenance.js.map +1 -0
  270. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  271. package/dist/domains/comet-native/native-hook-guard.js +199 -19
  272. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  273. package/dist/domains/comet-native/native-init-command.d.ts.map +1 -1
  274. package/dist/domains/comet-native/native-init-command.js +14 -2
  275. package/dist/domains/comet-native/native-init-command.js.map +1 -1
  276. package/dist/domains/comet-native/native-local-execution.d.ts +25 -0
  277. package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -0
  278. package/dist/domains/comet-native/native-local-execution.js +241 -0
  279. package/dist/domains/comet-native/native-local-execution.js.map +1 -0
  280. package/dist/domains/comet-native/native-lock.d.ts +1 -1
  281. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  282. package/dist/domains/comet-native/native-lock.js +9 -9
  283. package/dist/domains/comet-native/native-lock.js.map +1 -1
  284. package/dist/domains/comet-native/native-loop-runtime.d.ts +63 -0
  285. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -0
  286. package/dist/domains/comet-native/native-loop-runtime.js +580 -0
  287. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -0
  288. package/dist/domains/comet-native/native-mutation-lock.d.ts +2 -0
  289. package/dist/domains/comet-native/native-mutation-lock.d.ts.map +1 -1
  290. package/dist/domains/comet-native/native-mutation-lock.js +23 -2
  291. package/dist/domains/comet-native/native-mutation-lock.js.map +1 -1
  292. package/dist/domains/comet-native/native-new-command.d.ts.map +1 -1
  293. package/dist/domains/comet-native/native-new-command.js +27 -20
  294. package/dist/domains/comet-native/native-new-command.js.map +1 -1
  295. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  296. package/dist/domains/comet-native/native-next-command.js +193 -62
  297. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  298. package/dist/domains/comet-native/native-paths.d.ts +18 -0
  299. package/dist/domains/comet-native/native-paths.d.ts.map +1 -1
  300. package/dist/domains/comet-native/native-paths.js +125 -13
  301. package/dist/domains/comet-native/native-paths.js.map +1 -1
  302. package/dist/domains/comet-native/native-portable-acceptance.d.ts +28 -0
  303. package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -0
  304. package/dist/domains/comet-native/native-portable-acceptance.js +73 -0
  305. package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -0
  306. package/dist/domains/comet-native/native-portable-archive.d.ts +37 -0
  307. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -0
  308. package/dist/domains/comet-native/native-portable-archive.js +492 -0
  309. package/dist/domains/comet-native/native-portable-archive.js.map +1 -0
  310. package/dist/domains/comet-native/native-portable-continuation.d.ts +30 -0
  311. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -0
  312. package/dist/domains/comet-native/native-portable-continuation.js +403 -0
  313. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -0
  314. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts +9 -0
  315. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -0
  316. package/dist/domains/comet-native/native-portable-migration-runtime.js +213 -0
  317. package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -0
  318. package/dist/domains/comet-native/native-portable-migration.d.ts +42 -0
  319. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -0
  320. package/dist/domains/comet-native/native-portable-migration.js +212 -0
  321. package/dist/domains/comet-native/native-portable-migration.js.map +1 -0
  322. package/dist/domains/comet-native/native-portable-recovery.d.ts +15 -0
  323. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -0
  324. package/dist/domains/comet-native/native-portable-recovery.js +203 -0
  325. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -0
  326. package/dist/domains/comet-native/native-portable-runtime.d.ts +155 -0
  327. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -0
  328. package/dist/domains/comet-native/native-portable-runtime.js +1550 -0
  329. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -0
  330. package/dist/domains/comet-native/native-portable-state.d.ts +30 -0
  331. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -0
  332. package/dist/domains/comet-native/native-portable-state.js +701 -0
  333. package/dist/domains/comet-native/native-portable-state.js.map +1 -0
  334. package/dist/domains/comet-native/native-portable-status.d.ts +65 -0
  335. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -0
  336. package/dist/domains/comet-native/native-portable-status.js +133 -0
  337. package/dist/domains/comet-native/native-portable-status.js.map +1 -0
  338. package/dist/domains/comet-native/native-portable-text.d.ts +8 -0
  339. package/dist/domains/comet-native/native-portable-text.d.ts.map +1 -0
  340. package/dist/domains/comet-native/native-portable-text.js +28 -0
  341. package/dist/domains/comet-native/native-portable-text.js.map +1 -0
  342. package/dist/domains/comet-native/native-portable-transactions.d.ts +41 -0
  343. package/dist/domains/comet-native/native-portable-transactions.d.ts.map +1 -0
  344. package/dist/domains/comet-native/native-portable-transactions.js +204 -0
  345. package/dist/domains/comet-native/native-portable-transactions.js.map +1 -0
  346. package/dist/domains/comet-native/native-portable-types.d.ts +166 -0
  347. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -0
  348. package/dist/domains/comet-native/native-portable-types.js +18 -0
  349. package/dist/domains/comet-native/native-portable-types.js.map +1 -0
  350. package/dist/domains/comet-native/native-repair-integration.js +5 -5
  351. package/dist/domains/comet-native/native-repair-integration.js.map +1 -1
  352. package/dist/domains/comet-native/native-resume-view.d.ts.map +1 -1
  353. package/dist/domains/comet-native/native-resume-view.js +1 -5
  354. package/dist/domains/comet-native/native-resume-view.js.map +1 -1
  355. package/dist/domains/comet-native/native-root-move.d.ts.map +1 -1
  356. package/dist/domains/comet-native/native-root-move.js +4 -20
  357. package/dist/domains/comet-native/native-root-move.js.map +1 -1
  358. package/dist/domains/comet-native/native-run-consistency.d.ts.map +1 -1
  359. package/dist/domains/comet-native/native-run-consistency.js +8 -12
  360. package/dist/domains/comet-native/native-run-consistency.js.map +1 -1
  361. package/dist/domains/comet-native/native-run-store.js +4 -4
  362. package/dist/domains/comet-native/native-run-store.js.map +1 -1
  363. package/dist/domains/comet-native/native-runner-input.d.ts +160 -0
  364. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -0
  365. package/dist/domains/comet-native/native-runner-input.js +347 -0
  366. package/dist/domains/comet-native/native-runner-input.js.map +1 -0
  367. package/dist/domains/comet-native/native-runner-protocol.d.ts +40 -0
  368. package/dist/domains/comet-native/native-runner-protocol.d.ts.map +1 -0
  369. package/dist/domains/comet-native/native-runner-protocol.js +55 -0
  370. package/dist/domains/comet-native/native-runner-protocol.js.map +1 -0
  371. package/dist/domains/comet-native/native-runtime-package.d.ts +3 -0
  372. package/dist/domains/comet-native/native-runtime-package.d.ts.map +1 -1
  373. package/dist/domains/comet-native/native-runtime-package.js +5 -1
  374. package/dist/domains/comet-native/native-runtime-package.js.map +1 -1
  375. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  376. package/dist/domains/comet-native/native-schema-migration.js +30 -27
  377. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  378. package/dist/domains/comet-native/native-select-command.d.ts.map +1 -1
  379. package/dist/domains/comet-native/native-select-command.js +8 -4
  380. package/dist/domains/comet-native/native-select-command.js.map +1 -1
  381. package/dist/domains/comet-native/native-selection.d.ts.map +1 -1
  382. package/dist/domains/comet-native/native-selection.js +11 -2
  383. package/dist/domains/comet-native/native-selection.js.map +1 -1
  384. package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
  385. package/dist/domains/comet-native/native-show-command.js +37 -0
  386. package/dist/domains/comet-native/native-show-command.js.map +1 -1
  387. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  388. package/dist/domains/comet-native/native-snapshot.js +13 -10
  389. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  390. package/dist/domains/comet-native/native-spec-command.d.ts.map +1 -1
  391. package/dist/domains/comet-native/native-spec-command.js +14 -28
  392. package/dist/domains/comet-native/native-spec-command.js.map +1 -1
  393. package/dist/domains/comet-native/native-specs.js +3 -3
  394. package/dist/domains/comet-native/native-specs.js.map +1 -1
  395. package/dist/domains/comet-native/native-status-command.d.ts.map +1 -1
  396. package/dist/domains/comet-native/native-status-command.js +7 -17
  397. package/dist/domains/comet-native/native-status-command.js.map +1 -1
  398. package/dist/domains/comet-native/native-status-discovery.d.ts +51 -0
  399. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -0
  400. package/dist/domains/comet-native/native-status-discovery.js +299 -0
  401. package/dist/domains/comet-native/native-status-discovery.js.map +1 -0
  402. package/dist/domains/comet-native/native-trajectory-recovery.d.ts.map +1 -1
  403. package/dist/domains/comet-native/native-trajectory-recovery.js +6 -9
  404. package/dist/domains/comet-native/native-trajectory-recovery.js.map +1 -1
  405. package/dist/domains/comet-native/native-transaction.d.ts.map +1 -1
  406. package/dist/domains/comet-native/native-transaction.js +31 -20
  407. package/dist/domains/comet-native/native-transaction.js.map +1 -1
  408. package/dist/domains/comet-native/native-transition-evidence.d.ts.map +1 -1
  409. package/dist/domains/comet-native/native-transition-evidence.js +1 -0
  410. package/dist/domains/comet-native/native-transition-evidence.js.map +1 -1
  411. package/dist/domains/comet-native/native-transition-journal.d.ts.map +1 -1
  412. package/dist/domains/comet-native/native-transition-journal.js +71 -22
  413. package/dist/domains/comet-native/native-transition-journal.js.map +1 -1
  414. package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
  415. package/dist/domains/comet-native/native-transitions.js +167 -15
  416. package/dist/domains/comet-native/native-transitions.js.map +1 -1
  417. package/dist/domains/comet-native/native-types.d.ts +36 -1
  418. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  419. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  420. package/dist/domains/comet-native/native-verification-receipt-runtime.js +18 -100
  421. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  422. package/dist/domains/comet-native/native-verification-report-v2.d.ts +12 -0
  423. package/dist/domains/comet-native/native-verification-report-v2.d.ts.map +1 -0
  424. package/dist/domains/comet-native/native-verification-report-v2.js +141 -0
  425. package/dist/domains/comet-native/native-verification-report-v2.js.map +1 -0
  426. package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
  427. package/dist/domains/comet-native/native-verification-runtime.js +7 -2
  428. package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
  429. package/dist/domains/comet-native/native-verification-scope.d.ts +23 -0
  430. package/dist/domains/comet-native/native-verification-scope.d.ts.map +1 -1
  431. package/dist/domains/comet-native/native-verification-scope.js +106 -19
  432. package/dist/domains/comet-native/native-verification-scope.js.map +1 -1
  433. package/dist/domains/comet-native/native-verifier-protocol.d.ts +49 -0
  434. package/dist/domains/comet-native/native-verifier-protocol.d.ts.map +1 -0
  435. package/dist/domains/comet-native/native-verifier-protocol.js +157 -0
  436. package/dist/domains/comet-native/native-verifier-protocol.js.map +1 -0
  437. package/dist/domains/comet-native/native-workspace-finish.d.ts +61 -0
  438. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -0
  439. package/dist/domains/comet-native/native-workspace-finish.js +332 -0
  440. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -0
  441. package/dist/domains/comet-native/native-workspace-preparation.d.ts +32 -0
  442. package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -0
  443. package/dist/domains/comet-native/native-workspace-preparation.js +324 -0
  444. package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -0
  445. package/dist/domains/comet-native/native-workspace.d.ts +9 -1
  446. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  447. package/dist/domains/comet-native/native-workspace.js +109 -11
  448. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  449. package/dist/domains/dashboard/collector.d.ts +1 -1
  450. package/dist/domains/dashboard/collector.d.ts.map +1 -1
  451. package/dist/domains/dashboard/collector.js +102 -87
  452. package/dist/domains/dashboard/collector.js.map +1 -1
  453. package/dist/domains/dashboard/native-adapter.d.ts +155 -126
  454. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  455. package/dist/domains/dashboard/native-adapter.js +165 -268
  456. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  457. package/dist/domains/dashboard/native-collector.d.ts +5 -4
  458. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  459. package/dist/domains/dashboard/native-collector.js +506 -439
  460. package/dist/domains/dashboard/native-collector.js.map +1 -1
  461. package/dist/domains/dashboard/native-legacy-adapter.d.ts +37 -0
  462. package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -0
  463. package/dist/domains/dashboard/native-legacy-adapter.js +127 -0
  464. package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -0
  465. package/dist/domains/dashboard/server.d.ts.map +1 -1
  466. package/dist/domains/dashboard/server.js +5 -3
  467. package/dist/domains/dashboard/server.js.map +1 -1
  468. package/dist/domains/dashboard/types.d.ts +5 -0
  469. package/dist/domains/dashboard/types.d.ts.map +1 -1
  470. package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-B5cFR6hS.js +1 -0
  471. package/dist/domains/dashboard/web/assets/arc-CVQDtMsu.js +1 -0
  472. package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-C0v0kULK.js +36 -0
  473. package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-DpHLuxu4.js +132 -0
  474. package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-Ca5zba3N.js → c4Diagram-5PPSVZJV-BHnFxUs1.js} +1 -1
  475. package/dist/domains/dashboard/web/assets/channel-eM0x3m1G.js +1 -0
  476. package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-Bj6HWRwi.js → chunk-2GRJ4B5K-CGC9gh5n.js} +1 -1
  477. package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-B1kXfg5N.js → chunk-2Q5K7J3B-l4puLU_O.js} +1 -1
  478. package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-ls9jQHZc.js +231 -0
  479. package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-BAJLB5V6.js → chunk-5VM5RSS4-BVavmTEq.js} +1 -1
  480. package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-Dungt2g9.js +88 -0
  481. package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-CwghIMO9.js → chunk-GF5L2VYU-BidXO_ZP.js} +5 -5
  482. package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-JYluRsP-.js → chunk-JWPE2WC7-57L5Up5X.js} +1 -1
  483. package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-CCVPBm0J.js → chunk-KBJHAD2P-C5u5vbwr.js} +1 -1
  484. package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-CvLz21I2.js +1 -0
  485. package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-DfYm7pN7.js → chunk-XXDRQBXY-D5nJpckG.js} +1 -1
  486. package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CEFhao2K.js +1 -0
  487. package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CEFhao2K.js +1 -0
  488. package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-BBrkuiAU.js → cose-bilkent-JH36ORCC-Dp0JAGyE.js} +1 -1
  489. package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-DlFhgQHt.js → cynefin-VYW2F7L2-EjC54l1g.js} +2 -2
  490. package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-CpYrW3w3.js +62 -0
  491. package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-h5K39rCk.js +4 -0
  492. package/dist/domains/dashboard/web/assets/demo-BfLsKrIL.js +45 -0
  493. package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-CKQj9O4H.js +30 -0
  494. package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-BQahyP-C.js → diagram-B4RE2ZJO-DXRIYcnW.js} +3 -3
  495. package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-wWutQYmv.js +24 -0
  496. package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-EgXLJQYi.js +24 -0
  497. package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-CsQRXDQZ.js +41 -0
  498. package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-gm328Eho.js +1 -0
  499. package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-BbbMVUx_.js +85 -0
  500. package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-1Y7scCns.js +156 -0
  501. package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-BAoBqczv.js +292 -0
  502. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-DCxvMAUJ.js → gitGraphDiagram-DS77QQ5N-CMUAyEzl.js} +3 -3
  503. package/dist/domains/dashboard/web/assets/{graph--OzhPTMs.js → graph-DOmOIIwC.js} +1 -1
  504. package/dist/domains/dashboard/web/assets/{index-Blit0P5Z.js → index-CCApJ0Yr.js} +1 -1
  505. package/dist/domains/dashboard/web/assets/index-DWdm_XBi.js +257 -0
  506. package/dist/domains/dashboard/web/assets/index-DhhbseFJ.css +1 -0
  507. package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-9qXEkzDe.js → infoDiagram-6WML65LV-BaCdtYYC.js} +1 -1
  508. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-Dkf5othW.js → ishikawaDiagram-WSZJBQD7-DQQlNnjU.js} +4 -4
  509. package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-C2_IkO4s.js → journeyDiagram-NVQOT4AX-DW9wUMqn.js} +1 -1
  510. package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-BxWgu4DL.js → kanban-definition-27J2QSJJ-C_ITaZ0q.js} +7 -7
  511. package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +1 -0
  512. package/dist/domains/dashboard/web/assets/{linear-Dkr6p-Ro.js → linear-DXOo6ZRT.js} +1 -1
  513. package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +1 -0
  514. package/dist/domains/dashboard/web/assets/mermaid.core-ol-0NI97.js +306 -0
  515. package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-C9xyxGfa.js → mindmap-definition-FAOFIHXS-CHF_HOLV.js} +1 -1
  516. package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-wQEvkNF8.js +1 -0
  517. package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-C3H3kiIP.js +39 -0
  518. package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +3 -0
  519. package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-Cy6iOcxc.js → quadrantDiagram-CIZ2JOQS-S0FdVzJb.js} +4 -4
  520. package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-DCDXDaVg.js +1 -0
  521. package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-B_gZONhx.js → requirementDiagram-LRYGKXZP-BW8J4gO_.js} +1 -1
  522. package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-DQQBmLoy.js +40 -0
  523. package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-2tDcli0Y.js +162 -0
  524. package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-4sEZLBKb.js +1 -0
  525. package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-OgPb8pyR.js +1 -0
  526. package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-CiDNPr4P.js +1 -0
  527. package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-DR7lwtxd.js +2 -0
  528. package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-DggHFP9q.js +8 -0
  529. package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-DvONX2YQ.js → timeline-definition-Z64GVDOM-DNIJVlQV.js} +4 -4
  530. package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-CClhw4QZ.js +34 -0
  531. package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-cf39WX2o.js → wardleyDiagram-T6FBY63Y-DzR3aFPS.js} +3 -3
  532. package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DZhq0ZRj.js +7 -0
  533. package/dist/domains/dashboard/web/index.html +16 -16
  534. package/dist/domains/dashboard/workspace.d.ts +24 -0
  535. package/dist/domains/dashboard/workspace.d.ts.map +1 -0
  536. package/dist/domains/dashboard/workspace.js +87 -0
  537. package/dist/domains/dashboard/workspace.js.map +1 -0
  538. package/dist/domains/eval/index.d.ts +3 -0
  539. package/dist/domains/eval/index.d.ts.map +1 -1
  540. package/dist/domains/eval/index.js +3 -0
  541. package/dist/domains/eval/index.js.map +1 -1
  542. package/dist/domains/eval/standalone-context.d.ts +19 -0
  543. package/dist/domains/eval/standalone-context.d.ts.map +1 -0
  544. package/dist/domains/eval/standalone-context.js +107 -0
  545. package/dist/domains/eval/standalone-context.js.map +1 -0
  546. package/dist/domains/eval/standalone-static-collect.d.ts +22 -0
  547. package/dist/domains/eval/standalone-static-collect.d.ts.map +1 -0
  548. package/dist/domains/eval/standalone-static-collect.js +779 -0
  549. package/dist/domains/eval/standalone-static-collect.js.map +1 -0
  550. package/dist/domains/eval/user-environment.d.ts +6 -0
  551. package/dist/domains/eval/user-environment.d.ts.map +1 -0
  552. package/dist/domains/eval/user-environment.js +73 -0
  553. package/dist/domains/eval/user-environment.js.map +1 -0
  554. package/dist/domains/integrations/openspec.d.ts +1 -1
  555. package/dist/domains/integrations/openspec.d.ts.map +1 -1
  556. package/dist/domains/integrations/openspec.js +110 -26
  557. package/dist/domains/integrations/openspec.js.map +1 -1
  558. package/dist/domains/integrations/superpowers.d.ts +5 -1
  559. package/dist/domains/integrations/superpowers.d.ts.map +1 -1
  560. package/dist/domains/integrations/superpowers.js +21 -2
  561. package/dist/domains/integrations/superpowers.js.map +1 -1
  562. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  563. package/dist/domains/skill/platform-inspect.js +11 -3
  564. package/dist/domains/skill/platform-inspect.js.map +1 -1
  565. package/dist/domains/skill/platform-install.d.ts +8 -2
  566. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  567. package/dist/domains/skill/platform-install.js +115 -34
  568. package/dist/domains/skill/platform-install.js.map +1 -1
  569. package/dist/domains/skill/project-instructions.d.ts.map +1 -1
  570. package/dist/domains/skill/project-instructions.js +5 -3
  571. package/dist/domains/skill/project-instructions.js.map +1 -1
  572. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  573. package/dist/domains/skill/uninstall.js +69 -15
  574. package/dist/domains/skill/uninstall.js.map +1 -1
  575. package/dist/domains/workflow-contract/hook-write-policy.d.ts +9 -0
  576. package/dist/domains/workflow-contract/hook-write-policy.d.ts.map +1 -0
  577. package/dist/domains/workflow-contract/hook-write-policy.js +52 -0
  578. package/dist/domains/workflow-contract/hook-write-policy.js.map +1 -0
  579. package/dist/domains/workflow-contract/index.d.ts +3 -0
  580. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  581. package/dist/domains/workflow-contract/index.js +2 -0
  582. package/dist/domains/workflow-contract/index.js.map +1 -1
  583. package/dist/domains/workflow-contract/project-config.d.ts +3 -1
  584. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  585. package/dist/domains/workflow-contract/project-config.js +119 -19
  586. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  587. package/dist/domains/workflow-contract/project-gitignore.d.ts +9 -0
  588. package/dist/domains/workflow-contract/project-gitignore.d.ts.map +1 -0
  589. package/dist/domains/workflow-contract/project-gitignore.js +108 -0
  590. package/dist/domains/workflow-contract/project-gitignore.js.map +1 -0
  591. package/dist/domains/workflow-contract/protected-project-path.d.ts +13 -0
  592. package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
  593. package/dist/domains/workflow-contract/protected-project-path.js +83 -0
  594. package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
  595. package/dist/domains/workflow-contract/types.d.ts +4 -0
  596. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  597. package/dist/platform/install/platforms.d.ts +3 -1
  598. package/dist/platform/install/platforms.d.ts.map +1 -1
  599. package/dist/platform/install/platforms.js +22 -2
  600. package/dist/platform/install/platforms.js.map +1 -1
  601. package/dist/platform/paths/git-worktree.d.ts +8 -1
  602. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  603. package/dist/platform/paths/git-worktree.js +41 -7
  604. package/dist/platform/paths/git-worktree.js.map +1 -1
  605. package/dist/platform/process/external-command.d.ts +13 -0
  606. package/dist/platform/process/external-command.d.ts.map +1 -0
  607. package/dist/platform/process/external-command.js +45 -0
  608. package/dist/platform/process/external-command.js.map +1 -0
  609. package/dist/platform/process/git.d.ts +12 -0
  610. package/dist/platform/process/git.d.ts.map +1 -0
  611. package/dist/platform/process/git.js +86 -0
  612. package/dist/platform/process/git.js.map +1 -0
  613. package/dist/platform/process/spawn-command.d.ts +8 -0
  614. package/dist/platform/process/spawn-command.d.ts.map +1 -0
  615. package/dist/platform/process/spawn-command.js +113 -0
  616. package/dist/platform/process/spawn-command.js.map +1 -0
  617. package/eval/.env.example +115 -0
  618. package/eval/README.md +237 -14
  619. package/eval/langfuse/.env.example +9 -0
  620. package/eval/langfuse/tests/conftest.py +146 -0
  621. package/eval/langfuse/tests/tasks/test_tasks.py +109 -0
  622. package/eval/langfuse/tests/test_adapter.py +272 -0
  623. package/eval/langsmith/.env.example +16 -0
  624. package/eval/langsmith/tests/conftest.py +10 -1
  625. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +4 -2
  626. package/eval/local/tasks/comet-native-clarification/validation/test_native_clarification.py +9 -21
  627. package/eval/local/tasks/comet-native-clarification-depth/validation/test_native_clarification_depth.py +4 -7
  628. package/eval/local/tasks/comet-native-clarification-modes/validation/test_native_clarification_modes.py +4 -10
  629. package/eval/local/tasks/comet-native-interrupted-transition/instruction.md +1 -1
  630. package/eval/local/tasks/comet-native-interrupted-transition/validation/test_native_interrupted_transition.py +15 -16
  631. package/eval/local/tasks/comet-native-repository-fact/instruction.md +2 -2
  632. package/eval/local/tasks/comet-native-repository-fact/validation/test_native_repository_fact.py +8 -2
  633. package/eval/local/tasks/comet-native-wave-b-decision-resume/instruction.md +8 -4
  634. package/eval/local/tasks/comet-native-wave-b-decision-resume/task.toml +6 -6
  635. package/eval/local/tasks/comet-native-wave-b-decision-resume/validation/test_native_wave_b_decision_resume.py +126 -135
  636. package/eval/local/tasks/comet-native-wave-c-verification-integrity/instruction.md +6 -6
  637. package/eval/local/tasks/comet-native-wave-c-verification-integrity/task.toml +8 -8
  638. package/eval/local/tasks/comet-native-wave-c-verification-integrity/validation/test_native_wave_c_verification_integrity.py +97 -317
  639. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +7 -7
  640. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +4 -4
  641. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +130 -199
  642. package/eval/local/tasks/comet-native-wave-e-parallel-safety/instruction.md +5 -5
  643. package/eval/local/tasks/comet-native-wave-e-parallel-safety/task.toml +8 -8
  644. package/eval/local/tasks/comet-native-wave-e-parallel-safety/validation/test_native_wave_e_parallel_safety.py +135 -239
  645. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +2 -2
  646. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/instruction.md +3 -3
  647. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/task.toml +6 -6
  648. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/validation/test_native_wave_f_dashboard_readonly.py +81 -439
  649. package/eval/local/tasks/comet-native-workflow/instruction.md +5 -4
  650. package/eval/local/tasks/comet-native-workflow/validation/test_native_workflow.py +145 -502
  651. package/eval/local/tasks/index.yaml +5 -5
  652. package/eval/local/tests/conftest.py +701 -80
  653. package/eval/local/tests/scaffold/fixtures/custom-agent/adapter.yaml +19 -0
  654. package/eval/local/tests/scaffold/test_agents.py +76 -0
  655. package/eval/local/tests/scaffold/test_aligned_comparison.py +70 -0
  656. package/eval/local/tests/scaffold/test_auto_tasks.py +350 -0
  657. package/eval/local/tests/scaffold/test_conftest_helpers.py +267 -18
  658. package/eval/local/tests/scaffold/test_custom_agents.py +174 -0
  659. package/eval/local/tests/scaffold/test_eval_context.py +217 -0
  660. package/eval/local/tests/scaffold/test_execution.py +364 -0
  661. package/eval/local/tests/scaffold/test_inline_tasks.py +56 -0
  662. package/eval/local/tests/scaffold/test_langfuse_trajectory.py +263 -0
  663. package/eval/local/tests/scaffold/test_langsmith_conftest.py +63 -0
  664. package/eval/local/tests/scaffold/test_logging.py +162 -0
  665. package/eval/local/tests/scaffold/test_manifest_tasks.py +76 -0
  666. package/eval/local/tests/scaffold/test_manifests.py +396 -0
  667. package/eval/local/tests/scaffold/test_native_aligned_eval.py +163 -35
  668. package/eval/local/tests/scaffold/test_native_wave_evaluations.py +75 -2054
  669. package/eval/local/tests/scaffold/test_profiles.py +64 -6
  670. package/eval/local/tests/scaffold/test_task_resolution.py +212 -0
  671. package/eval/local/tests/scaffold/test_tasks.py +38 -52
  672. package/eval/local/tests/scaffold/test_utils.py +480 -4
  673. package/eval/local/tests/tasks/test_tasks.py +219 -17
  674. package/eval/local/treatments/comet/comet_native_phase1.yaml +7 -4
  675. package/eval/pyproject.toml +9 -4
  676. package/eval/scaffold/__init__.py +6 -0
  677. package/eval/scaffold/docker/agent-overlay.Dockerfile +41 -0
  678. package/eval/scaffold/python/__init__.py +128 -20
  679. package/eval/scaffold/python/agents.py +239 -0
  680. package/eval/scaffold/python/aligned_comparison.py +156 -27
  681. package/eval/scaffold/python/auto_tasks.py +700 -0
  682. package/eval/scaffold/python/custom_agents.py +172 -0
  683. package/eval/scaffold/python/eval_context.py +236 -0
  684. package/eval/scaffold/python/eval_schema.py +135 -0
  685. package/eval/scaffold/python/execution.py +544 -0
  686. package/eval/scaffold/python/generated_task_cache.py +230 -0
  687. package/eval/scaffold/python/generic_llm_judge.py +41 -14
  688. package/eval/scaffold/python/inline_tasks.py +118 -0
  689. package/eval/scaffold/python/judge_config.py +158 -37
  690. package/eval/scaffold/python/langfuse_adapter.py +1023 -0
  691. package/eval/scaffold/python/llm_judge.py +68 -11
  692. package/eval/scaffold/python/logging.py +157 -17
  693. package/eval/scaffold/python/manifest_tasks.py +69 -0
  694. package/eval/scaffold/python/manifests.py +443 -22
  695. package/eval/scaffold/python/native_eval.py +10 -5
  696. package/eval/scaffold/python/paths.py +11 -1
  697. package/eval/scaffold/python/task_resolution.py +176 -0
  698. package/eval/scaffold/python/tasks.py +17 -4
  699. package/eval/scaffold/python/utils.py +167 -11
  700. package/eval/scaffold/python/validation/core.py +48 -2
  701. package/eval/scaffold/python/validation/generic_rubric.py +9 -0
  702. package/eval/scaffold/python/validation/native_v4.py +249 -0
  703. package/eval/scaffold/python/validation/native_wave.py +4 -5
  704. package/eval/scaffold/python/validation/native_workflow.py +199 -98
  705. package/eval/scaffold/python/validation/rubric.py +130 -2
  706. package/eval/scaffold/shell/agent-runtime-config.sh +88 -0
  707. package/eval/scaffold/shell/docker.sh +534 -33
  708. package/eval/scaffold/shell/run-agent-runtime.sh +49 -0
  709. package/eval/scaffold/shell/run-claude-loop.sh +153 -14
  710. package/eval/schemas/comet.eval/v1alpha1.schema.json +244 -0
  711. package/package.json +9 -3
  712. package/assets/skills/comet-native/scripts/comet-native-check.mjs +0 -179
  713. package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +0 -179
  714. package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +0 -151
  715. package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +0 -187
  716. package/dist/domains/comet-native/native-check-entry.d.ts +0 -2
  717. package/dist/domains/comet-native/native-check-entry.d.ts.map +0 -1
  718. package/dist/domains/comet-native/native-check-entry.js +0 -4
  719. package/dist/domains/comet-native/native-check-entry.js.map +0 -1
  720. package/dist/domains/comet-native/native-checkpoint-entry.d.ts +0 -2
  721. package/dist/domains/comet-native/native-checkpoint-entry.d.ts.map +0 -1
  722. package/dist/domains/comet-native/native-checkpoint-entry.js +0 -4
  723. package/dist/domains/comet-native/native-checkpoint-entry.js.map +0 -1
  724. package/dist/domains/comet-native/native-evidence-entry.d.ts +0 -2
  725. package/dist/domains/comet-native/native-evidence-entry.d.ts.map +0 -1
  726. package/dist/domains/comet-native/native-evidence-entry.js +0 -4
  727. package/dist/domains/comet-native/native-evidence-entry.js.map +0 -1
  728. package/dist/domains/comet-native/native-receipt-entry.d.ts +0 -2
  729. package/dist/domains/comet-native/native-receipt-entry.d.ts.map +0 -1
  730. package/dist/domains/comet-native/native-receipt-entry.js +0 -4
  731. package/dist/domains/comet-native/native-receipt-entry.js.map +0 -1
  732. package/dist/domains/dashboard/web/assets/arc-ClrSujVb.js +0 -1
  733. package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR-B4A_t84A.js +0 -36
  734. package/dist/domains/dashboard/web/assets/blockDiagram-GPEHLZMM-D72u2953.js +0 -132
  735. package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +0 -1
  736. package/dist/domains/dashboard/web/assets/chunk-AQP2D5EJ-BA_zgMXZ.js +0 -231
  737. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-BpA7BPgX.js +0 -1
  738. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-BpA7BPgX.js +0 -1
  739. package/dist/domains/dashboard/web/assets/dagre-BM42HDAG-B0Bk5oiP.js +0 -4
  740. package/dist/domains/dashboard/web/assets/demo-DZYPLZpF.js +0 -25
  741. package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-tvTUiBA2.js +0 -43
  742. package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-BZfcK29q.js +0 -10
  743. package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-D5bJnW2C.js +0 -24
  744. package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-DTwWdzWJ.js +0 -24
  745. package/dist/domains/dashboard/web/assets/erDiagram-TEJ5UH35-BbvrdCp9.js +0 -85
  746. package/dist/domains/dashboard/web/assets/flowDiagram-I6XJVG4X-DgbR7Tcc.js +0 -162
  747. package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-wWMOA7F4.js +0 -292
  748. package/dist/domains/dashboard/web/assets/index-Bk1o-4VO.css +0 -1
  749. package/dist/domains/dashboard/web/assets/index-g8vyW0R_.js +0 -257
  750. package/dist/domains/dashboard/web/assets/layout-SsrduOYp.js +0 -1
  751. package/dist/domains/dashboard/web/assets/mermaid.core-DZUcsoG4.js +0 -301
  752. package/dist/domains/dashboard/web/assets/pieDiagram-4H26LBE5-Dn67tdOF.js +0 -30
  753. package/dist/domains/dashboard/web/assets/purify.es-VaSPOPhr.js +0 -3
  754. package/dist/domains/dashboard/web/assets/sankeyDiagram-5OEKKPKP-C3u-4dOk.js +0 -40
  755. package/dist/domains/dashboard/web/assets/sequenceDiagram-3UESZ5HK-Xd3ByTVF.js +0 -162
  756. package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-CJGHL7Up.js +0 -1
  757. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +0 -1
  758. package/dist/domains/dashboard/web/assets/vennDiagram-CIIHVFJN-B-L4qWy4.js +0 -34
  759. package/dist/domains/dashboard/web/assets/xychartDiagram-2RQKCTM6-Dk1vcm3u.js +0 -7
  760. /package/assets/skills/{comet → comet-classic}/reference/classic-layout.md +0 -0
  761. /package/assets/skills-zh/{comet → comet-classic}/reference/classic-layout.md +0 -0
@@ -1,207 +1,263 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var JN=Object.create;var Xf=Object.defineProperty;var zN=Object.getOwnPropertyDescriptor;var GN=Object.getOwnPropertyNames;var UN=Object.getPrototypeOf,KN=Object.prototype.hasOwnProperty;var ho=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var YN=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of GN(t))!KN.call(e,r)&&r!==i&&Xf(e,r,{get:()=>t[r],enumerable:!(n=zN(t,r))||n.enumerable});return e};var po=(e,t,i)=>(i=e!=null?JN(UN(e)):{},YN(t||!e||!e.__esModule?Xf(i,"default",{value:e,enumerable:!0}):i,e));var V=C(Ne=>{"use strict";var tl=Symbol.for("yaml.alias"),nh=Symbol.for("yaml.document"),mo=Symbol.for("yaml.map"),rh=Symbol.for("yaml.pair"),il=Symbol.for("yaml.scalar"),vo=Symbol.for("yaml.seq"),Wt=Symbol.for("yaml.node.type"),eb=e=>!!e&&typeof e=="object"&&e[Wt]===tl,tb=e=>!!e&&typeof e=="object"&&e[Wt]===nh,ib=e=>!!e&&typeof e=="object"&&e[Wt]===mo,nb=e=>!!e&&typeof e=="object"&&e[Wt]===rh,ah=e=>!!e&&typeof e=="object"&&e[Wt]===il,rb=e=>!!e&&typeof e=="object"&&e[Wt]===vo;function oh(e){if(e&&typeof e=="object")switch(e[Wt]){case mo:case vo:return!0}return!1}function ab(e){if(e&&typeof e=="object")switch(e[Wt]){case tl:case mo:case il:case vo:return!0}return!1}var ob=e=>(ah(e)||oh(e))&&!!e.anchor;Ne.ALIAS=tl;Ne.DOC=nh;Ne.MAP=mo;Ne.NODE_TYPE=Wt;Ne.PAIR=rh;Ne.SCALAR=il;Ne.SEQ=vo;Ne.hasAnchor=ob;Ne.isAlias=eb;Ne.isCollection=oh;Ne.isDocument=tb;Ne.isMap=ib;Ne.isNode=ab;Ne.isPair=nb;Ne.isScalar=ah;Ne.isSeq=rb});var Ar=C(nl=>{"use strict";var me=V(),Be=Symbol("break visit"),sh=Symbol("skip children"),xt=Symbol("remove node");function go(e,t){let i=ch(t);me.isDocument(e)?Cn(null,e.contents,i,Object.freeze([e]))===xt&&(e.contents=null):Cn(null,e,i,Object.freeze([]))}go.BREAK=Be;go.SKIP=sh;go.REMOVE=xt;function Cn(e,t,i,n){let r=lh(e,t,i,n);if(me.isNode(r)||me.isPair(r))return uh(e,n,r),Cn(e,r,i,n);if(typeof r!="symbol"){if(me.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=Cn(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===xt&&(t.items.splice(a,1),a-=1)}}}else if(me.isPair(t)){n=Object.freeze(n.concat(t));let a=Cn("key",t.key,i,n);if(a===Be)return Be;a===xt&&(t.key=null);let o=Cn("value",t.value,i,n);if(o===Be)return Be;o===xt&&(t.value=null)}}return r}async function wo(e,t){let i=ch(t);me.isDocument(e)?await Pn(null,e.contents,i,Object.freeze([e]))===xt&&(e.contents=null):await Pn(null,e,i,Object.freeze([]))}wo.BREAK=Be;wo.SKIP=sh;wo.REMOVE=xt;async function Pn(e,t,i,n){let r=await lh(e,t,i,n);if(me.isNode(r)||me.isPair(r))return uh(e,n,r),Pn(e,r,i,n);if(typeof r!="symbol"){if(me.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await Pn(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===Be)return Be;o===xt&&(t.items.splice(a,1),a-=1)}}}else if(me.isPair(t)){n=Object.freeze(n.concat(t));let a=await Pn("key",t.key,i,n);if(a===Be)return Be;a===xt&&(t.key=null);let o=await Pn("value",t.value,i,n);if(o===Be)return Be;o===xt&&(t.value=null)}}return r}function ch(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 lh(e,t,i,n){if(typeof i=="function")return i(e,t,n);if(me.isMap(t))return i.Map?.(e,t,n);if(me.isSeq(t))return i.Seq?.(e,t,n);if(me.isPair(t))return i.Pair?.(e,t,n);if(me.isScalar(t))return i.Scalar?.(e,t,n);if(me.isAlias(t))return i.Alias?.(e,t,n)}function uh(e,t,i){let n=t[t.length-1];if(me.isCollection(n))n.items[e]=i;else if(me.isPair(n))e==="key"?n.key=i:n.value=i;else if(me.isDocument(n))n.contents=i;else{let r=me.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}nl.visit=go;nl.visitAsync=wo});var rl=C(fh=>{"use strict";var dh=V(),sb=Ar(),cb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},lb=e=>e.replace(/[!,[\]{}]/g,t=>cb[t]),xr=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+lb(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&&dh.isNode(t.contents)){let a={};sb.visit(t.contents,(o,s)=>{dh.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
- `)}};xr.defaultYaml={explicit:!1,version:"1.2"};xr.defaultTags={"!!":"tag:yaml.org,2002:"};fh.Directives=xr});var yo=C(Tr=>{"use strict";var hh=V(),ub=Ar();function db(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 ph(e){let t=new Set;return ub.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function mh(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function fb(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=ph(e));let o=mh(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(hh.isScalar(o.node)||hh.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}}Tr.anchorIsValid=db;Tr.anchorNames=ph;Tr.createNodeAnchors=fb;Tr.findNewAnchor=mh});var al=C(vh=>{"use strict";function Ir(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=Ir(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=Ir(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=Ir(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=Ir(e,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return e.call(t,i,n)}vh.applyReviver=Ir});var li=C(wh=>{"use strict";var hb=V();function gh(e,t,i){if(Array.isArray(e))return e.map((n,r)=>gh(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!hb.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}wh.toJS=gh});var No=C(Nh=>{"use strict";var pb=al(),yh=V(),mb=li(),ol=class{constructor(t){Object.defineProperty(this,yh.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(!yh.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=mb.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?pb.applyReviver(a,{"":s},"",s):s}};Nh.NodeBase=ol});var _r=C(bh=>{"use strict";var vb=yo(),gb=Ar(),An=V(),wb=No(),yb=li(),sl=class extends wb.NodeBase{constructor(t){super(An.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=[],gb.visit(t,{Node:(a,o)=>{(An.isAlias(o)||An.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||(yb.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=bo(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(vb.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 bo(e,t,i){if(An.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(An.isCollection(t)){let n=0;for(let r of t.items){let a=bo(e,r,i);a>n&&(n=a)}return n}else if(An.isPair(t)){let n=bo(e,t.key,i),r=bo(e,t.value,i);return Math.max(n,r)}return 1}bh.Alias=sl});var de=C(cl=>{"use strict";var Nb=V(),bb=No(),kb=li(),Sb=e=>!e||typeof e!="function"&&typeof e!="object",ui=class extends bb.NodeBase{constructor(t){super(Nb.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:kb.toJS(this.value,t,i)}toString(){return String(this.value)}};ui.BLOCK_FOLDED="BLOCK_FOLDED";ui.BLOCK_LITERAL="BLOCK_LITERAL";ui.PLAIN="PLAIN";ui.QUOTE_DOUBLE="QUOTE_DOUBLE";ui.QUOTE_SINGLE="QUOTE_SINGLE";cl.Scalar=ui;cl.isScalarValue=Sb});var jr=C(Sh=>{"use strict";var Eb=_r(),Yi=V(),kh=de(),Rb="tag:yaml.org,2002:";function Cb(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 Pb(e,t,i){if(Yi.isDocument(e)&&(e=e.contents),Yi.isNode(e))return e;if(Yi.isPair(e)){let d=i.schema[Yi.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 Eb.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Rb+t.slice(2));let l=Cb(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new kh.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Yi.MAP]:Symbol.iterator in Object(e)?o[Yi.SEQ]:o[Yi.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 kh.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Sh.createNode=Pb});var So=C(ko=>{"use strict";var Ab=jr(),Tt=V(),xb=No();function ll(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 Ab.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 Eh=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ul=class extends xb.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=>Tt.isNode(n)||Tt.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Eh(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(Tt.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,ll(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(Tt.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&&Tt.isScalar(a)?a.value:a:Tt.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Tt.isPair(i))return!1;let n=i.value;return n==null||t&&Tt.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 Tt.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(Tt.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,ll(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};ko.Collection=ul;ko.collectionFromPath=ll;ko.isEmptyPath=Eh});var Or=C(Eo=>{"use strict";var Tb=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function dl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ib=(e,t,i)=>e.endsWith(`
6
- `)?dl(i,t):i.includes(`
4
+ var JS=Object.create;var sm=Object.defineProperty;var GS=Object.getOwnPropertyDescriptor;var US=Object.getOwnPropertyNames;var KS=Object.getPrototypeOf,YS=Object.prototype.hasOwnProperty;var Ps=(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 x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var XS=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of US(t))!YS.call(e,n)&&n!==i&&sm(e,n,{get:()=>t[n],enumerable:!(r=GS(t,n))||r.enumerable});return e};var hn=(e,t,i)=>(i=e!=null?JS(KS(e)):{},XS(t||!e||!e.__esModule?sm(i,"default",{value:e,enumerable:!0}):i,e));var J=x(Ce=>{"use strict";var Fu=Symbol.for("yaml.alias"),hm=Symbol.for("yaml.document"),Rs=Symbol.for("yaml.map"),pm=Symbol.for("yaml.pair"),Lu=Symbol.for("yaml.scalar"),xs=Symbol.for("yaml.seq"),Ni=Symbol.for("yaml.node.type"),tE=e=>!!e&&typeof e=="object"&&e[Ni]===Fu,iE=e=>!!e&&typeof e=="object"&&e[Ni]===hm,rE=e=>!!e&&typeof e=="object"&&e[Ni]===Rs,nE=e=>!!e&&typeof e=="object"&&e[Ni]===pm,mm=e=>!!e&&typeof e=="object"&&e[Ni]===Lu,aE=e=>!!e&&typeof e=="object"&&e[Ni]===xs;function vm(e){if(e&&typeof e=="object")switch(e[Ni]){case Rs:case xs:return!0}return!1}function oE(e){if(e&&typeof e=="object")switch(e[Ni]){case Fu:case Rs:case Lu:case xs:return!0}return!1}var sE=e=>(mm(e)||vm(e))&&!!e.anchor;Ce.ALIAS=Fu;Ce.DOC=hm;Ce.MAP=Rs;Ce.NODE_TYPE=Ni;Ce.PAIR=pm;Ce.SCALAR=Lu;Ce.SEQ=xs;Ce.hasAnchor=sE;Ce.isAlias=tE;Ce.isCollection=vm;Ce.isDocument=iE;Ce.isMap=rE;Ce.isNode=oE;Ce.isPair=nE;Ce.isScalar=mm;Ce.isSeq=aE});var Ia=x(Bu=>{"use strict";var Ee=J(),tt=Symbol("break visit"),gm=Symbol("skip children"),ei=Symbol("remove node");function Cs(e,t){let i=wm(t);Ee.isDocument(e)?pn(null,e.contents,i,Object.freeze([e]))===ei&&(e.contents=null):pn(null,e,i,Object.freeze([]))}Cs.BREAK=tt;Cs.SKIP=gm;Cs.REMOVE=ei;function pn(e,t,i,r){let n=ym(e,t,i,r);if(Ee.isNode(n)||Ee.isPair(n))return Nm(e,r,n),pn(e,n,i,r);if(typeof n!="symbol"){if(Ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=pn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===tt)return tt;o===ei&&(t.items.splice(a,1),a-=1)}}}else if(Ee.isPair(t)){r=Object.freeze(r.concat(t));let a=pn("key",t.key,i,r);if(a===tt)return tt;a===ei&&(t.key=null);let o=pn("value",t.value,i,r);if(o===tt)return tt;o===ei&&(t.value=null)}}return n}async function As(e,t){let i=wm(t);Ee.isDocument(e)?await mn(null,e.contents,i,Object.freeze([e]))===ei&&(e.contents=null):await mn(null,e,i,Object.freeze([]))}As.BREAK=tt;As.SKIP=gm;As.REMOVE=ei;async function mn(e,t,i,r){let n=await ym(e,t,i,r);if(Ee.isNode(n)||Ee.isPair(n))return Nm(e,r,n),mn(e,n,i,r);if(typeof n!="symbol"){if(Ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await mn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===tt)return tt;o===ei&&(t.items.splice(a,1),a-=1)}}}else if(Ee.isPair(t)){r=Object.freeze(r.concat(t));let a=await mn("key",t.key,i,r);if(a===tt)return tt;a===ei&&(t.key=null);let o=await mn("value",t.value,i,r);if(o===tt)return tt;o===ei&&(t.value=null)}}return n}function wm(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 ym(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(Ee.isMap(t))return i.Map?.(e,t,r);if(Ee.isSeq(t))return i.Seq?.(e,t,r);if(Ee.isPair(t))return i.Pair?.(e,t,r);if(Ee.isScalar(t))return i.Scalar?.(e,t,r);if(Ee.isAlias(t))return i.Alias?.(e,t,r)}function Nm(e,t,i){let r=t[t.length-1];if(Ee.isCollection(r))r.items[e]=i;else if(Ee.isPair(r))e==="key"?r.key=i:r.value=i;else if(Ee.isDocument(r))r.contents=i;else{let n=Ee.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Bu.visit=Cs;Bu.visitAsync=As});var qu=x(km=>{"use strict";var bm=J(),cE=Ia(),lE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},uE=e=>e.replace(/[!,[\]{}]/g,t=>lE[t]),ja=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+uE(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&bm.isNode(t.contents)){let a={};cE.visit(t.contents,(o,s)=>{bm.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
+ `)}};ja.defaultYaml={explicit:!1,version:"1.2"};ja.defaultTags={"!!":"tag:yaml.org,2002:"};km.Directives=ja});var _s=x($a=>{"use strict";var Sm=J(),dE=Ia();function fE(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 Em(e){let t=new Set;return dE.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Pm(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function hE(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Em(e));let o=Pm(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Sm.isScalar(o.node)||Sm.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}}$a.anchorIsValid=fE;$a.anchorNames=Em;$a.createNodeAnchors=hE;$a.findNewAnchor=Pm});var Vu=x(Rm=>{"use strict";function Oa(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Oa(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Oa(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Oa(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Oa(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Rm.applyReviver=Oa});var Mi=x(Cm=>{"use strict";var pE=J();function xm(e,t,i){if(Array.isArray(e))return e.map((r,n)=>xm(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!pE.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Cm.toJS=xm});var Ts=x(_m=>{"use strict";var mE=Vu(),Am=J(),vE=Mi(),Wu=class{constructor(t){Object.defineProperty(this,Am.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Am.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=vE.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?mE.applyReviver(a,{"":s},"",s):s}};_m.NodeBase=Wu});var Ha=x(Tm=>{"use strict";var gE=_s(),wE=Ia(),vn=J(),yE=Ts(),NE=Mi(),zu=class extends yE.NodeBase{constructor(t){super(vn.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],wE.visit(t,{Node:(a,o)=>{(vn.isAlias(o)||vn.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(NE.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=Is(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(gE.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Is(e,t,i){if(vn.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(vn.isCollection(t)){let r=0;for(let n of t.items){let a=Is(e,n,i);a>r&&(r=a)}return r}else if(vn.isPair(t)){let r=Is(e,t.key,i),n=Is(e,t.value,i);return Math.max(r,n)}return 1}Tm.Alias=zu});var ye=x(Ju=>{"use strict";var bE=J(),kE=Ts(),SE=Mi(),EE=e=>!e||typeof e!="function"&&typeof e!="object",Fi=class extends kE.NodeBase{constructor(t){super(bE.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:SE.toJS(this.value,t,i)}toString(){return String(this.value)}};Fi.BLOCK_FOLDED="BLOCK_FOLDED";Fi.BLOCK_LITERAL="BLOCK_LITERAL";Fi.PLAIN="PLAIN";Fi.QUOTE_DOUBLE="QUOTE_DOUBLE";Fi.QUOTE_SINGLE="QUOTE_SINGLE";Ju.Scalar=Fi;Ju.isScalarValue=EE});var Da=x(jm=>{"use strict";var PE=Ha(),$r=J(),Im=ye(),RE="tag:yaml.org,2002:";function xE(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function CE(e,t,i){if($r.isDocument(e)&&(e=e.contents),$r.isNode(e))return e;if($r.isPair(e)){let d=i.schema[$r.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new PE.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=RE+t.slice(2));let l=xE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Im.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[$r.MAP]:Symbol.iterator in Object(e)?o[$r.SEQ]:o[$r.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 Im.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}jm.createNode=CE});var $s=x(js=>{"use strict";var AE=Da(),ti=J(),_E=Ts();function Gu(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return AE.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var $m=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Uu=class extends _E.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>ti.isNode(r)||ti.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if($m(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(ti.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Gu(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(ti.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&ti.isScalar(a)?a.value:a:ti.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!ti.isPair(i))return!1;let r=i.value;return r==null||t&&ti.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return ti.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(ti.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Gu(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};js.Collection=Uu;js.collectionFromPath=Gu;js.isEmptyPath=$m});var Ma=x(Os=>{"use strict";var TE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ku(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var IE=(e,t,i)=>e.endsWith(`
6
+ `)?Ku(i,t):i.includes(`
7
7
  `)?`
8
- `+dl(i,t):(e.endsWith(" ")?"":" ")+i;Eo.indentComment=dl;Eo.lineComment=Ib;Eo.stringifyComment=Tb});var Ch=C($r=>{"use strict";var _b="flow",fl="block",Ro="quoted";function jb(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,v=-1,b=-1;i===fl&&(h=Rh(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(i===Ro&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(k===`
9
- `)i===fl&&(h=Rh(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
8
+ `+Ku(i,t):(e.endsWith(" ")?"":" ")+i;Os.indentComment=Ku;Os.lineComment=IE;Os.stringifyComment=TE});var Hm=x(Fa=>{"use strict";var jE="flow",Yu="block",Hs="quoted";function $E(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,N=-1;i===Yu&&(h=Om(e,h,t.length),h!==-1&&(d=h+c));for(let E;E=e[h+=1];){if(i===Hs&&E==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}N=h}if(E===`
9
+ `)i===Yu&&(h=Om(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(E===" "&&p&&p!==" "&&p!==`
10
10
  `&&p!==" "){let S=e[h+1];S&&S!==" "&&S!==`
11
- `&&S!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Ro){for(;p===" "||p===" ";)p=k,k=e[h+=1],m=!0;let S=h>b+1?h-2:v-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+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 S=l[k],R=l[k+1]||e.length;S===0?N=`
12
- ${t}${e.slice(0,R)}`:(i===Ro&&u[S]&&(N+=`${e[S]}\\`),N+=`
13
- ${t}${e.slice(S+1,R)}`)}return N}function Rh(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}$r.FOLD_BLOCK=fl;$r.FOLD_FLOW=_b;$r.FOLD_QUOTED=Ro;$r.foldFlowLines=jb});var Dr=C(Ph=>{"use strict";var pt=de(),di=Ch(),Po=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ao=e=>/^(%|---|\.\.\.)/m.test(e);function Ob(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 Hr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Ao(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)+`
11
+ `&&S!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Hs){for(;p===" "||p===" ";)p=E,E=e[h+=1],v=!0;let S=h>N+1?h-2:m-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+c,f=void 0}else v=!0}p=E}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let E=0;E<l.length;++E){let S=l[E],k=l[E+1]||e.length;S===0?y=`
12
+ ${t}${e.slice(0,k)}`:(i===Hs&&u[S]&&(y+=`${e[S]}\\`),y+=`
13
+ ${t}${e.slice(S+1,k)}`)}return y}function Om(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);r=t,n=t+1,a=e[n]}return r}Fa.FOLD_BLOCK=Yu;Fa.FOLD_FLOW=jE;Fa.FOLD_QUOTED=Hs;Fa.foldFlowLines=$E});var Ba=x(Dm=>{"use strict";var Mt=ye(),Li=Hm(),Ms=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Fs=e=>/^(%|---|\.\.\.)/m.test(e);function OE(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function La(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Fs(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
16
16
 
17
17
  `;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,n?o:di.foldFlowLines(o,a,di.FOLD_QUOTED,Po(t,!1))}function hl(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Hr(e,t);let i=t.indent||(Ao(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?n:di.foldFlowLines(n,i,di.FOLD_FLOW,Po(t,!1))}function xn(e,t){let{singleQuote:i}=t.options,n;if(i===!1)n=Hr;else{let r=e.includes('"'),a=e.includes("'");r&&!a?n=hl:a&&!r?n=Hr:n=i?hl:Hr}return n(e,t)}var pl;try{pl=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:Li.foldFlowLines(o,a,Li.FOLD_QUOTED,Ms(t,!1))}function Xu(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return La(e,t);let i=t.indent||(Fs(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?r:Li.foldFlowLines(r,i,Li.FOLD_FLOW,Ms(t,!1))}function gn(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=La;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Xu:a&&!n?r=La:r=i?Xu:La}return r(e,t)}var Qu;try{Qu=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{pl=/\n+(?!\n|$)/g}function Co({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 xn(i,n);let l=n.indent||(n.forceBlockIndent||Ao(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===pt.Scalar.BLOCK_FOLDED?!1:t===pt.Scalar.BLOCK_LITERAL?!0:!Ob(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{Qu=/\n+(?!\n|$)/g}function Ds({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return gn(i,r);let l=r.indent||(r.forceBlockIndent||Fs(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Mt.Scalar.BLOCK_FOLDED?!1:t===Mt.Scalar.BLOCK_LITERAL?!0:!OE(i,c,l.length);if(!i)return u?`|
24
24
  `:`>
25
- `;let d,f;for(f=i.length;f>0;--f){let R=i[f-1];if(R!==`
26
- `&&R!==" "&&R!==" ")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(pl,`$&${l}`));let h=!1,v,b=-1;for(v=0;v<i.length;++v){let R=i[v];if(R===" ")h=!0;else if(R===`
29
- `)b=v;else break}let N=i.substring(0,b<v?b+1:v);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let S=(h?l?"2":"1":"")+d;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let R=i.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),y=!1,w=Po(n,!0);o!=="folded"&&t!==pt.Scalar.BLOCK_FOLDED&&(w.onOverflow=()=>{y=!0});let g=di.foldFlowLines(`${N}${R}${p}`,l,di.FOLD_BLOCK,w);if(!y)return`>${S}
31
- ${l}${g}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S}
32
- ${l}${N}${i}${p}`}function $b(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 xn(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?xn(a,t):Co(e,t,i,n);if(!s&&!u&&r!==pt.Scalar.PLAIN&&a.includes(`
35
- `))return Co(e,t,i,n);if(Ao(a)){if(c==="")return t.forceBlockIndent=!0,Co(e,t,i,n);if(s&&c===l)return xn(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 xn(a,t)}return s?d:di.foldFlowLines(d,c,di.FOLD_FLOW,Po(t,!1))}function Hb(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!==pt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=pt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case pt.Scalar.BLOCK_FOLDED:case pt.Scalar.BLOCK_LITERAL:return r||a?xn(o.value,t):Co(o,t,i,n);case pt.Scalar.QUOTE_DOUBLE:return Hr(o.value,t);case pt.Scalar.QUOTE_SINGLE:return hl(o.value,t);case pt.Scalar.PLAIN:return $b(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}Ph.stringifyString=Hb});var Fr=C(ml=>{"use strict";var Db=yo(),fi=V(),Fb=Or(),Mb=Dr();function Lb(e,t){let i=Object.assign({blockQuote:!0,commentString:Fb.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 Bb(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(fi.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 qb(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(fi.isScalar(e)||fi.isCollection(e))&&e.anchor;a&&Db.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 Vb(e,t,i,n){if(fi.isPair(e))return e.toString(t,i,n);if(fi.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=fi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=Bb(t.doc.schema.tags,a));let o=qb(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):fi.isScalar(a)?Mb.stringifyString(a,t,i,n):a.toString(t,i,n);return o?fi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}ml.createStringifyContext=Lb;ml.stringify=Vb});var Ih=C(Th=>{"use strict";var Jt=V(),Ah=de(),xh=Fr(),Mr=Or();function Wb({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=Jt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Jt.isCollection(e)||!Jt.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||Jt.isCollection(e)||(Jt.isScalar(e)?e.type===Ah.Scalar.BLOCK_FOLDED||e.type===Ah.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,v=xh.stringify(e,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return m&&n&&n(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,f&&!m?v+=Mr.lineComment(v,i.indent,l(f)):h&&r&&r(),v;m&&(f=null),p?(f&&(v+=Mr.lineComment(v,i.indent,l(f))),v=`? ${v}
38
- ${s}:`):(v=`${v}:`,f&&(v+=Mr.lineComment(v,i.indent,l(f))));let b,N,k;Jt.isNode(t)?(b=!!t.spaceBefore,N=t.commentBefore,k=t.comment):(b=!1,N=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&Jt.isScalar(t)&&(i.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&Jt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,R=xh.stringify(t,i,()=>S=!0,()=>h=!0),y=" ";if(f||b||N){if(y=b?`
39
- `:"",N){let w=l(N);y+=`
40
- ${Mr.indentComment(w,i.indent)}`}R===""&&!i.inFlow?y===`
41
- `&&k&&(y=`
42
-
43
- `):y+=`
44
- ${i.indent}`}else if(!p&&Jt.isCollection(t)){let w=R[0],g=R.indexOf(`
45
- `),E=g!==-1,j=i.inFlow??t.flow??t.items.length===0;if(E||!j){let Q=!1;if(E&&(w==="&"||w==="!")){let J=R.indexOf(" ");w==="&"&&J!==-1&&J<g&&R[J+1]==="!"&&(J=R.indexOf(" ",J+1)),(J===-1||g<J)&&(Q=!0)}Q||(y=`
46
- ${i.indent}`)}}else(R===""||R[0]===`
47
- `)&&(y="");return v+=y+R,i.inFlow?S&&n&&n():k&&!S?v+=Mr.lineComment(v,i.indent,l(k)):h&&r&&r(),v}Th.stringifyPair=Wb});var gl=C(vl=>{"use strict";var _h=ho("process");function Jb(e,...t){e==="debug"&&console.log(...t)}function zb(e,t){(e==="debug"||e==="warn")&&(typeof _h.emitWarning=="function"?_h.emitWarning(t):console.warn(t))}vl.debug=Jb;vl.warn=zb});var jo=C(_o=>{"use strict";var Io=V(),jh=de(),xo="<<",To={identify:e=>e===xo||typeof e=="symbol"&&e.description===xo,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new jh.Scalar(Symbol(xo)),{addToJSMap:Oh}),stringify:()=>xo},Gb=(e,t)=>(To.identify(t)||Io.isScalar(t)&&(!t.type||t.type===jh.Scalar.PLAIN)&&To.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===To.tag&&i.default);function Oh(e,t,i){let n=$h(e,i);if(Io.isSeq(n))for(let r of n.items)wl(e,t,r);else if(Array.isArray(n))for(let r of n)wl(e,t,r);else wl(e,t,n)}function wl(e,t,i){let n=$h(e,i);if(!Io.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 $h(e,t){return e&&Io.isAlias(t)?t.resolve(e.doc,e):t}_o.addMergeToJSMap=Oh;_o.isMergeKey=Gb;_o.merge=To});var Nl=C(Fh=>{"use strict";var Ub=gl(),Hh=jo(),Kb=Fr(),Dh=V(),yl=li();function Yb(e,t,{key:i,value:n}){if(Dh.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(Hh.isMergeKey(e,i))Hh.addMergeToJSMap(e,t,n);else{let r=yl.toJS(i,"",e);if(t instanceof Map)t.set(r,yl.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=Xb(i,r,e),o=yl.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 Xb(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Dh.isNode(e)&&i?.doc){let n=Kb.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)+'..."'),Ub.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)}Fh.addPairToJSMap=Yb});var hi=C(bl=>{"use strict";var Mh=jr(),Qb=Ih(),Zb=Nl(),Oo=V();function ek(e,t,i){let n=Mh.createNode(e,void 0,i),r=Mh.createNode(t,void 0,i);return new $o(n,r)}var $o=class e{constructor(t,i=null){Object.defineProperty(this,Oo.NODE_TYPE,{value:Oo.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return Oo.isNode(i)&&(i=i.clone(t)),Oo.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return Zb.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?Qb.stringifyPair(this,t,i,n):JSON.stringify(this)}};bl.Pair=$o;bl.createPair=ek});var kl=C(Bh=>{"use strict";var Xi=V(),Lh=Fr(),Ho=Or();function tk(e,t,i){return(t.inFlow??e.flow?nk:ik)(e,t,i)}function ik({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],v=null;if(Xi.isNode(h))!d&&h.spaceBefore&&f.push(""),Do(i,f,h.commentBefore,d),h.comment&&(v=h.comment);else if(Xi.isPair(h)){let N=Xi.isNode(h.key)?h.key:null;N&&(!d&&N.spaceBefore&&f.push(""),Do(i,f,N.commentBefore,d))}d=!1;let b=Lh.stringify(h,u,()=>v=null,()=>d=!0);v&&(b+=Ho.lineComment(b,a,l(v))),d&&v&&(d=!1),f.push(n+b)}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?`
25
+ `;let d,f;for(f=i.length;f>0;--f){let k=i[f-1];if(k!==`
26
+ `&&k!==" "&&k!==" ")break}let p=i.substring(f),v=p.indexOf(`
27
+ `);v===-1?d="-":i===p||v!==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(Qu,`$&${l}`));let h=!1,m,N=-1;for(m=0;m<i.length;++m){let k=i[m];if(k===" ")h=!0;else if(k===`
29
+ `)N=m;else break}let y=i.substring(0,N<m?N+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let S=(h?l?"2":"1":"")+d;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=i.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,R=Ms(r,!0);o!=="folded"&&t!==Mt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{b=!0});let w=Li.foldFlowLines(`${y}${k}${p}`,l,Li.FOLD_BLOCK,R);if(!b)return`>${S}
31
+ ${l}${w}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S}
32
+ ${l}${y}${i}${p}`}function HE(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return gn(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?gn(a,t):Ds(e,t,i,r);if(!s&&!u&&n!==Mt.Scalar.PLAIN&&a.includes(`
35
+ `))return Ds(e,t,i,r);if(Fs(a)){if(c==="")return t.forceBlockIndent=!0,Ds(e,t,i,r);if(s&&c===l)return gn(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:v}=t.doc.schema;if(v.some(f)||p?.some(f))return gn(a,t)}return s?d:Li.foldFlowLines(d,c,Li.FOLD_FLOW,Ms(t,!1))}function DE(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Mt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Mt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Mt.Scalar.BLOCK_FOLDED:case Mt.Scalar.BLOCK_LITERAL:return n||a?gn(o.value,t):Ds(o,t,i,r);case Mt.Scalar.QUOTE_DOUBLE:return La(o.value,t);case Mt.Scalar.QUOTE_SINGLE:return Xu(o.value,t);case Mt.Scalar.PLAIN:return HE(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Dm.stringifyString=DE});var qa=x(Zu=>{"use strict";var ME=_s(),Bi=J(),FE=Ma(),LE=Ba();function BE(e,t){let i=Object.assign({blockQuote:!0,commentString:FE.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function qE(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Bi.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function VE(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Bi.isScalar(e)||Bi.isCollection(e))&&e.anchor;a&&ME.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function WE(e,t,i,r){if(Bi.isPair(e))return e.toString(t,i,r);if(Bi.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Bi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=qE(t.doc.schema.tags,a));let o=VE(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Bi.isScalar(a)?LE.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Bi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Zu.createStringifyContext=BE;Zu.stringify=WE});var Bm=x(Lm=>{"use strict";var bi=J(),Mm=ye(),Fm=qa(),Va=Ma();function zE({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=bi.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(bi.isCollection(e)||!bi.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||bi.isCollection(e)||(bi.isScalar(e)?e.type===Mm.Scalar.BLOCK_FOLDED||e.type===Mm.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Fm.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.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 v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Va.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Va.lineComment(m,i.indent,l(f))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,f&&(m+=Va.lineComment(m,i.indent,l(f))));let N,y,E;bi.isNode(t)?(N=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(N=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&bi.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&bi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Fm.stringify(t,i,()=>S=!0,()=>h=!0),b=" ";if(f||N||y){if(b=N?`
39
+ `:"",y){let R=l(y);b+=`
40
+ ${Va.indentComment(R,i.indent)}`}k===""&&!i.inFlow?b===`
41
+ `&&E&&(b=`
42
+
43
+ `):b+=`
44
+ ${i.indent}`}else if(!p&&bi.isCollection(t)){let R=k[0],w=k.indexOf(`
45
+ `),g=w!==-1,P=i.inFlow??t.flow??t.items.length===0;if(g||!P){let D=!1;if(g&&(R==="&"||R==="!")){let O=k.indexOf(" ");R==="&"&&O!==-1&&O<w&&k[O+1]==="!"&&(O=k.indexOf(" ",O+1)),(O===-1||w<O)&&(D=!0)}D||(b=`
46
+ ${i.indent}`)}}else(k===""||k[0]===`
47
+ `)&&(b="");return m+=b+k,i.inFlow?S&&r&&r():E&&!S?m+=Va.lineComment(m,i.indent,l(E)):h&&n&&n(),m}Lm.stringifyPair=zE});var td=x(ed=>{"use strict";var qm=Ps("process");function JE(e,...t){e==="debug"&&console.log(...t)}function GE(e,t){(e==="debug"||e==="warn")&&(typeof qm.emitWarning=="function"?qm.emitWarning(t):console.warn(t))}ed.debug=JE;ed.warn=GE});var Ws=x(Vs=>{"use strict";var qs=J(),Vm=ye(),Ls="<<",Bs={identify:e=>e===Ls||typeof e=="symbol"&&e.description===Ls,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Vm.Scalar(Symbol(Ls)),{addToJSMap:Wm}),stringify:()=>Ls},UE=(e,t)=>(Bs.identify(t)||qs.isScalar(t)&&(!t.type||t.type===Vm.Scalar.PLAIN)&&Bs.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Bs.tag&&i.default);function Wm(e,t,i){let r=zm(e,i);if(qs.isSeq(r))for(let n of r.items)id(e,t,n);else if(Array.isArray(r))for(let n of r)id(e,t,n);else id(e,t,r)}function id(e,t,i){let r=zm(e,i);if(!qs.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function zm(e,t){return e&&qs.isAlias(t)?t.resolve(e.doc,e):t}Vs.addMergeToJSMap=Wm;Vs.isMergeKey=UE;Vs.merge=Bs});var nd=x(Um=>{"use strict";var KE=td(),Jm=Ws(),YE=qa(),Gm=J(),rd=Mi();function XE(e,t,{key:i,value:r}){if(Gm.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Jm.isMergeKey(e,i))Jm.addMergeToJSMap(e,t,r);else{let n=rd.toJS(i,"",e);if(t instanceof Map)t.set(n,rd.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=QE(i,n,e),o=rd.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function QE(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Gm.isNode(e)&&i?.doc){let r=YE.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),KE.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Um.addPairToJSMap=XE});var qi=x(ad=>{"use strict";var Km=Da(),ZE=Bm(),eP=nd(),zs=J();function tP(e,t,i){let r=Km.createNode(e,void 0,i),n=Km.createNode(t,void 0,i);return new Js(r,n)}var Js=class e{constructor(t,i=null){Object.defineProperty(this,zs.NODE_TYPE,{value:zs.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return zs.isNode(i)&&(i=i.clone(t)),zs.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return eP.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?ZE.stringifyPair(this,t,i,r):JSON.stringify(this)}};ad.Pair=Js;ad.createPair=tP});var od=x(Xm=>{"use strict";var Or=J(),Ym=qa(),Gs=Ma();function iP(e,t,i){return(t.inFlow??e.flow?nP:rP)(e,t,i)}function rP({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(Or.isNode(h))!d&&h.spaceBefore&&f.push(""),Us(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(Or.isPair(h)){let y=Or.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Us(i,f,y.commentBefore,d))}d=!1;let N=Ym.stringify(h,u,()=>m=null,()=>d=!0);m&&(N+=Gs.lineComment(N,a,l(m))),d&&m&&(d=!1),f.push(r+N)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
48
48
  ${c}${h}`:`
49
49
  `}}return e?(p+=`
50
- `+Ho.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function nk({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],v=null;if(Xi.isNode(h))h.spaceBefore&&d.push(""),Do(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(Xi.isPair(h)){let N=Xi.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&d.push(""),Do(t,d,N.commentBefore,!1),N.comment&&(l=!0));let k=Xi.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(v=N.comment)}v&&(l=!0);let b=Lh.stringify(h,c,()=>v=null);l||(l=d.length>u||b.includes(`
51
- `)),m<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((N,k)=>N+k.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),v&&(b+=Ho.lineComment(b,n,s(v))),d.push(b),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?`
52
- ${a}${r}${h}`:`
53
- `;return`${m}
54
- ${r}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Do({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=Ho.indentComment(t(n),e);i.push(a.trimStart())}}Bh.stringifyCollection=tk});var mi=C(El=>{"use strict";var rk=kl(),ak=Nl(),ok=So(),pi=V(),Fo=hi(),sk=de();function Lr(e,t){let i=pi.isScalar(t)?t.value:t;for(let n of e)if(pi.isPair(n)&&(n.key===t||n.key===i||pi.isScalar(n.key)&&n.key.value===i))return n}var Sl=class extends ok.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(pi.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(Fo.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;pi.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Fo.Pair(t,t?.value):n=new Fo.Pair(t.key,t.value);let r=Lr(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);pi.isScalar(r.value)&&sk.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=Lr(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=Lr(this.items,t)?.value;return(!i&&pi.isScalar(r)?r.value:r)??void 0}has(t){return!!Lr(this.items,t)}set(t,i){this.add(new Fo.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)ak.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!pi.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})),rk.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};El.YAMLMap=Sl;El.findPair=Lr});var Tn=C(Vh=>{"use strict";var ck=V(),qh=mi(),lk={collection:"map",default:!0,nodeClass:qh.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ck.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>qh.YAMLMap.from(e,t,i)};Vh.map=lk});var vi=C(Wh=>{"use strict";var uk=jr(),dk=kl(),fk=So(),Lo=V(),hk=de(),pk=li(),Rl=class extends fk.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Lo.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Mo(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=Mo(t);if(typeof n!="number")return;let r=this.items[n];return!i&&Lo.isScalar(r)?r.value:r}has(t){let i=Mo(t);return typeof i=="number"&&i<this.items.length}set(t,i){let n=Mo(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[n];Lo.isScalar(r)&&hk.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(pk.toJS(a,String(r++),i));return n}toString(t,i,n){return t?dk.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(uk.createNode(s,void 0,n))}}return a}};function Mo(e){let t=Lo.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Wh.YAMLSeq=Rl});var In=C(zh=>{"use strict";var mk=V(),Jh=vi(),vk={collection:"seq",default:!0,nodeClass:Jh.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return mk.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Jh.YAMLSeq.from(e,t,i)};zh.seq=vk});var Br=C(Gh=>{"use strict";var gk=Dr(),wk={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),gk.stringifyString(e,t,i,n)}};Gh.string=wk});var Bo=C(Yh=>{"use strict";var Uh=de(),Kh={identify:e=>e==null,createNode:()=>new Uh.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Uh.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Kh.test.test(e)?e:t.options.nullStr};Yh.nullTag=Kh});var Cl=C(Qh=>{"use strict";var yk=de(),Xh={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new yk.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Xh.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};Qh.boolTag=Xh});var _n=C(Zh=>{"use strict";function Nk({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}Zh.stringifyNumber=Nk});var Al=C(qo=>{"use strict";var bk=de(),Pl=_n(),kk={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:Pl.stringifyNumber},Sk={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():Pl.stringifyNumber(e)}},Ek={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 bk.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Pl.stringifyNumber};qo.float=Ek;qo.floatExp=Sk;qo.floatNaN=kk});var Tl=C(Wo=>{"use strict";var ep=_n(),Vo=e=>typeof e=="bigint"||Number.isInteger(e),xl=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function tp(e,t,i){let{value:n}=e;return Vo(n)&&n>=0?i+n.toString(t):ep.stringifyNumber(e)}var Rk={identify:e=>Vo(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>xl(e,2,8,i),stringify:e=>tp(e,8,"0o")},Ck={identify:Vo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>xl(e,0,10,i),stringify:ep.stringifyNumber},Pk={identify:e=>Vo(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>xl(e,2,16,i),stringify:e=>tp(e,16,"0x")};Wo.int=Ck;Wo.intHex=Pk;Wo.intOct=Rk});var np=C(ip=>{"use strict";var Ak=Tn(),xk=Bo(),Tk=In(),Ik=Br(),_k=Cl(),Il=Al(),_l=Tl(),jk=[Ak.map,Tk.seq,Ik.string,xk.nullTag,_k.boolTag,_l.intOct,_l.int,_l.intHex,Il.floatNaN,Il.floatExp,Il.float];ip.schema=jk});var op=C(ap=>{"use strict";var Ok=de(),$k=Tn(),Hk=In();function rp(e){return typeof e=="bigint"||Number.isInteger(e)}var Jo=({value:e})=>JSON.stringify(e),Dk=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Jo},{identify:e=>e==null,createNode:()=>new Ok.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Jo},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Jo},{identify:rp,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})=>rp(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:Jo}],Fk={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Mk=[$k.map,Hk.seq].concat(Dk,Fk);ap.schema=Mk});var Ol=C(sp=>{"use strict";var qr=ho("buffer"),jl=de(),Lk=Dr(),Bk={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof qr.Buffer=="function")return qr.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 qr.Buffer=="function")s=o instanceof qr.Buffer?o.toString("base64"):qr.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=jl.Scalar.BLOCK_LITERAL),t!==jl.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===jl.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return Lk.stringifyString({comment:e,type:t,value:s},n,r,a)}};sp.binary=Bk});var Uo=C(Go=>{"use strict";var zo=V(),$l=hi(),qk=de(),Vk=vi();function cp(e,t){if(zo.isSeq(e))for(let i=0;i<e.items.length;++i){let n=e.items[i];if(!zo.isPair(n)){if(zo.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new $l.Pair(new qk.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]=zo.isPair(n)?n:new $l.Pair(n)}}else t("Expected a sequence for this tag");return e}function lp(e,t,i){let{replacer:n}=i,r=new Vk.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($l.createPair(s,c,i))}return r}var Wk={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:cp,createNode:lp};Go.createPairs=lp;Go.pairs=Wk;Go.resolvePairs=cp});var Fl=C(Dl=>{"use strict";var up=V(),Hl=li(),Vr=mi(),Jk=vi(),dp=Uo(),Qi=class e extends Jk.YAMLSeq{constructor(){super(),this.add=Vr.YAMLMap.prototype.add.bind(this),this.delete=Vr.YAMLMap.prototype.delete.bind(this),this.get=Vr.YAMLMap.prototype.get.bind(this),this.has=Vr.YAMLMap.prototype.has.bind(this),this.set=Vr.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(up.isPair(r)?(a=Hl.toJS(r.key,"",i),o=Hl.toJS(r.value,a,i)):a=Hl.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=dp.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Qi.tag="tag:yaml.org,2002:omap";var zk={collection:"seq",identify:e=>e instanceof Map,nodeClass:Qi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=dp.resolvePairs(e,t),n=[];for(let{key:r}of i.items)up.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Qi,i)},createNode:(e,t,i)=>Qi.from(e,t,i)};Dl.YAMLOMap=Qi;Dl.omap=zk});var vp=C(Ml=>{"use strict";var fp=de();function hp({value:e,source:t},i){return t&&(e?pp:mp).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var pp={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 fp.Scalar(!0),stringify:hp},mp={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 fp.Scalar(!1),stringify:hp};Ml.falseTag=mp;Ml.trueTag=pp});var gp=C(Ko=>{"use strict";var Gk=de(),Ll=_n(),Uk={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:Ll.stringifyNumber},Kk={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():Ll.stringifyNumber(e)}},Yk={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 Gk.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:Ll.stringifyNumber};Ko.float=Yk;Ko.floatExp=Kk;Ko.floatNaN=Uk});var yp=C(Jr=>{"use strict";var wp=_n(),Wr=e=>typeof e=="bigint"||Number.isInteger(e);function Yo(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 Bl(e,t,i){let{value:n}=e;if(Wr(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return wp.stringifyNumber(e)}var Xk={identify:Wr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Yo(e,2,2,i),stringify:e=>Bl(e,2,"0b")},Qk={identify:Wr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Yo(e,1,8,i),stringify:e=>Bl(e,8,"0")},Zk={identify:Wr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Yo(e,0,10,i),stringify:wp.stringifyNumber},eS={identify:Wr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Yo(e,2,16,i),stringify:e=>Bl(e,16,"0x")};Jr.int=Zk;Jr.intBin=Xk;Jr.intHex=eS;Jr.intOct=Qk});var Vl=C(ql=>{"use strict";var Zo=V(),Xo=hi(),Qo=mi(),Zi=class e extends Qo.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Zo.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Xo.Pair(t.key,null):i=new Xo.Pair(t,null),Qo.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=Qo.findPair(this.items,t);return!i&&Zo.isPair(n)?Zo.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=Qo.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new Xo.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(Xo.createPair(o,null,n));return a}};Zi.tag="tag:yaml.org,2002:set";var tS={collection:"map",identify:e=>e instanceof Set,nodeClass:Zi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Zi.from(e,t,i),resolve(e,t){if(Zo.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Zi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ql.YAMLSet=Zi;ql.set=tS});var Jl=C(es=>{"use strict";var iS=_n();function Wl(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 Np(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return iS.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 nS={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})=>Wl(e,i),stringify:Np},rS={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=>Wl(e,!1),stringify:Np},bp={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(bp.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=Wl(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$/,"")??""};es.floatTime=rS;es.intTime=nS;es.timestamp=bp});var Ep=C(Sp=>{"use strict";var aS=Tn(),oS=Bo(),sS=In(),cS=Br(),lS=Ol(),kp=vp(),zl=gp(),ts=yp(),uS=jo(),dS=Fl(),fS=Uo(),hS=Vl(),Gl=Jl(),pS=[aS.map,sS.seq,cS.string,oS.nullTag,kp.trueTag,kp.falseTag,ts.intBin,ts.intOct,ts.int,ts.intHex,zl.floatNaN,zl.floatExp,zl.float,lS.binary,uS.merge,dS.omap,fS.pairs,hS.set,Gl.intTime,Gl.floatTime,Gl.timestamp];Sp.schema=pS});var Op=C(Yl=>{"use strict";var Ap=Tn(),mS=Bo(),xp=In(),vS=Br(),gS=Cl(),Ul=Al(),Kl=Tl(),wS=np(),yS=op(),Tp=Ol(),zr=jo(),Ip=Fl(),_p=Uo(),Rp=Ep(),jp=Vl(),is=Jl(),Cp=new Map([["core",wS.schema],["failsafe",[Ap.map,xp.seq,vS.string]],["json",yS.schema],["yaml11",Rp.schema],["yaml-1.1",Rp.schema]]),Pp={binary:Tp.binary,bool:gS.boolTag,float:Ul.float,floatExp:Ul.floatExp,floatNaN:Ul.floatNaN,floatTime:is.floatTime,int:Kl.int,intHex:Kl.intHex,intOct:Kl.intOct,intTime:is.intTime,map:Ap.map,merge:zr.merge,null:mS.nullTag,omap:Ip.omap,pairs:_p.pairs,seq:xp.seq,set:jp.set,timestamp:is.timestamp},NS={"tag:yaml.org,2002:binary":Tp.binary,"tag:yaml.org,2002:merge":zr.merge,"tag:yaml.org,2002:omap":Ip.omap,"tag:yaml.org,2002:pairs":_p.pairs,"tag:yaml.org,2002:set":jp.set,"tag:yaml.org,2002:timestamp":is.timestamp};function bS(e,t,i){let n=Cp.get(t);if(n&&!e)return i&&!n.includes(zr.merge)?n.concat(zr.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(Cp.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(zr.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Pp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Pp).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},[])}Yl.coreKnownTags=NS;Yl.getTags=bS});var Zl=C($p=>{"use strict";var Xl=V(),kS=Tn(),SS=In(),ES=Br(),ns=Op(),RS=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Ql=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ns.getTags(t,"compat"):t?ns.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?ns.coreKnownTags:{},this.tags=ns.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Xl.MAP,{value:kS.map}),Object.defineProperty(this,Xl.SCALAR,{value:ES.string}),Object.defineProperty(this,Xl.SEQ,{value:SS.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?RS:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};$p.Schema=Ql});var Dp=C(Hp=>{"use strict";var CS=V(),eu=Fr(),Gr=Or();function PS(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=eu.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Gr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(CS.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Gr.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=eu.stringify(e.contents,r,()=>s=null,c);s&&(l+=Gr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(eu.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(Gr.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(Gr.indentComment(a(c),"")))}return i.join(`
50
+ `+Gs.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function nP({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(Or.isNode(h))h.spaceBefore&&d.push(""),Us(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(Or.isPair(h)){let y=Or.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Us(t,d,y.commentBefore,!1),y.comment&&(l=!0));let E=Or.isNode(h.value)?h.value:null;E?(E.comment&&(m=E.comment),E.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let N=Ym.stringify(h,c,()=>m=null);l||(l=d.length>u||N.includes(`
51
+ `)),v<e.length-1?N+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,E)=>y+E.length+2,2)+(N.length+2)>t.options.lineWidth)),l&&(N+=",")),m&&(N+=Gs.lineComment(N,r,s(m))),d.push(N),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?`
52
+ ${a}${n}${h}`:`
53
+ `;return`${v}
54
+ ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Us({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Gs.indentComment(t(r),e);i.push(a.trimStart())}}Xm.stringifyCollection=iP});var Wi=x(cd=>{"use strict";var aP=od(),oP=nd(),sP=$s(),Vi=J(),Ks=qi(),cP=ye();function Wa(e,t){let i=Vi.isScalar(t)?t.value:t;for(let r of e)if(Vi.isPair(r)&&(r.key===t||r.key===i||Vi.isScalar(r.key)&&r.key.value===i))return r}var sd=class extends sP.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Vi.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ks.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Vi.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Ks.Pair(t,t?.value):r=new Ks.Pair(t.key,t.value);let n=Wa(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Vi.isScalar(n.value)&&cP.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=Wa(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Wa(this.items,t)?.value;return(!i&&Vi.isScalar(n)?n.value:n)??void 0}has(t){return!!Wa(this.items,t)}set(t,i){this.add(new Ks.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)oP.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Vi.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),aP.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};cd.YAMLMap=sd;cd.findPair=Wa});var wn=x(Zm=>{"use strict";var lP=J(),Qm=Wi(),uP={collection:"map",default:!0,nodeClass:Qm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return lP.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Qm.YAMLMap.from(e,t,i)};Zm.map=uP});var zi=x(ev=>{"use strict";var dP=Da(),fP=od(),hP=$s(),Xs=J(),pP=ye(),mP=Mi(),ld=class extends hP.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Xs.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ys(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Ys(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Xs.isScalar(n)?n.value:n}has(t){let i=Ys(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Ys(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Xs.isScalar(n)&&pP.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(mP.toJS(a,String(n++),i));return r}toString(t,i,r){return t?fP.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(dP.createNode(s,void 0,r))}}return a}};function Ys(e){let t=Xs.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}ev.YAMLSeq=ld});var yn=x(iv=>{"use strict";var vP=J(),tv=zi(),gP={collection:"seq",default:!0,nodeClass:tv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return vP.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>tv.YAMLSeq.from(e,t,i)};iv.seq=gP});var za=x(rv=>{"use strict";var wP=Ba(),yP={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),wP.stringifyString(e,t,i,r)}};rv.string=yP});var Qs=x(ov=>{"use strict";var nv=ye(),av={identify:e=>e==null,createNode:()=>new nv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new nv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&av.test.test(e)?e:t.options.nullStr};ov.nullTag=av});var ud=x(cv=>{"use strict";var NP=ye(),sv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new NP.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&sv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};cv.boolTag=sv});var Nn=x(lv=>{"use strict";function bP({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}lv.stringifyNumber=bP});var fd=x(Zs=>{"use strict";var kP=ye(),dd=Nn(),SP={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:dd.stringifyNumber},EP={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():dd.stringifyNumber(e)}},PP={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 kP.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:dd.stringifyNumber};Zs.float=PP;Zs.floatExp=EP;Zs.floatNaN=SP});var pd=x(tc=>{"use strict";var uv=Nn(),ec=e=>typeof e=="bigint"||Number.isInteger(e),hd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function dv(e,t,i){let{value:r}=e;return ec(r)&&r>=0?i+r.toString(t):uv.stringifyNumber(e)}var RP={identify:e=>ec(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>hd(e,2,8,i),stringify:e=>dv(e,8,"0o")},xP={identify:ec,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>hd(e,0,10,i),stringify:uv.stringifyNumber},CP={identify:e=>ec(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>hd(e,2,16,i),stringify:e=>dv(e,16,"0x")};tc.int=xP;tc.intHex=CP;tc.intOct=RP});var hv=x(fv=>{"use strict";var AP=wn(),_P=Qs(),TP=yn(),IP=za(),jP=ud(),md=fd(),vd=pd(),$P=[AP.map,TP.seq,IP.string,_P.nullTag,jP.boolTag,vd.intOct,vd.int,vd.intHex,md.floatNaN,md.floatExp,md.float];fv.schema=$P});var vv=x(mv=>{"use strict";var OP=ye(),HP=wn(),DP=yn();function pv(e){return typeof e=="bigint"||Number.isInteger(e)}var ic=({value:e})=>JSON.stringify(e),MP=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ic},{identify:e=>e==null,createNode:()=>new OP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ic},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ic},{identify:pv,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})=>pv(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:ic}],FP={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},LP=[HP.map,DP.seq].concat(MP,FP);mv.schema=LP});var wd=x(gv=>{"use strict";var Ja=Ps("buffer"),gd=ye(),BP=Ba(),qP={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ja.Buffer=="function")return Ja.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Ja.Buffer=="function")s=o instanceof Ja.Buffer?o.toString("base64"):Ja.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=gd.Scalar.BLOCK_LITERAL),t!==gd.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===gd.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return BP.stringifyString({comment:e,type:t,value:s},r,n,a)}};gv.binary=qP});var ac=x(nc=>{"use strict";var rc=J(),yd=qi(),VP=ye(),WP=zi();function wv(e,t){if(rc.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!rc.isPair(r)){if(rc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new yd.Pair(new VP.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
56
+ ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
57
+ ${a.comment}`:r.comment}r=n}e.items[i]=rc.isPair(r)?r:new yd.Pair(r)}}else t("Expected a sequence for this tag");return e}function yv(e,t,i){let{replacer:r}=i,n=new WP.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(yd.createPair(s,c,i))}return n}var zP={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:wv,createNode:yv};nc.createPairs=yv;nc.pairs=zP;nc.resolvePairs=wv});var kd=x(bd=>{"use strict";var Nv=J(),Nd=Mi(),Ga=Wi(),JP=zi(),bv=ac(),Hr=class e extends JP.YAMLSeq{constructor(){super(),this.add=Ga.YAMLMap.prototype.add.bind(this),this.delete=Ga.YAMLMap.prototype.delete.bind(this),this.get=Ga.YAMLMap.prototype.get.bind(this),this.has=Ga.YAMLMap.prototype.has.bind(this),this.set=Ga.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(Nv.isPair(n)?(a=Nd.toJS(n.key,"",i),o=Nd.toJS(n.value,a,i)):a=Nd.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=bv.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Hr.tag="tag:yaml.org,2002:omap";var GP={collection:"seq",identify:e=>e instanceof Map,nodeClass:Hr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=bv.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Nv.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Hr,i)},createNode:(e,t,i)=>Hr.from(e,t,i)};bd.YAMLOMap=Hr;bd.omap=GP});var Rv=x(Sd=>{"use strict";var kv=ye();function Sv({value:e,source:t},i){return t&&(e?Ev:Pv).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Ev={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 kv.Scalar(!0),stringify:Sv},Pv={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 kv.Scalar(!1),stringify:Sv};Sd.falseTag=Pv;Sd.trueTag=Ev});var xv=x(oc=>{"use strict";var UP=ye(),Ed=Nn(),KP={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:Ed.stringifyNumber},YP={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():Ed.stringifyNumber(e)}},XP={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 UP.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Ed.stringifyNumber};oc.float=XP;oc.floatExp=YP;oc.floatNaN=KP});var Av=x(Ka=>{"use strict";var Cv=Nn(),Ua=e=>typeof e=="bigint"||Number.isInteger(e);function sc(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Pd(e,t,i){let{value:r}=e;if(Ua(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Cv.stringifyNumber(e)}var QP={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>sc(e,2,2,i),stringify:e=>Pd(e,2,"0b")},ZP={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>sc(e,1,8,i),stringify:e=>Pd(e,8,"0")},eR={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>sc(e,0,10,i),stringify:Cv.stringifyNumber},tR={identify:Ua,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>sc(e,2,16,i),stringify:e=>Pd(e,16,"0x")};Ka.int=eR;Ka.intBin=QP;Ka.intHex=tR;Ka.intOct=ZP});var xd=x(Rd=>{"use strict";var uc=J(),cc=qi(),lc=Wi(),Dr=class e extends lc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;uc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new cc.Pair(t.key,null):i=new cc.Pair(t,null),lc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=lc.findPair(this.items,t);return!i&&uc.isPair(r)?uc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=lc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new cc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(cc.createPair(o,null,r));return a}};Dr.tag="tag:yaml.org,2002:set";var iR={collection:"map",identify:e=>e instanceof Set,nodeClass:Dr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Dr.from(e,t,i),resolve(e,t){if(uc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Dr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Rd.YAMLSet=Dr;Rd.set=iR});var Ad=x(dc=>{"use strict";var rR=Nn();function Cd(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function _v(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return rR.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var nR={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})=>Cd(e,i),stringify:_v},aR={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=>Cd(e,!1),stringify:_v},Tv={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(Tv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Cd(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$/,"")??""};dc.floatTime=aR;dc.intTime=nR;dc.timestamp=Tv});var $v=x(jv=>{"use strict";var oR=wn(),sR=Qs(),cR=yn(),lR=za(),uR=wd(),Iv=Rv(),_d=xv(),fc=Av(),dR=Ws(),fR=kd(),hR=ac(),pR=xd(),Td=Ad(),mR=[oR.map,cR.seq,lR.string,sR.nullTag,Iv.trueTag,Iv.falseTag,fc.intBin,fc.intOct,fc.int,fc.intHex,_d.floatNaN,_d.floatExp,_d.float,uR.binary,dR.merge,fR.omap,hR.pairs,pR.set,Td.intTime,Td.floatTime,Td.timestamp];jv.schema=mR});var Wv=x($d=>{"use strict";var Mv=wn(),vR=Qs(),Fv=yn(),gR=za(),wR=ud(),Id=fd(),jd=pd(),yR=hv(),NR=vv(),Lv=wd(),Ya=Ws(),Bv=kd(),qv=ac(),Ov=$v(),Vv=xd(),hc=Ad(),Hv=new Map([["core",yR.schema],["failsafe",[Mv.map,Fv.seq,gR.string]],["json",NR.schema],["yaml11",Ov.schema],["yaml-1.1",Ov.schema]]),Dv={binary:Lv.binary,bool:wR.boolTag,float:Id.float,floatExp:Id.floatExp,floatNaN:Id.floatNaN,floatTime:hc.floatTime,int:jd.int,intHex:jd.intHex,intOct:jd.intOct,intTime:hc.intTime,map:Mv.map,merge:Ya.merge,null:vR.nullTag,omap:Bv.omap,pairs:qv.pairs,seq:Fv.seq,set:Vv.set,timestamp:hc.timestamp},bR={"tag:yaml.org,2002:binary":Lv.binary,"tag:yaml.org,2002:merge":Ya.merge,"tag:yaml.org,2002:omap":Bv.omap,"tag:yaml.org,2002:pairs":qv.pairs,"tag:yaml.org,2002:set":Vv.set,"tag:yaml.org,2002:timestamp":hc.timestamp};function kR(e,t,i){let r=Hv.get(t);if(r&&!e)return i&&!r.includes(Ya.merge)?r.concat(Ya.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Hv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Ya.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Dv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Dv).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},[])}$d.coreKnownTags=bR;$d.getTags=kR});var Dd=x(zv=>{"use strict";var Od=J(),SR=wn(),ER=yn(),PR=za(),pc=Wv(),RR=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Hd=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?pc.getTags(t,"compat"):t?pc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?pc.coreKnownTags:{},this.tags=pc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Od.MAP,{value:SR.map}),Object.defineProperty(this,Od.SCALAR,{value:PR.string}),Object.defineProperty(this,Od.SEQ,{value:ER.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?RR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};zv.Schema=Hd});var Gv=x(Jv=>{"use strict";var xR=J(),Md=qa(),Xa=Ma();function CR(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=Md.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Xa.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(xR.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Xa.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Md.stringify(e.contents,n,()=>s=null,c);s&&(l+=Xa.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Md.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(Xa.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(Xa.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}Hp.stringifyDocument=PS});var Ur=C(Fp=>{"use strict";var AS=_r(),jn=So(),et=V(),xS=hi(),TS=li(),IS=Zl(),_S=Dp(),tu=yo(),jS=al(),OS=jr(),iu=rl(),nu=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,et.NODE_TYPE,{value:et.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 iu.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,{[et.NODE_TYPE]:{value:et.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=et.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){On(this.contents)&&this.contents.add(t)}addIn(t,i){On(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=tu.anchorNames(this);t.anchor=!i||n.has(i)?tu.findNewAnchor(i||"a",n):i}return new AS.Alias(t.anchor)}createNode(t,i,n){let r;if(typeof i=="function")t=i.call({"":t},"",t),r=i;else if(Array.isArray(i)){let v=N=>typeof N=="number"||N instanceof String||N instanceof Number,b=i.filter(v).map(String);b.length>0&&(i=i.concat(b)),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}=tu.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=OS.createNode(t,u,m);return s&&et.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 xS.Pair(r,a)}delete(t){return On(this.contents)?this.contents.delete(t):!1}deleteIn(t){return jn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):On(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return et.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return jn.isEmptyPath(t)?!i&&et.isScalar(this.contents)?this.contents.value:this.contents:et.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return et.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return jn.isEmptyPath(t)?this.contents!==void 0:et.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=jn.collectionFromPath(this.schema,[t],i):On(this.contents)&&this.contents.set(t,i)}setIn(t,i){jn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=jn.collectionFromPath(this.schema,Array.from(t),i):On(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 iu.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 iu.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 IS.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=TS.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"?jS.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 _S.stringifyDocument(this,t)}};function On(e){if(et.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Fp.Document=nu});var Xr=C(Yr=>{"use strict";var Kr=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},ru=class extends Kr{constructor(t,i,n){super("YAMLParseError",t,i,n)}},au=class extends Kr{constructor(t,i,n){super("YAMLWarning",t,i,n)}},$S=(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
+ `}Jv.stringifyDocument=CR});var Qa=x(Uv=>{"use strict";var AR=Ha(),bn=$s(),kt=J(),_R=qi(),TR=Mi(),IR=Dd(),jR=Gv(),Fd=_s(),$R=Vu(),OR=Da(),Ld=qu(),Bd=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,kt.NODE_TYPE,{value:kt.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 Ld.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[kt.NODE_TYPE]:{value:kt.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=kt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){kn(this.contents)&&this.contents.add(t)}addIn(t,i){kn(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Fd.anchorNames(this);t.anchor=!i||r.has(i)?Fd.findNewAnchor(i||"a",r):i}return new AR.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,N=i.filter(m).map(String);N.length>0&&(i=i.concat(N)),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:p}=Fd.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=OR.createNode(t,u,v);return s&&kt.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new _R.Pair(n,a)}delete(t){return kn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return bn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):kn(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return kt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return bn.isEmptyPath(t)?!i&&kt.isScalar(this.contents)?this.contents.value:this.contents:kt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return kt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return bn.isEmptyPath(t)?this.contents!==void 0:kt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=bn.collectionFromPath(this.schema,[t],i):kn(this.contents)&&this.contents.set(t,i)}setIn(t,i){bn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=bn.collectionFromPath(this.schema,Array.from(t),i):kn(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ld.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Ld.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new IR.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=TR.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"?$R.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 jR.stringifyDocument(this,t)}};function kn(e){if(kt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Uv.Document=Bd});var to=x(eo=>{"use strict";var Za=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},qd=class extends Za{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Vd=class extends Za{constructor(t,i,r){super("YAMLWarning",t,i,r)}},HR=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
61
+ `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};Yr.YAMLError=Kr;Yr.YAMLParseError=ru;Yr.YAMLWarning=au;Yr.prettifyError=$S});var Qr=C(Mp=>{"use strict";function HS(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,v=null,b=null,N=null,k=null,S=null,R=null;for(let g of e)switch(m&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),g.type){case"space":!t&&(i!=="doc-start"||n?.type!=="flow-collection")&&g.source.includes(" ")&&(h=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=g.source.substring(1)||" ";d?d+=f+E:d=E,f="",l=!1;break}case"newline":l?d?d+=g.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(v||b)&&(N=g),u=!0;break;case"anchor":v&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=g,R??(R=g.offset),l=!1,u=!1,m=!0;break;case"tag":{b&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),b=g,R??(R=g.offset),l=!1,u=!1,m=!0;break}case i:(v||b)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),S&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),S=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.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:S,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:b,newlineAfterProp:N,end:w,start:R??w}}Mp.resolveProps=HS});var rs=C(Lp=>{"use strict";function ou(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(ou(t.key)||ou(t.value))return!0}return!1;default:return!0}}Lp.containsNewline=ou});var su=C(Bp=>{"use strict";var DS=rs();function FS(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&DS.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Bp.flowIndentCheck=FS});var cu=C(Vp=>{"use strict";var qp=V();function MS(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||qp.isScalar(a)&&qp.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Vp.mapIncludes=MS});var Kp=C(Up=>{"use strict";var Wp=hi(),LS=mi(),Jp=Qr(),BS=rs(),zp=su(),qS=cu(),Gp="All mapping items must start at the same column";function VS({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??LS.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=Jp.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),v=!h.found;if(v){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",Gp)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||BS.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",Gp);i.atKey=!0;let b=h.end,N=f?e(i,f,h,r):t(i,b,d,null,h,r);i.schema.compat&&zp.flowIndentCheck(n.indent,f,r),i.atKey=!1,qS.mapIncludes(i,s.items,N)&&r(b,"DUPLICATE_KEY","Map keys must be unique");let k=Jp.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){v&&(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 S=m?e(i,m,k,r):t(i,c,p,null,k,r);i.schema.compat&&zp.flowIndentCheck(n.indent,m,r),c=S.range[2];let R=new Wp.Pair(N,S);i.options.keepSourceTokens&&(R.srcToken=u),s.items.push(R)}else{v&&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 S=new Wp.Pair(N);i.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}Up.resolveBlockMap=VS});var Xp=C(Yp=>{"use strict";var WS=vi(),JS=Qr(),zS=su();function GS({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??WS.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=JS.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&&zS.flowIndentCheck(n.indent,d,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}Yp.resolveBlockSeq=GS});var $n=C(Qp=>{"use strict";function US(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}}Qp.resolveEnd=US});var im=C(tm=>{"use strict";var KS=V(),YS=hi(),Zp=mi(),XS=vi(),QS=$n(),em=Qr(),ZS=rs(),eE=cu(),lu="Block collections are not allowed within flow collections",uu=e=>e&&(e.type==="block-map"||e.type==="block-seq");function tE({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Zp.YAMLMap:XS.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 v=0;v<n.items.length;++v){let b=n.items[v],{start:N,key:k,sep:S,value:R}=b,y=em.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:k??S?.[0],offset:d,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!y.found){if(!y.anchor&&!y.tag&&!S&&!R){v===0&&y.comma?r(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<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&&ZS.containsNewline(k)&&r(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===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 g of N)switch(g.type){case"comma":case"space":break;case"comment":w=g.source.substring(1);break e;default:break e}if(w){let g=l.items[l.items.length-1];KS.isPair(g)&&(g=g.value??g.key),g.comment?g.comment+=`
70
- `+w:g.comment=w,y.comment=y.comment.substring(w.length+1)}}if(!o&&!S&&!y.found){let w=R?e(i,R,y,r):t(i,y.end,S,null,y,r);l.items.push(w),d=w.range[2],uu(R)&&r(w.range,"BLOCK_IN_FLOW",lu)}else{i.atKey=!0;let w=y.end,g=k?e(i,k,y,r):t(i,w,N,null,y,r);uu(k)&&r(g.range,"BLOCK_IN_FLOW",lu),i.atKey=!1;let E=em.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:R,offset:g.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(E.found){if(!o&&!y.found&&i.options.strict){if(S)for(let J of S){if(J===E.found)break;if(J.type==="newline"){r(J,"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 R&&("source"in R&&R.source?.[0]===":"?r(R,"MISSING_CHAR",`Missing space after : in ${s}`):r(E.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let j=R?e(i,R,E,r):E.found?t(i,E.end,S,null,E,r):null;j?uu(R)&&r(j.range,"BLOCK_IN_FLOW",lu):E.comment&&(g.comment?g.comment+=`
71
- `+E.comment:g.comment=E.comment);let Q=new YS.Pair(g,j);if(i.options.keepSourceTokens&&(Q.srcToken=b),o){let J=l;eE.mapIncludes(i,J.items,g)&&r(w,"DUPLICATE_KEY","Map keys must be unique"),J.items.push(Q)}else{let J=new Zp.YAMLMap(i.schema);J.flow=!0,J.items.push(Q);let K=(j??g).range;J.range=[g.range[0],K[1],K[2]],l.items.push(J)}d=j?j.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 v=s[0].toUpperCase()+s.substring(1),b=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;r(d,u?"MISSING_CHAR":"BAD_INDENT",b),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=QS.resolveEnd(m,h,i.options.strict,r);v.comment&&(l.comment?l.comment+=`
72
- `+v.comment:l.comment=v.comment),l.range=[n.offset,h,v.offset]}else l.range=[n.offset,h,h];return l}tm.resolveFlowCollection=tE});var rm=C(nm=>{"use strict";var iE=V(),nE=de(),rE=mi(),aE=vi(),oE=Kp(),sE=Xp(),cE=im();function du(e,t,i,n,r,a){let o=i.type==="block-map"?oE.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?sE.resolveBlockSeq(e,t,i,n,a):cE.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 lE(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===rE.YAMLMap.tagName&&s==="map"||o===aE.YAMLSeq.tagName&&s==="seq")return du(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),du(e,t,i,r,o)}let l=du(e,t,i,r,o,c),u=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=iE.isNode(u)?u:new nE.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}nm.composeCollection=lE});var hu=C(am=>{"use strict";var fu=de();function uE(e,t,i){let n=t.offset,r=dE(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?fu.Scalar.BLOCK_FOLDED:fu.Scalar.BLOCK_LITERAL,o=t.source?fE(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=r.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",v=n+r.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:r.comment,range:[n,v,v]}}let c=t.indent+r.indent,l=t.offset+r.length,u=0;for(let h=0;h<s;++h){let[v,b]=o[h];if(b===""||b==="\r")r.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&i(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+b.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[v,b]=o[h];l+=v.length+b.length+1;let N=b[b.length-1]==="\r";if(N&&(b=b.slice(0,-1)),b&&v.length<c){let S=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(N?2:1),"BAD_INDENT",S),v=""}a===fu.Scalar.BLOCK_LITERAL?(d+=f+v.slice(c)+b,f=`
75
- `):v.length>c||b[0]===" "?(f===" "?f=`
65
+ `}};eo.YAMLError=Za;eo.YAMLParseError=qd;eo.YAMLWarning=Vd;eo.prettifyError=HR});var io=x(Kv=>{"use strict";function DR(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,N=null,y=null,E=null,S=null,k=null;for(let w of e)switch(v&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&a(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(h=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:(!S||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,p=!0,(m||N)&&(y=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,k??(k=w.offset),l=!1,u=!1,v=!0;break;case"tag":{N&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),N=w,k??(k=w.offset),l=!1,u=!1,v=!0;break}case i:(m||N)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),S&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),S=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){E&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let b=e[e.length-1],R=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:N,newlineAfterProp:y,end:R,start:k??R}}Kv.resolveProps=DR});var mc=x(Yv=>{"use strict";function Wd(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(Wd(t.key)||Wd(t.value))return!0}return!1;default:return!0}}Yv.containsNewline=Wd});var zd=x(Xv=>{"use strict";var MR=mc();function FR(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&MR.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Xv.flowIndentCheck=FR});var Jd=x(Zv=>{"use strict";var Qv=J();function LR(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Qv.isScalar(a)&&Qv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Zv.mapIncludes=LR});var ag=x(ng=>{"use strict";var eg=qi(),BR=Wi(),tg=io(),qR=mc(),ig=zd(),VR=Jd(),rg="All mapping items must start at the same column";function WR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??BR.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:p,value:v}=u,h=tg.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.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",rg)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||qR.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",rg);i.atKey=!0;let N=h.end,y=f?e(i,f,h,n):t(i,N,d,null,h,n);i.schema.compat&&ig.flowIndentCheck(r.indent,f,n),i.atKey=!1,VR.mapIncludes(i,s.items,y)&&n(N,"DUPLICATE_KEY","Map keys must be unique");let E=tg.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=E.end,E.found){m&&(v?.type==="block-map"&&!E.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<E.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?e(i,v,E,n):t(i,c,p,null,E,n);i.schema.compat&&ig.flowIndentCheck(r.indent,v,n),c=S.range[2];let k=new eg.Pair(y,S);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),E.comment&&(y.comment?y.comment+=`
68
+ `+E.comment:y.comment=E.comment);let S=new eg.Pair(y);i.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}ng.resolveBlockMap=WR});var sg=x(og=>{"use strict";var zR=zi(),JR=io(),GR=zd();function UR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??zR.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=JR.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 p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&GR.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}og.resolveBlockSeq=UR});var Sn=x(cg=>{"use strict";function KR(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}cg.resolveEnd=KR});var fg=x(dg=>{"use strict";var YR=J(),XR=qi(),lg=Wi(),QR=zi(),ZR=Sn(),ug=io(),ex=mc(),tx=Jd(),Gd="Block collections are not allowed within flow collections",Ud=e=>e&&(e.type==="block-map"||e.type==="block-seq");function ix({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?lg.YAMLMap:QR.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 N=r.items[m],{start:y,key:E,sep:S,value:k}=N,b=ug.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:E??S?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!S&&!k){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
69
+ `+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&ex.containsNewline(E)&&n(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let R="";e:for(let w of y)switch(w.type){case"comma":case"space":break;case"comment":R=w.source.substring(1);break e;default:break e}if(R){let w=l.items[l.items.length-1];YR.isPair(w)&&(w=w.value??w.key),w.comment?w.comment+=`
70
+ `+R:w.comment=R,b.comment=b.comment.substring(R.length+1)}}if(!o&&!S&&!b.found){let R=k?e(i,k,b,n):t(i,b.end,S,null,b,n);l.items.push(R),d=R.range[2],Ud(k)&&n(R.range,"BLOCK_IN_FLOW",Gd)}else{i.atKey=!0;let R=b.end,w=E?e(i,E,b,n):t(i,R,y,null,b,n);Ud(E)&&n(w.range,"BLOCK_IN_FLOW",Gd),i.atKey=!1;let g=ug.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:k,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(g.found){if(!o&&!b.found&&i.options.strict){if(S)for(let O of S){if(O===g.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.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 k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(g.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,g,n):g.found?t(i,g.end,S,null,g,n):null;P?Ud(k)&&n(P.range,"BLOCK_IN_FLOW",Gd):g.comment&&(w.comment?w.comment+=`
71
+ `+g.comment:w.comment=g.comment);let D=new XR.Pair(w,P);if(i.options.keepSourceTokens&&(D.srcToken=N),o){let O=l;tx.mapIncludes(i,O.items,w)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(D)}else{let O=new lg.YAMLMap(i.schema);O.flow=!0,O.items.push(D);let De=(P??w).range;O.range=[w.range[0],De[1],De[2]],l.items.push(O)}d=P?P.range[2]:g.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),N=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",N),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=ZR.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
+ `+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}dg.resolveFlowCollection=ix});var pg=x(hg=>{"use strict";var rx=J(),nx=ye(),ax=Wi(),ox=zi(),sx=ag(),cx=sg(),lx=fg();function Kd(e,t,i,r,n,a){let o=i.type==="block-map"?sx.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?cx.resolveBlockSeq(e,t,i,r,a):lx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function ux(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===ax.YAMLMap.tagName&&s==="map"||o===ox.YAMLSeq.tagName&&s==="seq")return Kd(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Kd(e,t,i,n,o)}let l=Kd(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=rx.isNode(u)?u:new nx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}hg.composeCollection=ux});var Xd=x(mg=>{"use strict";var Yd=ye();function dx(e,t,i){let r=t.offset,n=fx(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Yd.Scalar.BLOCK_FOLDED:Yd.Scalar.BLOCK_LITERAL,o=t.source?hx(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,N]=o[h];if(N===""||N==="\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=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+N.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[m,N]=o[h];l+=m.length+N.length+1;let y=N[N.length-1]==="\r";if(y&&(N=N.slice(0,-1)),N&&m.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-N.length-(y?2:1),"BAD_INDENT",S),m=""}a===Yd.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+N,f=`
75
+ `):m.length>c||N[0]===" "?(f===" "?f=`
76
76
  `:!p&&f===`
77
77
  `&&(f=`
78
78
 
79
- `),d+=f+v.slice(c)+b,f=`
80
- `,p=!0):b===""?f===`
79
+ `),d+=f+m.slice(c)+N,f=`
80
+ `,p=!0):N===""?f===`
81
81
  `?d+=`
82
82
  `:f=`
83
- `:(d+=f+b,f=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
83
+ `:(d+=f+N,f=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
84
84
  `+o[h][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 dE({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 fE(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}am.resolveBlockScalar=uE});var mu=C(sm=>{"use strict";var pu=de(),hE=$n();function pE(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=pu.Scalar.PLAIN,c=mE(a,l);break;case"single-quoted-scalar":s=pu.Scalar.QUOTE_SINGLE,c=vE(a,l);break;case"double-quoted-scalar":s=pu.Scalar.QUOTE_DOUBLE,c=gE(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=hE.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function mE(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}`),om(e)}function vE(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),om(e.slice(1,-1)).replace(/''/g,"'")}function om(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function fx({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(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":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function hx(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}mg.resolveBlockScalar=dx});var Zd=x(gg=>{"use strict";var Qd=ye(),px=Sn();function mx(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=Qd.Scalar.PLAIN,c=vx(a,l);break;case"single-quoted-scalar":s=Qd.Scalar.QUOTE_SINGLE,c=gx(a,l);break;case"double-quoted-scalar":s=Qd.Scalar.QUOTE_DOUBLE,c=wx(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=px.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function vx(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}`),vg(e)}function gx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),vg(e.slice(1,-1)).replace(/''/g,"'")}function vg(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
- `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let r=n[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;n=i.exec(e);)n[1]===""?a===`
90
- `?r+=a:a=`
91
- `:(r+=a+n[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(e),r+a+(n?.[1]??"")}function gE(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}=wE(e,n);i+=a,n=o}else if(r==="\\"){let a=e[++n],o=yE[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+=NE(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 wE(e,t){let i="",n=e[t+1];for(;(n===" "||n===" "||n===`
98
- `||n==="\r")&&!(n==="\r"&&e[t+2]!==`
99
- `);)n===`
89
+ `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
90
+ `?n+=a:a=`
91
+ `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function wx(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
92
+ `))if(n===`
93
+ `){let{fold:a,offset:o}=yx(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Nx[a];if(o)i+=o;else if(a===`
94
+ `)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
95
+ `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=bx(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
96
+ `&&!(o==="\r"&&e[r+2]===`
97
+ `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function yx(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
98
+ `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
99
+ `);)r===`
100
100
  `&&(i+=`
101
- `),t+=1,n=e[t+1];return i||(i=" "),{fold:i,offset:t}}var yE={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function NE(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}}sm.resolveFlowScalar=pE});var um=C(lm=>{"use strict";var en=V(),cm=de(),bE=hu(),kE=mu();function SE(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?bE.resolveBlockScalar(e,t,n):kE.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[en.SCALAR]:c?l=EE(e.schema,r,c,i,n):t.type==="scalar"?l=RE(e,r,t,n):l=e.schema[en.SCALAR];let u;try{let d=l.resolve(r,f=>n(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=en.isScalar(d)?d:new cm.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(i??t,"TAG_RESOLVE_FAILED",f),u=new cm.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 EE(e,t,i,n,r){if(i==="!")return e[en.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[en.SCALAR])}function RE({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[en.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[en.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}lm.composeScalar=SE});var fm=C(dm=>{"use strict";function CE(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}dm.emptyScalarPosition=CE});var mm=C(gu=>{"use strict";var PE=_r(),AE=V(),xE=rm(),hm=um(),TE=$n(),IE=fm(),_E={composeNode:pm,composeEmptyNode:vu};function pm(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=jE(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=hm.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=xE.composeCollection(_E,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=vu(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&&(!AE.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 vu(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:IE.emptyScalarPosition(t,i,n),indent:-1,source:""},d=hm.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 jE({options:e},{offset:t,source:i,end:n},r){let a=new PE.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=TE.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}gu.composeEmptyNode=vu;gu.composeNode=pm});var wm=C(gm=>{"use strict";var OE=Ur(),vm=mm(),$E=$n(),HE=Qr();function DE(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new OE.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=HE.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?vm.composeNode(l,r,u,o):vm.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=$E.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}gm.composeDoc=DE});var yu=C(bm=>{"use strict";var FE=ho("process"),ME=rl(),LE=Ur(),Zr=Xr(),ym=V(),BE=wm(),qE=$n();function ea(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 Nm(e){let t="",i=!1,n=!1;for(let r=0;r<e.length;++r){let a=e[r];switch(a[0]){case"#":t+=(t===""?"":n?`
101
+ `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Nx={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function bx(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}gg.resolveFlowScalar=mx});var Ng=x(yg=>{"use strict";var Mr=J(),wg=ye(),kx=Xd(),Sx=Zd();function Ex(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?kx.resolveBlockScalar(e,t,r):Sx.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Mr.SCALAR]:c?l=Px(e.schema,n,c,i,r):t.type==="scalar"?l=Rx(e,n,t,r):l=e.schema[Mr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Mr.isScalar(d)?d:new wg.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new wg.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 Px(e,t,i,r,n){if(i==="!")return e[Mr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Mr.SCALAR])}function Rx({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[Mr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Mr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}yg.composeScalar=Ex});var kg=x(bg=>{"use strict";function xx(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}bg.emptyScalarPosition=xx});var Pg=x(tf=>{"use strict";var Cx=Ha(),Ax=J(),_x=pg(),Sg=Ng(),Tx=Sn(),Ix=kg(),jx={composeNode:Eg,composeEmptyNode:ef};function Eg(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=$x(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Sg.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=_x.composeCollection(jx,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=ef(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Ax.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function ef(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Ix.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Sg.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function $x({options:e},{offset:t,source:i,end:r},n){let a=new Cx.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Tx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}tf.composeEmptyNode=ef;tf.composeNode=Eg});var Cg=x(xg=>{"use strict";var Ox=Qa(),Rg=Pg(),Hx=Sn(),Dx=io();function Mx(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Ox.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Dx.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?Rg.composeNode(l,n,u,o):Rg.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Hx.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}xg.composeDoc=Mx});var nf=x(Tg=>{"use strict";var Fx=Ps("process"),Lx=qu(),Bx=Qa(),ro=to(),Ag=J(),qx=Cg(),Vx=Sn();function no(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 _g(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),i=!0,n=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),i=!1;break;default:i||(n=!0),i=!1}}return{comment:t,afterEmptyLine:n}}var wu=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=ea(i);a?this.warnings.push(new Zr.YAMLWarning(o,n,r)):this.errors.push(new Zr.YAMLParseError(o,n,r))},this.directives=new ME.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=Nm(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(ym.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];ym.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:Nm(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(FE.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,n,r)=>{let a=ea(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=BE.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 Zr.YAMLParseError(ea(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 Zr.YAMLParseError(ea(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=qE.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 Zr.YAMLParseError(ea(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 LE.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}}};bm.Composer=wu});var Em=C(as=>{"use strict";var VE=hu(),WE=mu(),JE=Xr(),km=Dr();function zE(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 JE.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return WE.resolveFlowScalar(e,t,n);case"block-scalar":return VE.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function GE(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=km.stringifyString({type:o,value:e},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
105
+ `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var rf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=no(i);a?this.warnings.push(new ro.YAMLWarning(o,r,n)):this.errors.push(new ro.YAMLParseError(o,r,n))},this.directives=new Lx.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=_g(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
+ ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Ag.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ag.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
107
+ ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
108
+ ${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:_g(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(Fx.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=no(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=qx.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new ro.YAMLParseError(no(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new ro.YAMLParseError(no(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Vx.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
+ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new ro.YAMLParseError(no(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new Bx.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}}};Tg.Composer=rf});var $g=x(vc=>{"use strict";var Wx=Xd(),zx=Zd(),Jx=to(),Ig=Ba();function Gx(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new Jx.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return zx.resolveFlowScalar(e,t,r);case"block-scalar":return Wx.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Ux(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Ig.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),u=s.substring(0,l),d=s.substring(l+1)+`
112
- `,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return Sm(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 UE(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=km.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">":KE(e,c);break;case'"':Nu(e,c,"double-quoted-scalar");break;case"'":Nu(e,c,"single-quoted-scalar");break;default:Nu(e,c,"scalar")}}function KE(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}];Sm(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 Sm(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 Nu(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})}}}as.createScalarToken=GE;as.resolveAsScalar=zE;as.setScalarValue=UE});var Cm=C(Rm=>{"use strict";var YE=e=>"type"in e?ss(e):os(e);function ss(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=ss(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=os(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=os(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=os(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 os({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=ss(t)),i)for(let a of i)r+=a.source;return n&&(r+=ss(n)),r}Rm.stringify=YE});var Tm=C(xm=>{"use strict";var bu=Symbol("break visit"),XE=Symbol("skip children"),Pm=Symbol("remove item");function tn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Am(Object.freeze([]),e,t)}tn.BREAK=bu;tn.SKIP=XE;tn.REMOVE=Pm;tn.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};tn.parentCollection=(e,t)=>{let i=tn.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 Am(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=Am(Object.freeze(e.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===bu)return bu;s===Pm&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}xm.visit=tn});var cs=C(qe=>{"use strict";var ku=Em(),QE=Cm(),ZE=Tm(),Su="\uFEFF",Eu="",Ru="",Cu="",eR=e=>!!e&&"items"in e,tR=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function iR(e){switch(e){case Su:return"<BOM>";case Eu:return"<DOC>";case Ru:return"<FLOW_END>";case Cu:return"<SCALAR>";default:return JSON.stringify(e)}}function nR(e){switch(e){case Su:return"byte-order-mark";case Eu:return"doc-mode";case Ru:return"flow-error-end";case Cu: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 jg(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 Kx(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Ig.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Yx(e,c);break;case'"':af(e,c,"double-quoted-scalar");break;case"'":af(e,c,"single-quoted-scalar");break;default:af(e,c,"scalar")}}function Yx(e,t){let i=t.indexOf(`
114
+ `),r=t.substring(0,i),n=t.substring(i+1)+`
115
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];jg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function jg(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 af(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}vc.createScalarToken=Ux;vc.resolveAsScalar=Gx;vc.setScalarValue=Kx});var Hg=x(Og=>{"use strict";var Xx=e=>"type"in e?wc(e):gc(e);function wc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=wc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=gc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=gc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=gc(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 gc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=wc(t)),i)for(let a of i)n+=a.source;return r&&(n+=wc(r)),n}Og.stringify=Xx});var Lg=x(Fg=>{"use strict";var of=Symbol("break visit"),Qx=Symbol("skip children"),Dg=Symbol("remove item");function Fr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Mg(Object.freeze([]),e,t)}Fr.BREAK=of;Fr.SKIP=Qx;Fr.REMOVE=Dg;Fr.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Fr.parentCollection=(e,t)=>{let i=Fr.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Mg(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Mg(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===of)return of;s===Dg&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Fg.visit=Fr});var yc=x(it=>{"use strict";var sf=$g(),Zx=Hg(),eC=Lg(),cf="\uFEFF",lf="",uf="",df="",tC=e=>!!e&&"items"in e,iC=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function rC(e){switch(e){case cf:return"<BOM>";case lf:return"<DOC>";case uf:return"<FLOW_END>";case df:return"<SCALAR>";default:return JSON.stringify(e)}}function nC(e){switch(e){case cf:return"byte-order-mark";case lf:return"doc-mode";case uf:return"flow-error-end";case df: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}qe.createScalarToken=ku.createScalarToken;qe.resolveAsScalar=ku.resolveAsScalar;qe.setScalarValue=ku.setScalarValue;qe.stringify=QE.stringify;qe.visit=ZE.visit;qe.BOM=Su;qe.DOCUMENT=Eu;qe.FLOW_END=Ru;qe.SCALAR=Cu;qe.isCollection=eR;qe.isScalar=tR;qe.prettyToken=iR;qe.tokenType=nR});var xu=C(_m=>{"use strict";var ta=cs();function mt(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var Im=new Set("0123456789ABCDEFabcdef"),rR=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ls=new Set(",[]{}"),aR=new Set(` ,[]{}
121
- \r `),Pu=e=>!e||aR.has(e),Au=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}it.createScalarToken=sf.createScalarToken;it.resolveAsScalar=sf.resolveAsScalar;it.setScalarValue=sf.setScalarValue;it.stringify=Zx.stringify;it.visit=eC.visit;it.BOM=cf;it.DOCUMENT=lf;it.FLOW_END=uf;it.SCALAR=df;it.isCollection=tC;it.isScalar=iC;it.prettyToken=rC;it.tokenType=nC});var pf=x(qg=>{"use strict";var ao=yc();function Ft(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Bg=new Set("0123456789ABCDEFabcdef"),aC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Nc=new Set(",[]{}"),oC=new Set(` ,[]{}
121
+ \r `),ff=e=>!e||oC.has(e),hf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
122
122
  `?!0:i==="\r"?this.buffer[t+1]===`
123
- `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let n=0;for(;i===" ";)i=this.buffer[++n+t];if(i==="\r"){let r=this.buffer[n+t+1];if(r===`
124
- `||!r&&!this.atEnd)return t+n+1}return i===`
125
- `||n>=this.indentNext||!i&&!this.atEnd?t+n:-1}if(i==="-"||i==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&mt(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]===ta.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 ta.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==="...")&&mt(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&&!mt(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===":")&&mt(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(Pu),"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("..."))&&mt(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield ta.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(Pu),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||mt(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=>mt(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":i+=1;break;case`
123
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
124
+ `||!n&&!this.atEnd)return t+r+1}return i===`
125
+ `||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Ft(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
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]===ao.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield ao.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==="...")&&Ft(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&&!Ft(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===":")&&Ft(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ff),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&Ft(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield ao.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(ff),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ft(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
127
+ `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
128
+ `,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Ft(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
129
129
  `:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
- `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
- `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(n=this.buffer[r];n===" ";)n=this.buffer[++r];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
132
- `;)n=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield ta.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(mt(a)||t&&ls.has(a))break;i=n}else if(mt(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&&ls.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&&ls.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield ta.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(Pu),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(mt(n)||i&&ls.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(;!mt(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(rR.has(i))i=this.buffer[++t];else if(i==="%"&&Im.has(this.buffer[t+1])&&Im.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
130
+ `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
+ `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
132
+ `;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
+ `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield ao.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Ft(a)||t&&Nc.has(a))break;i=r}else if(Ft(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
134
+ `?(r+=1,n=`
135
+ `,a=this.buffer[r+1]):i=r),a==="#"||t&&Nc.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Nc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ao.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ff),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ft(r)||i&&Nc.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Ft(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(aC.has(i))i=this.buffer[++t];else if(i==="%"&&Bg.has(this.buffer[t+1])&&Bg.has(this.buffer[t+2]))i=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,n;do n=this.buffer[++i];while(n===" "||t&&n===" ");let r=i-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=i),r}*pushUntil(t){let i=this.pos,n=this.buffer[i];for(;!t(n);)n=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};_m.Lexer=Au});var Iu=C(jm=>{"use strict";var Tu=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}}}};jm.LineCounter=Tu});var ju=C(Fm=>{"use strict";var oR=ho("process"),Om=cs(),sR=xu();function gi(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function $m(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 Dm(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 us(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 Hn(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 ds(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 Hm(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!gi(t.start,"explicit-key-ind")&&!gi(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Dm(t.value)?t.value.end?ds(t.value.end,t.sep):t.value.end=t.sep:ds(t.start,t.sep),delete t.sep)}var _u=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 sR.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,oR.env.LOG_TOKENS&&console.log("|",Om.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Om.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"&&Hm(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&&$m(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":{$m(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=us(this.peek(2)),n=Hn(i),r;t.end?(r=t.end,r.push(this.sourceToken),delete t.end):r=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};qg.Lexer=hf});var vf=x(Vg=>{"use strict";var mf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Vg.LineCounter=mf});var wf=x(Ug=>{"use strict";var sC=Ps("process"),Wg=yc(),cC=pf();function Ji(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function zg(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 Gg(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 bc(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 En(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 kc(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 Jg(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ji(t.start,"explicit-key-ind")&&!Ji(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Gg(t.value)?t.value.end?kc(t.value.end,t.sep):t.value.end=t.sep:kc(t.start,t.sep),delete t.sep)}var gf=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 cC.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,sC.env.LOG_TOKENS&&console.log("|",Wg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Wg.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Jg(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&&zg(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{zg(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=bc(this.peek(2)),r=En(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
139
139
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
140
- `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){ds(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(gi(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(Dm(i.key)&&!gi(i.sep,"newline")){let o=Hn(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(gi(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Hn(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]}):gi(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&&!gi(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)){ds(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||gi(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=us(n),a=Hn(r);Hm(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
140
+ `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){kc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ji(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(Gg(i.key)&&!Ji(i.sep,"newline")){let o=En(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(Ji(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=En(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Ji(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Ji(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){kc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Ji(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=bc(r),a=En(n);Jg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
141
141
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
142
- `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=us(t),n=Hn(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=us(t),n=Hn(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())}}};Fm.Parser=_u});var Vm=C(na=>{"use strict";var Mm=yu(),cR=Ur(),ia=Xr(),lR=gl(),uR=V(),dR=Iu(),Lm=ju();function Bm(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new dR.LineCounter||null,prettyErrors:t}}function fR(e,t={}){let{lineCounter:i,prettyErrors:n}=Bm(t),r=new Lm.Parser(i?.addNewLine),a=new Mm.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(ia.prettifyError(e,i)),s.warnings.forEach(ia.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function qm(e,t={}){let{lineCounter:i,prettyErrors:n}=Bm(t),r=new Lm.Parser(i?.addNewLine),a=new Mm.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 ia.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(ia.prettifyError(e,i)),o.warnings.forEach(ia.prettifyError(e,i))),o}function hR(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=qm(e,i);if(!r)return null;if(r.warnings.forEach(a=>lR.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 pR(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 uR.isDocument(e)&&!n?e.toString(i):new cR.Document(e,n,i).toString(i)}na.parse=hR;na.parseAllDocuments=fR;na.parseDocument=qm;na.stringify=pR});var ra=C(G=>{"use strict";var mR=yu(),vR=Ur(),gR=Zl(),Ou=Xr(),wR=_r(),wi=V(),yR=hi(),NR=de(),bR=mi(),kR=vi(),SR=cs(),ER=xu(),RR=Iu(),CR=ju(),fs=Vm(),Wm=Ar();G.Composer=mR.Composer;G.Document=vR.Document;G.Schema=gR.Schema;G.YAMLError=Ou.YAMLError;G.YAMLParseError=Ou.YAMLParseError;G.YAMLWarning=Ou.YAMLWarning;G.Alias=wR.Alias;G.isAlias=wi.isAlias;G.isCollection=wi.isCollection;G.isDocument=wi.isDocument;G.isMap=wi.isMap;G.isNode=wi.isNode;G.isPair=wi.isPair;G.isScalar=wi.isScalar;G.isSeq=wi.isSeq;G.Pair=yR.Pair;G.Scalar=NR.Scalar;G.YAMLMap=bR.YAMLMap;G.YAMLSeq=kR.YAMLSeq;G.CST=SR;G.Lexer=ER.Lexer;G.LineCounter=RR.LineCounter;G.Parser=CR.Parser;G.parse=fs.parse;G.parseAllDocuments=fs.parseAllDocuments;G.parseDocument=fs.parseDocument;G.stringify=fs.stringify;G.visit=Wm.visit;G.visitAsync=Wm.visitAsync});import{promises as Wj}from"fs";import ye from"path";import kr from"path";import{isDeepStrictEqual as R_}from"util";import{createHash as XN}from"crypto";function Qf(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Zf(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Zf(e[t]);return Object.freeze(e)}function ci(e){return Zf(structuredClone(e))}function Zc(e,t,i,n){return e.resolveStep({pkg:ci(t),state:ci(i),context:ci(n)})}function eh(e,t,i,n,r,a){return e.resolveNext({pkg:ci(t),state:ci(i),step:ci(n),outcome:ci(r),context:ci(a)})}function QN(e,t,i){return XN("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function el(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function th(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Zc(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=el(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:QN(s.runId,s.iteration,o.id),stepId:o.id};return ZN(e,s,c,i)}function ZN(e,t,i,n){let r=Qf(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function ih(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Zc(n,e,t,r):void 0,o=a?el(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?eh(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!el(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Td}from"fs";import Hg from"path";var ac=po(ra(),1);import{promises as Pg}from"fs";import Ut from"path";import{createHash as TR}from"node:crypto";import{promises as vt}from"node:fs";import tt from"node:path";import{TextDecoder as IR}from"node:util";import $u from"path";var PR=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),AR=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function xR(e){return e.toLowerCase().startsWith(".env")}function It(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>xR(n))?"environment-file":i.some(n=>AR.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>PR.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Hu(e,t){let i=It(t);if(i)return i;let n=$u.resolve(e.projectRoot,...t.split("/")),r=$u.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===$u.resolve(e.configFile)?"native-runtime":null}function yi(e){return e!==0&&e!==0n&&e!=="0"}function Ce(e,t){return yi(e.dev)&&yi(t.dev)&&yi(e.ino)&&yi(t.ino)}function M(e,t){let i=yi(e.dev)&&yi(t.dev);if(i&&e.dev!==t.dev)return!1;let n=yi(e.ino)&&yi(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var aa=1024*1024;function Du(e,t){let i=tt.relative(e,t);return i===""||!tt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${tt.sep}`)}function _R(e){let t=tt.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})||tt.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=It(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 jR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function OR(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hs(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ce(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Jm(e){let t=await vt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await vt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function $R(e,t){let i=tt.resolve(e),n=tt.resolve(t);if(!Du(i,n))throw new Error("Native artifact path is outside its root");let r=[await Jm(i)],a=i;for(let o of tt.relative(i,n).split(tt.sep).filter(Boolean)){a=tt.join(a,o);let s=await Jm(a);if(!Du(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function zm(e){for(let t of e){let i=await vt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!OR(t,i)||await vt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function $e(e){let t=_R(e.ref),i=jR(e.maxBytes??aa),n=tt.resolve(e.root,...t.split("/")),r=await $R(e.root,tt.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await vt.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 vt.realpath(n);if(!Du(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await vt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),vt.lstat(n),vt.realpath(n)]);if(await zm(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!hs(a,c)||!hs(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,S=await s.read(p,0,Math.min(p.length,k),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),vt.lstat(n),vt.realpath(n)]);if(await zm(r),!h.isFile()||h.isSymbolicLink()||v!==o||!hs(c,m)||!hs(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),N;try{N=new IR("utf-8",{fatal:!0}).decode(b)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:TR("sha256").update(b).digest("hex"),text:N}}finally{await s.close()}}import{randomUUID as HR}from"crypto";import{promises as Pe}from"fs";import gt from"path";function Mu(e,t){let i=gt.relative(e,t);return i===""||!gt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gt.sep}`)}function DR(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fu(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ce(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Gm(e){let t=await Pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function oa(e){for(let t of e){let i=await Pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!DR(t,i)||await Pe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function FR(e,t){let i=gt.resolve(e),n=gt.resolve(t);if(!Mu(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await Gm(i)],a=gt.relative(i,n).split(gt.sep).filter(Boolean),o=i;for(let s of a){await oa(r),o=gt.join(o,s);try{await Pe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Gm(o);if(!Mu(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await oa(r),r}async function MR(e){let t;try{t=await Pe.open(e,"r"),await t.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await t?.close()}}async function Um(e,t,i={}){let n=gt.dirname(e),r=i.containedRoot?await FR(i.containedRoot,n):null;r||await Pe.mkdir(n,{recursive:!0});let a=gt.join(n,`.${gt.basename(e)}.${HR()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Pe.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([Pe.lstat(a),Pe.realpath(a)]);if(await oa(r),!c.isFile()||c.isSymbolicLink()||!Fu(s,c)||!Mu(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Fu(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),r){await oa(r);let c=await Pe.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Fu(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Pe.link(a,e),await Pe.unlink(a)):await Pe.rename(a,e),await MR(n)}catch(c){if(await o?.close(),!r)await Pe.rm(a,{force:!0});else try{await oa(r),await Pe.rm(a,{force:!0})}catch{}throw c}}async function Ve(e,t,i={}){await Um(e,t,i)}async function Km(e,t,i={}){await Um(e,t,i)}async function ve(e,t,i={}){await Ve(e,JSON.stringify(t,null,2)+`
143
- `,i)}import rC from"path";var ca=po(ra(),1);import ms from"path";var la=64*1024,vs=1024,gs=64,Xm=5,LR=[".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/**"],wt={include:["**/*"],exclude:[...LR],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},ps={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
- # ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs, changes, and runtime data.","native.language":`# Artifact language used by Native workflow documents.
145
- # language: en | zh-CN`,"native.clarification_mode":`# Controls whether Native asks one clarification at a time or every currently answerable question in a round.
146
- # clarification_mode: sequential | batch`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
147
- # archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed contract before Native stops the completion loop.","native.snapshot":"# Controls the auditable project scope and bounded work used by Native content snapshots.","native.snapshot.include":"# Selects the project-relative paths included in Native snapshots. Patterns use / and support *, **, and ?.","native.snapshot.exclude":"# Removes paths from the included scope. Exclusions are bound into each new change baseline.","native.snapshot.max_files":"# Bounds the number of files captured by one snapshot. Increase it for large monorepos.","native.snapshot.max_total_bytes":"# Bounds the total file content hashed by one snapshot. Content is streamed and does not depend on Git hashes.","native.snapshot.max_duration_ms":"# Bounds snapshot capture time in milliseconds. Increase it together with the byte budget on slower or larger repositories.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
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=bc(t),r=En(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=bc(t),r=En(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ug.Parser=gf});var Zg=x(so=>{"use strict";var Kg=nf(),lC=Qa(),oo=to(),uC=td(),dC=J(),fC=vf(),Yg=wf();function Xg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new fC.LineCounter||null,prettyErrors:t}}function hC(e,t={}){let{lineCounter:i,prettyErrors:r}=Xg(t),n=new Yg.Parser(i?.addNewLine),a=new Kg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(oo.prettifyError(e,i)),s.warnings.forEach(oo.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Qg(e,t={}){let{lineCounter:i,prettyErrors:r}=Xg(t),n=new Yg.Parser(i?.addNewLine),a=new Kg.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new oo.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(oo.prettifyError(e,i)),o.warnings.forEach(oo.prettifyError(e,i))),o}function pC(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Qg(e,i);if(!n)return null;if(n.warnings.forEach(a=>uC.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 mC(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return dC.isDocument(e)&&!r?e.toString(i):new lC.Document(e,r,i).toString(i)}so.parse=pC;so.parseAllDocuments=hC;so.parseDocument=Qg;so.stringify=mC});var Lr=x(Y=>{"use strict";var vC=nf(),gC=Qa(),wC=Dd(),yf=to(),yC=Ha(),Gi=J(),NC=qi(),bC=ye(),kC=Wi(),SC=zi(),EC=yc(),PC=pf(),RC=vf(),xC=wf(),Sc=Zg(),ew=Ia();Y.Composer=vC.Composer;Y.Document=gC.Document;Y.Schema=wC.Schema;Y.YAMLError=yf.YAMLError;Y.YAMLParseError=yf.YAMLParseError;Y.YAMLWarning=yf.YAMLWarning;Y.Alias=yC.Alias;Y.isAlias=Gi.isAlias;Y.isCollection=Gi.isCollection;Y.isDocument=Gi.isDocument;Y.isMap=Gi.isMap;Y.isNode=Gi.isNode;Y.isPair=Gi.isPair;Y.isScalar=Gi.isScalar;Y.isSeq=Gi.isSeq;Y.Pair=NC.Pair;Y.Scalar=bC.Scalar;Y.YAMLMap=kC.YAMLMap;Y.YAMLSeq=SC.YAMLSeq;Y.CST=EC;Y.Lexer=PC.Lexer;Y.LineCounter=RC.LineCounter;Y.Parser=xC.Parser;Y.parse=Sc.parse;Y.parseAllDocuments=Sc.parseAllDocuments;Y.parseDocument=Sc.parseDocument;Y.stringify=Sc.stringify;Y.visit=ew.visit;Y.visitAsync=ew.visitAsync});import{promises as VS}from"node:fs";import Ou from"node:path";import{promises as xu}from"fs";import xe from"path";import{promises as Dk}from"fs";import Sa from"path";import{isDeepStrictEqual as fH}from"util";import{createHash as QS}from"crypto";function cm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function lm(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))lm(e[t]);return Object.freeze(e)}function Di(e){return lm(structuredClone(e))}function Du(e,t,i,r){return e.resolveStep({pkg:Di(t),state:Di(i),context:Di(r)})}function um(e,t,i,r,n,a){return e.resolveNext({pkg:Di(t),state:Di(i),step:Di(r),outcome:Di(n),context:Di(a)})}function ZS(e,t,i){return QS("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Mu(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function dm(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Du(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Mu(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:ZS(s.runId,s.iteration,o.id),stepId:o.id};return eE(e,s,c,i)}function eE(e,t,i,r){let n=cm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function fm(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Du(r,e,t,n):void 0,o=a?Mu(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?um(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Mu(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Rh}from"fs";import yN from"path";var Rl=hn(Lr(),1);import{promises as lN}from"fs";import li from"path";import{execFileSync as CC}from"child_process";import co from"path";function Pn(e,t){return CC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function AC(e,t){let i=co.normalize(e),r=co.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ae(e){try{let t=co.resolve(Pn(e,["rev-parse","--show-toplevel"])),r=Pn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?co.resolve(r.slice(9)):t,a=null;try{a=Pn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!AC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function tw(e){try{Pn(e,["rev-parse","--is-inside-work-tree"]);let t=Pn(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:co.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Rn(e){return tw(e).map(t=>t.root)}function Nf(e,t){try{let i=Pn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as jC}from"node:crypto";import{promises as Lt}from"node:fs";import St from"node:path";import{TextDecoder as $C}from"node:util";import bf from"path";var _C=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),TC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function IC(e){return e.toLowerCase().startsWith(".env")}function ii(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>IC(r))?"environment-file":i.some(r=>TC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>_C.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function kf(e,t){let i=ii(t);if(i)return i;let r=bf.resolve(e.projectRoot,...t.split("/")),n=bf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===bf.resolve(e.configFile)?"native-runtime":null}function Ui(e){return e!==0&&e!==0n&&e!=="0"}function Fe(e,t){return Ui(e.dev)&&Ui(t.dev)&&Ui(e.ino)&&Ui(t.ino)}function W(e,t){let i=Ui(e.dev)&&Ui(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ui(e.ino)&&Ui(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var lo=1024*1024;function Sf(e,t){let i=St.relative(e,t);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}function OC(e){let t=St.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||St.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ii(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function HC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function DC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ec(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function iw(e){let t=await Lt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Lt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function MC(e,t){let i=St.resolve(e),r=St.resolve(t);if(!Sf(i,r))throw new Error("Native artifact path is outside its root");let n=[await iw(i)],a=i;for(let o of St.relative(i,r).split(St.sep).filter(Boolean)){a=St.join(a,o);let s=await iw(a);if(!Sf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function rw(e){for(let t of e){let i=await Lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!DC(t,i)||await Lt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Q(e){let t=OC(e.ref),i=e.maxBytes===null?null:HC(e.maxBytes??lo),r=St.resolve(e.root,...t.split("/")),n=await MC(e.root,St.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Lt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Lt.realpath(r);if(!Sf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Lt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await rw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ec(a,c)||!Ec(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let E=i===null?p.length:i+1-f,S=await s.read(p,0,Math.min(p.length,E),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await rw(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Ec(c,v)||!Ec(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let N=Buffer.concat(d,f),y;try{y=new $C("utf-8",{fatal:!0}).decode(N)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:jC("sha256").update(N).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as FC}from"crypto";import{promises as Le}from"fs";import Bt from"path";function Pf(e,t){let i=Bt.relative(e,t);return i===""||!Bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Bt.sep}`)}function LC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ef(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function nw(e){let t=await Le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function uo(e){for(let t of e){let i=await Le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!LC(t,i)||await Le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function BC(e,t){let i=Bt.resolve(e),r=Bt.resolve(t);if(!Pf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await nw(i)],a=Bt.relative(i,r).split(Bt.sep).filter(Boolean),o=i;for(let s of a){await uo(n),o=Bt.join(o,s);try{await Le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await nw(o);if(!Pf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await uo(n),n}async function qC(e){let t;try{t=await Le.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function aw(e,t,i={}){let r=Bt.dirname(e),n=i.containedRoot?await BC(i.containedRoot,r):null;n||await Le.mkdir(r,{recursive:!0});let a=Bt.join(r,`.${Bt.basename(e)}.${FC()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Le.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([Le.lstat(a),Le.realpath(a)]);if(await uo(n),!c.isFile()||c.isSymbolicLink()||!Ef(s,c)||!Pf(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Ef(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await uo(n);let c=await Le.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Ef(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Le.link(a,e),await Le.unlink(a)):await Le.rename(a,e),await qC(r)}catch(c){if(await o?.close(),!n)await Le.rm(a,{force:!0});else try{await uo(n),await Le.rm(a,{force:!0})}catch{}throw c}}async function ue(e,t,i={}){await aw(e,t,i)}async function ow(e,t,i={}){await aw(e,t,i)}async function te(e,t,i={}){await ue(e,JSON.stringify(t,null,2)+`
143
+ `,i)}import dA from"path";var fo=hn(Lr(),1);import Rc from"path";var ho=64*1024,xc=1024,Cc=64,cw=5,VC=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/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/**"],WC=["**/.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"],zC=[...VC,...WC].sort((e,t)=>e.localeCompare(t,"en"));var qt={include:["**/*"],exclude:[...zC],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Pc={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
+ # ambient_resume: true | false`,hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
145
+ # language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time.
146
+ # clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
147
+ # archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.snapshot":"# Controls the auditable project scope and bounded work used by Native content snapshots.","native.snapshot.include":"# Selects the project-relative paths included in Native snapshots. Patterns use / and support *, **, and ?.","native.snapshot.exclude":"# Removes paths from the included scope. Exclusions are bound into each new change baseline.","native.snapshot.max_files":"# Bounds the number of files captured by one snapshot. Increase it for large monorepos.","native.snapshot.max_total_bytes":"# Bounds the total file content hashed by one snapshot. Content is streamed and does not depend on Git hashes.","native.snapshot.max_duration_ms":"# Bounds snapshot capture time in milliseconds. Increase it together with the byte budget on slower or larger repositories.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
148
148
  # artifact_layout: legacy | docs`,"classic.language":`# Artifact language used by Classic workflow documents.
149
149
  # language: en | zh-CN`,"classic.context_compression":`# Controls beta context compression for new Classic changes.
150
150
  # context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
151
151
  # review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
152
152
  # auto_transition: true | false`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
153
- # ambient_resume: true | false`,native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 产物的存放根目录,包括规格、change 和运行时数据。","native.language":`# Native 工作流文档使用的产物语言。
154
- # 可选值:en | zh-CN`,"native.clarification_mode":`# Native 每轮询问一个问题,或一次提出当前所有可回答的问题。
155
- # 可选值:sequential | batch`,"native.archive_confirmation":`# Native 归档预演成功后自动归档,或等待用户明确确认。
156
- # 可选值:automatic | required`,"native.max_verify_failures":"# 同一份已确认 contract 最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.snapshot":"# Native 内容快照使用的可审计项目范围与有界工作预算。","native.snapshot.include":"# Native 快照纳入的项目相对路径;模式使用 /,支持 *、** 和 ?。","native.snapshot.exclude":"# 从纳入范围中排除路径;新 change 会把排除策略绑定到 baseline。","native.snapshot.max_files":"# 单次快照最多捕获的文件数;大型 monorepo 可按需提高。","native.snapshot.max_total_bytes":"# 单次快照最多哈希的文件内容总字节数;内容采用流式读取,不依赖 Git hash。","native.snapshot.max_duration_ms":"# 单次快照的最长执行时间(毫秒);较慢或更大的仓库应与字节预算一并提高。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
153
+ # ambient_resume: true | false`,hook:"# Native 和 Classic 共享的 Hook 写入策略;路径必须是项目相对路径。","hook.allow_paths":"# 在受保护阶段允许写入的项目相对目录;每项填写一个目录,默认为空。",native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
154
+ # 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
155
+ # 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
156
+ # 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.snapshot":"# Native 内容快照使用的可审计项目范围与有界工作预算。","native.snapshot.include":"# Native 快照纳入的项目相对路径;模式使用 /,支持 *、** 和 ?。","native.snapshot.exclude":"# 从纳入范围中排除路径;新 change 会把排除策略绑定到 baseline。","native.snapshot.max_files":"# 单次快照最多捕获的文件数;大型 monorepo 可按需提高。","native.snapshot.max_total_bytes":"# 单次快照最多哈希的文件内容总字节数;内容采用流式读取,不依赖 Git hash。","native.snapshot.max_duration_ms":"# 单次快照的最长执行时间(毫秒);较慢或更大的仓库应与字节预算一并提高。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
157
157
  # 可选值:legacy | docs`,"classic.language":`# Classic 工作流文档使用的产物语言。
158
158
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
159
159
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
160
160
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
161
- # 可选值:true | false`}};function Qm(e,t){return ps[t][e]}function BR(e,t,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let r=n[1].length,a=n[2];if(r===0&&a in ps.en)return a;if(r===2&&t){let o=`${t}.${a}`;if(o in ps.en)return o}if(r===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in ps.en)return o}return null}function ua(e,t){let i=[],n=null,r=null;for(let a of(0,ca.stringify)(e).trimEnd().split(`
162
- `)){let o=BR(a,n,r);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of Qm(o,t).split(`
163
- `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?n="native":a.startsWith("classic:")?n="classic":n=null,r=null):/^ {2}[a-z_]+:/u.test(a)&&n==="native"&&(r=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
164
- `)}function qR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||ms.posix.isAbsolute(i)||ms.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 Fn(e){let t=qR(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Zm(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 Bu(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||ms.posix.isAbsolute(n)||ms.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 sa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ev(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 ws(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>vs)throw new Error(`${t} exceeds ${vs} characters`);let 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>gs)throw new Error(`${t} contains more than ${gs} wildcard tokens`);return e}function Ym(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=>ws(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function Lu(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 VR(e){if(e===void 0)return{...wt,include:[...wt.include],exclude:[...wt.exclude]};let t=sa(e,"native.snapshot");return{include:Ym(t.include,"native.snapshot.include",wt.include),exclude:Ym(t.exclude,"native.snapshot.exclude",wt.exclude),max_files:Lu(t.max_files,wt.max_files,"native.snapshot.max_files"),max_total_bytes:Lu(t.max_total_bytes,wt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Lu(t.max_duration_ms,wt.max_duration_ms,"native.snapshot.max_duration_ms")}}function WR(e){if(e===void 0)return;let t=sa(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=sa(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:Fn(n),toArtifactRoot:Fn(r),stage:a,...o?{cleanup:o}:{}}}function JR(e,t={}){let i=sa(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??Xm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=WR(i.pending_root_move);return{artifact_root:Fn(n),language:ev(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:VR(i.snapshot),...s?{pending_root_move:s}:{}}}function zR(e){let t=sa(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:Zm(t.artifact_layout),language:ev(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function GR(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function UR(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 Mn(e,t={}){let i=(0,ca.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=GR(r.ambient_resume),o=r.native===void 0?void 0:JR(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:zR(r.classic),c=UR(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function tv(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function iv(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,snapshot:e.native.snapshot,...e.native.pending_root_move?{pending_root_move:tv(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function Dn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function da(e,t){let i=iv(t),n=Mn((0,ca.stringify)(i)).config;if(!n)throw new Error("Unsupported Comet project schema");let r={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.native){let a=Dn(e.native),o=Dn(a.snapshot),s={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,snapshot:{...o,...n.native.snapshot}};if(n.native.pending_root_move){let c=Dn(a.pending_root_move),l=tv(n.native.pending_root_move),u=Dn(c.cleanup),d=Dn(l.cleanup);s.pending_root_move={...c,...l,...l.cleanup?{cleanup:{...u,...d}}:{}}}else delete s.pending_root_move;r.native=s}return n.classic&&(r.classic={...Dn(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition}),r}import{createHash as YR}from"crypto";import{promises as bs}from"fs";import Ni from"path";import{constants as ys,promises as nn}from"fs";var yt=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function qu(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function nv(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function fa(e){return{dev:e.dev,ino:e.ino,birthtime:qu(e)}}function Ns(e,t){let i=fa(e),n=fa(t);return Ce(i,n)?M(i,n):M(i,n)&&qu(e)===qu(t)&&nv(e)===nv(t)&&e.size===t.size}async function rn(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 nn.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new yt("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new yt("too-large",`${n} exceeds ${t} bytes`);let o=await nn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:fa(a)});let s=process.platform==="win32"?ys.O_RDONLY:ys.O_RDONLY|ys.O_NOFOLLOW|ys.O_NONBLOCK,c;try{c=await nn.open(e,s)}catch(l){throw l.code==="ELOOP"?new yt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),nn.lstat(e,{bigint:r}),nn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ns(a,l)||!Ns(a,u))throw new yt("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:fa(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 yt("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([c.stat({bigint:r}),nn.lstat(e,{bigint:r}),nn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||b!==o||!Ns(a,h)||!Ns(a,v))throw new yt("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:fa(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:b}}finally{await c.close()}}function KR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Vu(e,t){let i=Ni.relative(e,t);return i===""||!Ni.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ni.sep}`)}async function rv(e,t){let i=Ni.resolve(e),n=await bs.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return bs.realpath(i)}async function av(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=Ni.join(r,i[a]);let o;try{o=await bs.lstat(r)}catch(u){if(KR(u))return{exists:!1,kind:"missing"};throw u}let s=Ni.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 bs.realpath(r);if(!Vu(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 ha(e,t,i){let n=Bu(t,i.label),r=Ni.resolve(e),a=await rv(r,i.label),o=n.split("/"),s=Ni.resolve(r,...o);if(!Vu(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await av(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function an(e,t,i,n){let r=await ha(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 rv(r.projectRoot,n.label);return rn(r.target,i,{...n,verify:async(o,s)=>{if(!Vu(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await av(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var pa=".comet/config.yaml";function Wu(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function XR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ju(e,t={}){return(await ma(e,t)).document}async function ov(e){try{return(await an(e,pa,la,{label:pa})).bytes}catch(t){if(XR(t))return null;throw t}}function sv(e){return e?{exists:!0,sha256:YR("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ks(e){return sv(await ov(e))}async function ma(e,t={}){let i=await ov(e);return{document:i?Mn(i.toString("utf8"),t):null,identity:sv(i)}}var h0=16*1024;async function zu(e,t){if(!t)return;let i=await ks(e);if(!Wu(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as Ln}from"fs";import Y from"path";import tC from"os";var Es=".comet/config.yaml";async function Gu(e){try{return await Ln.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function iC(e){try{let t=await Ln.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function va(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}async function ga(e){let t=[],i=e;for(;!await Gu(i);){let r=Y.dirname(i);if(r===i)break;t.push(Y.basename(i)),i=r}let n=await Ln.realpath(i);return Y.resolve(n,...t.reverse())}async function cv(e){try{return(await Ln.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Uu(e){let t=Y.resolve(e);try{(await Ln.stat(t)).isDirectory()||(t=Y.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=Y.resolve(tC.homedir());for(;;){if(!(t===n&&i!==n)){let o=Y.join(t,...Es.split("/")),s=t===i||await iC(o);if(await Gu(o)&&s)return t}if(await Gu(Y.join(t,".git")))return t;let a=Y.dirname(t);if(a===t)return i;t=a}}function Rs(e){return Fn(e)}async function nC(e,t){let i=Rs(t),n=Y.resolve(e,...i.split("/")),r=await Ln.realpath(e),a=await ga(n);if(!va(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function _t(e,t){let i=Rs(t),n=await nC(e,i),r=Y.join(n,"comet");if(await cv(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ga(n),ga(r)]);if(!va(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:Y.resolve(e),configFile:Y.join(e,...Es.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:Y.join(r,"specs"),changesDir:Y.join(r,"changes"),archiveDir:Y.join(r,"archive"),runtimeDir:Y.join(r,"runtime"),locksDir:Y.join(r,"runtime","locks"),transactionsDir:Y.join(r,"runtime","transactions")}}function q(e,t){return va(Y.resolve(e),Y.resolve(t))}async function _(e,t){let i=Y.resolve(e),n=Y.resolve(t);if(!va(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await cv(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([ga(i),ga(n)]);if(!va(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Ku=wt;var Cs=ws;async function We(e){let t=(await Ju(e))?.config??null;return t?.native?t:null}async function Bn(e){let t=await We(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 qn(e,t,i={}){let n=await ma(e,{allowPartialProject:!0}),r=da(n.document?.value??{},t),a=rC.join(e,...Es.split("/"));await Ve(a,ua(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await zu(e,n.identity)}})}import{promises as LC}from"fs";import BC from"path";import{AsyncLocalStorage as aC}from"async_hooks";import{randomUUID as fv}from"crypto";import{promises as it}from"fs";import hv from"os";import ae from"path";var uv=16*1024,Yu=".coordinator",oC=5e3,dv=new aC,Ps=new Map;function sC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function cC(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 pv(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 Xu(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ce(i,n)?M(i,n):M(i,n)&&e.size===t.size}function As(e,t){return Xu(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function lC(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&As(e.identity,t.identity)}async function jt(e){let t,i;try{let n=await rn(e,uv,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof yt?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${uv} 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:cC(JSON.parse(t.toString("utf8")),e),identity:pv(i)}}async function uC(e){return(await jt(e))?.owner??null}function Qu(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==hv.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vC(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dC(e,t){try{await it.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await it.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function xs(e,t){let i=await jt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!As(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await it.mkdir(t,{recursive:!0});let n=ae.join(t,`${ae.basename(e.file)}.${e.owner.id}.${fv()}.removed`);try{await it.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await jt(n);if(!r||r.owner.id!==e.owner.id||!Xu(r.identity,e.identity))throw await dC(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await it.rm(n,{force:!0}),"removed"}function mv(e){return{id:fv(),pid:process.pid,hostname:hv.hostname(),createdAt:new Date().toISOString(),operation:e}}async function vv(e,t){let i;try{i=await it.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await uC(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)+`
165
- `,"utf8"),await i.sync(),pv(await i.stat({bigint:!0}))}finally{await i.close()}}async function fC(e,t){let i=await _(e.nativeRoot,e.locksDir);await it.mkdir(i,{recursive:!0});let n=await _(e.nativeRoot,ae.join(i,Yu));await it.mkdir(n,{recursive:!0});let r=mv(t),a=ae.join(n,`.${r.id}.tmp`),o=ae.join(n,`${r.id}.claim`);try{let s=await vv(a,r);await it.rename(a,o);let c=await jt(o);if(!c||!Xu(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 it.rm(a,{force:!0})}}async function hC(e){let t=ae.dirname(e.file),i=!1,n=ae.basename(e.file);for(let r of await it.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ae.join(t,r.name);if(ae.resolve(a)!==ae.resolve(e.file))try{let o=await jt(a),s=Qu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await xs(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function gv(e){let t=await jt(e.file);if(t){if(t.owner.id!==e.owner.id||!As(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await xs(t,ae.dirname(e.file))}}async function pC(e,t){let i=Date.now()+oC;for(;;){let n=await fC(e,t);if(!await hC(n))return n;if(await gv(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 mC(e){let t=Ps.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Ps.set(e,r),await t,()=>{i(),Ps.get(e)===r&&Ps.delete(e)}}async function Ts(e,t,i){let n=ae.resolve(e.locksDir),r=dv.getStore();if(r?.has(n))return i();let a=await mC(n);try{let o=await pC(e,t),s=new Map(r??[]);return s.set(n,o),await dv.run(s,async()=>{try{return await i()}finally{await gv(o)}})}finally{a()}}async function Is(e,t,i){let n=[...new Map(e.map(a=>[ae.resolve(a.locksDir),a])).values()].sort((a,o)=>ae.resolve(a.locksDir).localeCompare(ae.resolve(o.locksDir))),r=async a=>{let o=n[a];return o?Ts(o,t,()=>r(a+1)):i()};return r(0)}async function bi(e,t,i){return Ts(e,`acquire ${t}`,async()=>{let n=await _(e.nativeRoot,e.locksDir);await it.mkdir(n,{recursive:!0});let r=await _(e.nativeRoot,ae.join(n,sC(t))),a=mv(i),o=await vv(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function ki(e){await jt(e.file)&&await Ts(e,`release ${ae.basename(e.file)}`,async()=>{let t=await jt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!As(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ae.join(e.locksDir,Yu);await xs(t,i)})}function vC(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function wa(e){return Qu(await jt(e))}async function Zu(e,t,i){return Ts(e,`take over ${ae.basename(t)}`,async()=>{let n=await _(e.nativeRoot,e.locksDir),r=await _(e.nativeRoot,t);if(ae.resolve(ae.dirname(r))!==ae.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await jt(r),o=Qu(a);if(o.status==="missing")return{status:"missing"};if(i&&!lC(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=ae.join(n,Yu);return await xs(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as ya}from"fs";import nt from"path";import{TextDecoder as bC}from"util";import{createHash as gC}from"node:crypto";import{constants as _s,promises as L}from"node:fs";import z from"node:path";import{TextDecoder as wC}from"node:util";function Ae(e,t){let i=z.relative(e,t);return i===""||!z.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${z.sep}`)}function wv(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Wn(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yv(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Vn(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Si(e,t){let i=await L.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await L.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Ei(e,t,i){let n=z.resolve(e),r=z.resolve(t);if(!Ae(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Si(n,i)],o=n;for(let s of z.relative(n,r).split(z.sep).filter(Boolean)){await le(a,i),o=z.join(o,s);let c=await Si(o,i);if(!Ae(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await le(a,i),a}async function le(e,t){for(let i of e){let n=await L.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Wn(i,n)||await L.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function yC(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 Z(e){let t=wv(e.maxBytes),i=z.resolve(e.file),n=await Ei(e.root,z.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Si(z.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await le(n,e.label);let a=await L.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=yv(a),s=await L.realpath(i);if(!Ae(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Ae(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?_s.O_RDONLY:_s.O_RDONLY|_s.O_NOFOLLOW|_s.O_NONBLOCK,l=await L.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([L.lstat(i),L.realpath(i)]);if(await le(n,e.label),await le(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Vn(o,u)||!Vn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await yC(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),L.lstat(i),L.realpath(i)]);if(await le(n,e.label),await le(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Vn(o,m)||!Vn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:gC("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function js(e){let t=await Z(e),i;try{i=new wC("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 Ke(e){let t=await Ei(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await L.readdir(e.directory,{withFileTypes:!0});else{let n=wv(e.maxEntries);i=[];let r=await L.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 le(t,e.label),{entries:i,verify:()=>le(t,e.label)}}async function Ri(e){let t=await Ei(e.root,e.directory,e.label);return{verify:()=>le(t,e.label)}}async function NC(e){let t=z.resolve(e.directory),i=z.resolve(e.quarantine);if(z.dirname(i)!==z.dirname(t)||!Ae(z.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await Ei(e.root,z.dirname(t),e.label),r=await Si(t,e.label);if(!Ae(n[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await le(n,e.label);let a=await L.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Wn(r,a)||await L.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await L.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await L.rename(t,i),await le(n,e.label);let o=await L.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Wn(r,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await L.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:n,identity:r}}async function Nv(e){await NC(e)}async function Os(e){let t=z.resolve(e.file),i=await Ei(e.root,z.dirname(t),e.label),n=await L.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=yv(n),a=await L.realpath(t);if(!Ae(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await Z({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([L.lstat(t),L.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Vn(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await le(i,e.label);let[l,u]=await Promise.all([L.lstat(t),L.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Vn(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await L.rm(t),await le(i,e.label)}async function ed(e){let t=z.resolve(e.directory),i=await Ei(e.root,z.dirname(t),e.label),n=await Si(t,e.label);if(!Ae(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await le(i,e.label);let r=await L.lstat(t);if(!r.isDirectory()||r.isSymbolicLink()||!Wn(n,r)||await L.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await L.rmdir(t),await le(i,e.label)}async function Ot(e){let t=z.resolve(e.root),i=z.resolve(e.directory);if(!Ae(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await Si(t,e.label)],r=t;for(let a of z.relative(t,i).split(z.sep).filter(Boolean)){await le(n,e.label),r=z.join(r,a);try{await L.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Si(r,e.label);if(!Ae(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await le(n,e.label)}async function td(e){let t=z.resolve(e.root),i=z.resolve(e.source),n=z.resolve(e.target);if(i===n||!Ae(t,i)||!Ae(t,n)||Ae(i,n)||Ae(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Ot({root:t,directory:z.dirname(n),label:`${e.label} target parent`});let r=await Ei(t,z.dirname(i),e.label),a=await Ei(t,z.dirname(n),e.label),o=await Si(i,e.label);if(!Ae(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await L.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([le(r,e.label),le(a,e.label)]);let s=await L.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Wn(o,s)||await L.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await L.rename(i,n),await Promise.all([le(r,e.label),le(a,e.label)]);let c=await L.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Wn(o,c)||!Ae(r[0].realPath,await L.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await L.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Ci(e){let t=await Z({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Km(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await L.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await Z({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await Z({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var kC=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),SC=new Set(["id","type","source","target","staged","backup"]),EC=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),RC=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),CC=new Set(["sequence","timestamp","type","operationId"]),Ev=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Rv=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),PC=256*1024,AC=1024*1024,Cv=16*1024,Hs=1024,rd=64*1024*1024,xC=2e4,Pv=new bC("utf-8",{fatal:!0});function Na(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ba(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 zn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function id(e,t){if(typeof e!="string"||e.length===0||nt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function $s(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function bv(e,t){if(id(e,t),e.includes("\\")||e!==nt.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 TC(e,t){let i=Na(e,`transaction operations[${t}]`);if(ba(i,SC,`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`);id(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&id(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 Fs(e){let t=Na(e,"Native Archive transaction journal");if(ba(t,EC,"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"||!Ev.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(!zn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if($s(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=Na(s,`Archive transaction operations[${c}]`);if(ba(l,RC,`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`);bv(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&bv(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&$s(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($s(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`);$s(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 ad(e){let t=Na(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Fs(t);if(ba(t,kC,"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"||!Ev.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!nt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!nt.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(!zn(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(TC),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 Av(e,t){let i=Na(e,`Native transaction event at line ${t}`);if(ba(i,CC,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!zn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Rv.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=i.type==="operation-started"||i.type==="operation-completed";if(n&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!n&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function IC(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;n<e.length;n+=1){let r=t[n],a=e[n];if(r==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==r)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[n,r,a,o]of i){if(e.length<=n)continue;let s=e.slice(n,Math.min(n+r,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(r,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!zn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||zn(e)}function Jn(e,t){return e.length<t.length&&t.startsWith(e)}function _C(e){let t='","operationId":"';if(Jn(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),n=i.indexOf('"');if(n===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let r=i.slice(0,n);return/^[a-z0-9][a-z0-9-]*$/u.test(r)?Jn(i.slice(n),'"}'):!1}function jC(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Cv)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Jn(e,i))return!0;if(!e.startsWith(i))return!1;let n=e.slice(i.length),r=n.slice(0,Math.min(24,n.length));if(!IC(r))return!1;if(n.length<24)return!0;if(!zn(r))return!1;let a='","type":"',o=n.slice(24);if(Jn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Rv){if(Jn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(_C(l))return!0}else if(Jn(l,'"}'))return!0}return!1}function OC(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Cv)throw new Error(`Native transaction event at line ${t} is too large`);return Av(JSON.parse(e),t)}function $C(e){let t=e.split(`
166
- `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Hs)throw new Error(`Native transaction event log exceeds ${Hs} events`);let n=[];for(let r=0;r<t.length;r+=1){let a=r+1,o=t[r],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&r===t.length-1;try{n.push(OC(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&jC(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return n}function xv(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
161
+ # 可选值:true | false`}};function lw(e,t){return Pc[t][e]}function JC(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Pc.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Pc.en)return o}if(n===2&&t===null&&a==="hook")return"hook";if(n===2&&t==="hook"&&a==="allow_paths")return"hook.allow_paths";if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Pc.en)return o}return null}function po(e,t){let i=[],r=null,n=null;for(let a of(0,fo.stringify)(e).trimEnd().split(`
162
+ `)){let o=JC(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of lw(o,t).split(`
163
+ `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":a.startsWith("hook:")?r="hook":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
164
+ `)}function GC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Rc.posix.isAbsolute(i)||Rc.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Cn(e){let t=GC(e,"native.artifact_root");return t.length===0?".":t.join("/")}function uw(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 Ac(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Rc.posix.isAbsolute(r)||Rc.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function An(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function dw(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function _c(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>xc)throw new Error(`${t} exceeds ${xc} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Cc)throw new Error(`${t} contains more than ${Cc} wildcard tokens`);return e}function sw(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>_c(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Rf(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function UC(e){if(e===void 0)return{...qt,include:[...qt.include],exclude:[...qt.exclude]};let t=An(e,"native.snapshot");return{include:sw(t.include,"native.snapshot.include",qt.include),exclude:sw(t.exclude,"native.snapshot.exclude",qt.exclude),max_files:Rf(t.max_files,qt.max_files,"native.snapshot.max_files"),max_total_bytes:Rf(t.max_total_bytes,qt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Rf(t.max_duration_ms,qt.max_duration_ms,"native.snapshot.max_duration_ms")}}function KC(e){if(e===void 0)return;let t=An(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=An(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:Cn(r),toArtifactRoot:Cn(n),stage:a,...o?{cleanup:o}:{}}}function YC(e,t={}){let i=An(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??cw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=KC(i.pending_root_move);return{artifact_root:Cn(r),language:dw(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:UC(i.snapshot),...s?{pending_root_move:s}:{}}}function XC(e){let t=An(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:uw(t.artifact_layout),language:dw(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function QC(e){let i=An(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Ac(r,`hook.allow_paths[${n}]`)))]}}function ZC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function eA(e,t,i,r,n,a){let o=e.schema!==void 0;if(!(o||e.default_workflow!==void 0||e.workflows!==void 0||!a.allowPartialProject&&e.native!==void 0)||a.allowPartialProject&&!o)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 c=e.workflows??[e.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:l,ambient_resume:n,...t?{hook:t}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function _n(e,t={}){let i=(0,fo.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=ZC(n.ambient_resume),o=n.hook===void 0?void 0:QC(n.hook),s=n.native===void 0?void 0:YC(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:XC(n.classic),l=eA(n,o,s,c,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function fw(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function hw(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.pending_root_move?{pending_root_move:fw(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function xn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function mo(e,t){let i=hw(t),r=_n((0,fo.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...xn(e.hook),allow_paths:[...r.hook.allow_paths]}),r.native){let a=xn(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=xn(a.pending_root_move),c=fw(r.native.pending_root_move),l=xn(s.cleanup),u=xn(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...xn(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as iA}from"crypto";import{promises as jc}from"fs";import Ki from"path";import{constants as Tc,promises as Br}from"fs";var Vt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function xf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function pw(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function vo(e){return{dev:e.dev,ino:e.ino,birthtime:xf(e)}}function Ic(e,t){let i=vo(e),r=vo(t);return Fe(i,r)?W(i,r):W(i,r)&&xf(e)===xf(t)&&pw(e)===pw(t)&&e.size===t.size}async function qr(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Br.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Vt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Vt("too-large",`${r} exceeds ${t} bytes`);let o=await Br.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:vo(a)});let s=process.platform==="win32"?Tc.O_RDONLY:Tc.O_RDONLY|Tc.O_NOFOLLOW|Tc.O_NONBLOCK,c;try{c=await Br.open(e,s)}catch(l){throw l.code==="ELOOP"?new Vt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Br.lstat(e,{bigint:n}),Br.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ic(a,l)||!Ic(a,u))throw new Vt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:vo(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:E}=await c.read(v,0,Math.min(v.length,y),null);if(E===0)break;if(p+=E,p>t)throw new Vt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([c.stat({bigint:n}),Br.lstat(e,{bigint:n}),Br.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||N!==o||!Ic(a,h)||!Ic(a,m))throw new Vt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:vo(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:N}}finally{await c.close()}}function tA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Cf(e,t){let i=Ki.relative(e,t);return i===""||!Ki.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ki.sep}`)}async function mw(e,t){let i=Ki.resolve(e),r=await jc.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return jc.realpath(i)}async function vw(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Ki.join(n,i[a]);let o;try{o=await jc.lstat(n)}catch(u){if(tA(u))return{exists:!1,kind:"missing"};throw u}let s=Ki.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await jc.realpath(n);if(!Cf(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Tn(e,t,i){let r=Ac(t,i.label),n=Ki.resolve(e),a=await mw(n,i.label),o=r.split("/"),s=Ki.resolve(n,...o);if(!Cf(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await vw(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Yi(e,t,i,r){let n=await Tn(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await mw(n.projectRoot,r.label);return qr(n.target,i,{...r,verify:async(o,s)=>{if(!Cf(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await vw(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var go=".comet/config.yaml";function Af(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function rA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function $c(e,t={}){return(await wo(e,t)).document}async function gw(e){try{return(await Yi(e,go,ho,{label:go})).bytes}catch(t){if(rA(t))return null;throw t}}function ww(e){return e?{exists:!0,sha256:iA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Oc(e){return ww(await gw(e))}async function wo(e,t={}){let i=await gw(e);return{document:i?_n(i.toString("utf8"),t):null,identity:ww(i)}}async function _f(e){return(await $c(e))?.config??null}var TL=16*1024;async function Tf(e,t){if(!t)return;let i=await Oc(e);if(!Af(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as yw,promises as Xi}from"fs";import U from"path";import sA from"os";var Hc=".comet/config.yaml",cA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function If(e){try{return await Xi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function lA(e){try{let t=await Xi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function jn(e,t){let i=U.relative(e,t);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}async function In(e){let t=[],i=e;for(;!await If(i);){let n=U.dirname(i);if(n===i)break;t.push(U.basename(i)),i=n}let r=await Xi.realpath(i);return U.resolve(r,...t.reverse())}async function jf(e){try{return(await Xi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $f(e){let t=U.resolve(e);try{(await Xi.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=U.resolve(sA.homedir());for(;;){if(!(t===r&&i!==r)){let o=U.join(t,...Hc.split("/")),s=t===i||await lA(o);if(await If(o)&&s)return t}if(await If(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return i;t=a}}function Dc(e){return Cn(e)}async function uA(e,t){let i=Dc(t),r=U.resolve(e,...i.split("/")),n=await Xi.realpath(e),a=await In(r);if(!jn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Be(e,t){let i=Dc(t),r=await uA(e,i),n=U.join(r,"comet");if(await jf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([In(r),In(n)]);if(!jn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await jf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Xi.realpath(s),In(c)]);if(!jn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Hc.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function bw(e){if(!cA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function rt(e,t){bw(t);let i=U.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Vr(e,t){bw(t);let i=U.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=rt(e,t);if(yw(i))return i;let r=Vr(e,t);return yw(r)?r:i}async function Nw(e){try{let t=await Xi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function No(e,t){let i=rt(e,t),r=Vr(e,t),[n,a]=await Promise.all([Nw(i),Nw(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 Qi(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=U.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=U.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return jn(U.resolve(e),U.resolve(t))}async function T(e,t){let i=U.resolve(e),r=U.resolve(t);if(!jn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await jf(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([In(i),In(r)]);if(!jn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Of=qt;var Mc=_c;async function Ne(e){let t=(await $c(e))?.config??null;return t?.native?t:null}async function $n(e){let t=await Ne(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 Zi(e,t,i={}){let r=await wo(e,{allowPartialProject:!0}),n=mo(r.document?.value??{},t),a=dA.join(e,...Hc.split("/"));await ue(a,po(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Tf(e,r.identity)}})}import{promises as cT}from"fs";import lT from"path";import{AsyncLocalStorage as fA}from"async_hooks";import{randomUUID as Pw}from"crypto";import{promises as Et}from"fs";import Rw from"os";import de from"path";var Sw=16*1024,Hf=".coordinator",hA=5e3,Ew=new fA,Fc=new Map;function pA(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function mA(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 xw(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 Df(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Fe(i,r)?W(i,r):W(i,r)&&e.size===t.size}function Lc(e,t){return Df(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function vA(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Lc(e.identity,t.identity)}async function ri(e){let t,i;try{let r=await qr(e,Sw,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Vt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${Sw} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:mA(JSON.parse(t.toString("utf8")),e),identity:xw(i)}}async function gA(e){return(await ri(e))?.owner??null}function Mf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Rw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=SA(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function wA(e,t){try{await Et.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Et.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Bc(e,t){let i=await ri(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Lc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Et.mkdir(t,{recursive:!0});let r=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${Pw()}.removed`);try{await Et.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ri(r);if(!n||n.owner.id!==e.owner.id||!Df(n.identity,e.identity))throw await wA(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Et.rm(r,{force:!0}),"removed"}function Cw(e){return{id:Pw(),pid:process.pid,hostname:Rw.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Aw(e,t){let i;try{i=await Et.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await gA(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
165
+ `,"utf8"),await i.sync(),xw(await i.stat({bigint:!0}))}finally{await i.close()}}async function yA(e,t){let i=await T(e.runtimeDir,e.locksDir);await Et.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,de.join(i,Hf));await Et.mkdir(r,{recursive:!0});let n=Cw(t),a=de.join(r,`.${n.id}.tmp`),o=de.join(r,`${n.id}.claim`);try{let s=await Aw(a,n);await Et.rename(a,o);let c=await ri(o);if(!c||!Df(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await Et.rm(a,{force:!0})}}async function NA(e){let t=de.dirname(e.file),i=!1,r=de.basename(e.file);for(let n of await Et.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=de.join(t,n.name);if(de.resolve(a)!==de.resolve(e.file))try{let o=await ri(a),s=Mf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bc(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function _w(e){let t=await ri(e.file);if(t){if(t.owner.id!==e.owner.id||!Lc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Bc(t,de.dirname(e.file))}}async function bA(e,t){let i=Date.now()+hA;for(;;){let r=await yA(e,t);if(!await NA(r))return r;if(await _w(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function kA(e){let t=Fc.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Fc.set(e,n),await t,()=>{i(),Fc.get(e)===n&&Fc.delete(e)}}async function qc(e,t,i){let r=de.resolve(e.locksDir),n=Ew.getStore();if(n?.has(r))return i();let a=await kA(r);try{let o=await bA(e,t),s=new Map(n??[]);return s.set(r,o),await Ew.run(s,async()=>{try{return await i()}finally{await _w(o)}})}finally{a()}}async function On(e,t,i){let r=[...new Map(e.map(a=>[de.resolve(a.locksDir),a])).values()].sort((a,o)=>de.resolve(a.locksDir).localeCompare(de.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?qc(o,t,()=>n(a+1)):i()};return n(0)}async function er(e,t,i){return qc(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await Et.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,de.join(r,pA(t))),a=Cw(i),o=await Aw(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function tr(e){await ri(e.file)&&await qc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${de.basename(e.file)}`,async()=>{let t=await ri(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Lc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=de.join(e.locksDir,Hf);await Bc(t,i)})}function SA(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function bo(e){return Mf(await ri(e))}async function Ff(e,t,i){return qc(e,`take over ${de.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(de.resolve(de.dirname(n))!==de.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ri(n),o=Mf(a);if(o.status==="missing")return{status:"missing"};if(i&&!vA(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=de.join(r,Hf);return await Bc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as A_}from"node:fs";import Yf from"node:path";import p_ from"node:path";import Lw from"node:path";import Tw from"node:path";import{createHash as EA}from"crypto";function Wt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function PA(e,t){t.has(e)&&Wt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Wt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Wt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Wt("symbol properties are not supported"),`[${e.map(r=>Lf(r,t)).join(",")}]`}finally{t.delete(e)}}function RA(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Wt("only plain objects are supported"),t.has(e)&&Wt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Wt("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Wt("accessor properties are not supported"),`${JSON.stringify(o)}:${Lf(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Lf(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Wt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?PA(e,t):RA(e,t);case"bigint":case"function":case"symbol":case"undefined":return Wt(`${typeof e} values are not supported`)}return Wt("unsupported value type")}function ko(e){return Lf(e,new Set)}function M(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return EA("sha256").update(`${e}
166
+ ${ko(t)}`).digest("hex")}var xA="comet.native.acceptance.v1",CA=/^acceptance-[a-f0-9]{64}$/u,AA=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),_A=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,TA=/^[a-f0-9]{64}$/u,IA=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function jA(e,t){return e<t?-1:e>t?1:0}var ki=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Eo=Object.freeze({maxCriteria:1024}),Iw="<!-- comet-native:acceptance-evidence:start -->",jw="<!-- comet-native:acceptance-evidence:end -->";function $w(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Ow(e,t){let i=t.toString(36),r=M("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function $A(e){if(!TA.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=IA.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]!==M("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function OA(e,t){let i=$w(e.text,ki.maxTextBytes),r=e.context.slice(0,ki.maxContextItems).map(n=>$w(n,ki.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Dw(e){let t=$A({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(jA),n=r.slice(0,ki.maxFailedCheckIds),a=e.criteria.slice(t,t+ki.maxItems);for(let c of a){let l=[...i,OA(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Ow(e.acceptanceHash,u):null,limits:{...ki}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ki.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Ow(e.acceptanceHash,o):null,limits:{...ki}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ki.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function qf(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 Bf(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Hw(e){return e.includes("-->")||e.includes("--!>")}function*Hn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
167
+ `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
168
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Bf(l,t);else if(i)Hw(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Bf(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Hw(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function HA(e){return[...Hn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function So(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function DA(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Vf(e,t,i,r=[],n="content-hash"){let a=So(i),o=t.replaceAll("\\","/").trim(),s=r.map(So);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${M(xA,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Wf(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function MA(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Hn(e)){n=s+1;let c=o?qf(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function Vc(e,t="brief.md",i=Eo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=MA(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Hn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Hn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Wf(o.map(l=>Vf("brief-example",t,l.join(`
169
+ `),[],r)),"Brief",r)}function Wc(e,t="spec.md",i=Eo.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(Vf("spec-scenario",t,[o.title,...o.body].join(`
170
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of Hn(e)){let u=l?qf(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=So(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Wf(n,"Specification",r)}function zc(e,t="spec.md",i=Eo.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(Vf("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Hn(e)){let f=d?qf(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Bf(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Wf(n,"Specification mandatory requirements",r)}function FA(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||DA(i)||Tw.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=Tw.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!_A.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function LA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!AA.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Mw(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=LA(i,r),a=n.acceptance_id;if(typeof a!="string"||!CA.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return FA(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 Fw(e){let t=HA(e);if(t.some(({line:l,body:u})=>!u&&(l===Iw||l===jw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Iw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===jw?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
171
+ `).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=Mw(o),c=BA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function BA(e){let t=Mw([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var qA=/^A[1-9]\d*$/u;function Bw(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Lw.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Lw.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function VA(e,t){return e.localeCompare(t,"en")}function Jc(e){let t=Bw(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>VA(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=Vc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Bw(a.source,`Native spec source for ${a.capability}`);r.push(...Wc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...zc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=So(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function qw(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!qA.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Vw(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Kc=hn(Lr(),1);import{promises as WA}from"node:fs";var Dn="comet.native.v4",Po="comet.native.local-execution.v4";function zf(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var zA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GA=/^A[1-9][0-9]*$/u,UA=/^[a-f0-9]{64}$/u,KA=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Uc=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function at(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ot(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Te(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Gf(e,t){return e===null?null:Te(e,t)}function YA(e,t){let i=Te(e,t);if(!UA.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Mn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function fe(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function XA(e,t){return e===null?null:fe(e,t,Number.MIN_SAFE_INTEGER)}function _e(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ni(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Yc(e,t){return ni(e,t,(i,r)=>Te(i,`${t}[${r}]`))}function Wr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Fn(e,t){let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Uf(e,t,i=!1){let r=Te(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function zt(e,t){let i=at(e,t);return ot(i,new Set(["text","truncated"]),t),{text:Te(i.text,`${t}.text`,{empty:!0}),truncated:Mn(i.truncated,`${t}.truncated`)}}function QA(e,t){let i=`Native spec_changes[${t}]`,r=at(e,i);ot(r,new Set(["capability","operation","source"]),i);let n=Te(r.capability,`${i}.capability`);if(!JA.test(n))throw new Error(`${i}.capability is invalid`);let a=_e(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Uf(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 ZA(e){let t="Native workspace",i=at(e,t);ot(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=_e(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Gf(i.change_branch,`${t}.change_branch`),a=Gf(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:_e(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function e_(e){let t="Native loop",i=at(e,t);ot(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Yc(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Wr(r,`${t}.previous_unresolved_ids`),{stage:_e(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:fe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:fe(i.iteration,`${t}.iteration`),attempt:fe(i.attempt,`${t}.attempt`),retry_epoch:fe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:fe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:fe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:fe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Gf(i.next_action,`${t}.next_action`)}}function t_(e,t){let i=`Native acceptance[${t}]`,r=at(e,i);ot(r,new Set(["id","source","text","result","reason"]),i);let n=Te(r.id,`${i}.id`);if(!GA.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Uf(r.source,`${i}.source`),text:Te(r.text,`${i}.text`),result:_e(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:zt(r.reason,`${i}.reason`)}}function i_(e,t){let i=`Native builder_handoff.checks[${t}]`,r=at(e,i);return ot(r,new Set(["name","result","note"]),i),{name:zt(r.name,`${i}.name`),result:_e(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:zt(r.note,`${i}.note`)}}function r_(e){let t="Native builder_handoff",i=at(e,t);ot(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=Yc(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Wr(r,`${t}.addressed_acceptance_ids`),{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:Te(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Te(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),summary:zt(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ni(i.checks,`${t}.checks`,i_),checks_truncated:Mn(i.checks_truncated,`${t}.checks_truncated`),known_limits:ni(i.known_limits,`${t}.known_limits`,(n,a)=>zt(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Mn(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Fn(i.submitted_at,`${t}.submitted_at`)}}function n_(e,t){let i=`Native blockers[${t}]`,r=at(e,i);ot(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Yc(r.acceptance_ids,`${i}.acceptance_ids`);return Wr(n,`${i}.acceptance_ids`),{owner:_e(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:zt(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:_e(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function a_(e,t){let i=`Native verification.checks[${t}]`,r=at(e,i);return ot(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Te(r.id,`${i}.id`),name:zt(r.name,`${i}.name`),argv_display:ni(r.argv_display,`${i}.argv_display`,(n,a)=>zt(n,`${i}.argv_display[${a}]`)),argv_truncated:Mn(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Uf(r.cwd_ref,`${i}.cwd_ref`,!0),status:_e(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:XA(r.exit_code,`${i}.exit_code`),duration_ms:fe(r.duration_ms,`${i}.duration_ms`)}}function o_(e){let t="Native verification",i=at(e,t);ot(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ni(i.checks,`${t}.checks`,a_);Wr(r.map(a=>a.id),`${t}.checks IDs`);let n=Te(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Te(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),attempt:fe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":_e(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:_e(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:zt(i.summary,`${t}.summary`),risks:ni(i.risks,`${t}.risks`,(a,o)=>zt(a,`${t}.risks[${o}]`)),risks_truncated:Mn(i.risks_truncated,`${t}.risks_truncated`),completed_at:Fn(i.completed_at,`${t}.completed_at`)}}function Ww(e,t){let i=`Native history[${t}]`,r=at(e,i);ot(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Yc(r.unresolved_ids,`${i}.unresolved_ids`);return Wr(n,`${i}.unresolved_ids`),{goal_cycle:fe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:fe(r.iteration,`${i}.iteration`),attempt:fe(r.attempt,`${i}.attempt`),outcome:_e(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:zt(r.summary,`${i}.summary`),completed_at:Fn(r.completed_at,`${i}.completed_at`)}}function s_(e){let t="Native history_overflow.outcome_counts",i=at(e,t),r=["pass","fail","blocked","execution-error","recovery"];return ot(i,new Set(r),t),{pass:fe(i.pass,`${t}.pass`),fail:fe(i.fail,`${t}.fail`),blocked:fe(i.blocked,`${t}.blocked`),"execution-error":fe(i["execution-error"],`${t}.execution-error`),recovery:fe(i.recovery,`${t}.recovery`)}}function c_(e){let t="Native history_overflow",i=at(e,t);ot(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=fe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Fn(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Fn(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=s_(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 l_(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function u_(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function nt(e){let t=at(e,"Native portable state");if(ot(t,KA,"Native portable state"),t.schema!==Dn)throw new Error(`Native portable state schema must be ${Dn}`);let i=Te(t.name,"Native state name");if(!zA.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ni(t.spec_changes,"Native spec_changes",QA);Wr(r.map(s=>s.capability),"Native spec change capabilities");let n=ni(t.acceptance,"Native acceptance",t_);Wr(n.map(s=>s.id),"Native acceptance IDs");let a=ni(t.history,"Native history",Ww);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Dn,name:i,language:_e(t.language,["en","zh-CN"],"Native state language"),phase:_e(t.phase,["shape","build","verify","archive"],"Native state phase"),status:_e(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:fe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:YA(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:ZA(t.workspace),loop:e_(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:r_(t.builder_handoff),blockers:ni(t.blockers,"Native blockers",n_),verification:t.verification===null?null:o_(t.verification),history:a,history_overflow:c_(t.history_overflow),verification_result:_e(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:_e(t.verification_report,["verification.md"],"Native verification_report"),archived:Mn(t.archived,"Native archived"),created_at:Fn(t.created_at,"Native created_at")};return l_(o),u_(o),o}function Ln(e,t){let i=nt(e),r=Ww(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return nt({...i,history:n,history_overflow:a})}function d_(e,t){let i=(0,Kc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ue(e){let t=await WA.readFile(e,"utf8");return nt(d_(t,"Native portable state"))}async function Xc(e,t,i={}){let r=nt(t);await ue(e,(0,Kc.stringify)(r),i)}var Gc=new Map;async function f_(e,t){let i=Gc.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Gc.set(e,a),await i;try{return await t()}finally{r(),Gc.get(e)===a&&Gc.delete(e)}}async function zr(e){return f_(e.file,async()=>{let t=fe(e.expectedStateVersion,"Native expected state version",1),i=nt(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ue(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Uc(t,r.state_version);return await Xc(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ue(e.file);if(n.state_version!==t)throw new Uc(t,n.state_version)}}),i})}function h_(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ir(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(h_(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var ge="comet.native.v3",we="comet.native.v2",Ke="comet.native.v1",rr="comet.native.transition.v3",Si="comet.native.transition.v2",Jr="comet.native.transition.v1";var Qc="comet.native.portable-migration.v1",m_=new Set(["schema","id","change","fromSchema","status","createdAt"]),v_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,g_=/^[a-z0-9][a-z0-9-]{7,127}$/u,w_=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),y_=new Set([Ke,we,ge]);function N_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function b_(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function k_(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function S_(e){return e.schema===Ke?Gr(e):e.schema===we?ai(e):st(e)}function E_(e){return p_.posix.normalize(e.replaceAll("\\","/"))}function P_(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:E_(t.source)})}function R_(e){return e==="shape"?"shape":"build"}function x_(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function C_(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function zw(e){let t=S_(e.state);qw(e.acceptance);let i=R_(t.phase),r=i==="shape"?0:1,n=b_(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return nt({schema:Dn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:P_(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:x_(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:ir(C_(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:zf(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Kf(e){let t=N_(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!m_.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Qc)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!g_.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!v_.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!y_.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!w_.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Qc,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:k_(t.createdAt,"Native portable migration transaction createdAt")}}function Jw(e){switch(Kf(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Zc="comet.native.archive-transaction.v4",Gw="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",__=new RegExp(`^portable-archive-(${Gw})\\.json$`,"u"),T_=new RegExp(`^portable-migration-(${Gw})\\.json$`,"u"),I_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,j_=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$_=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),O_=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),H_=new Set(["capability","operation","source","content"]),Uw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Kw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yw(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function D_(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Kw(e,i);if(Yw(r,H_,i),typeof r.capability!="string"||!Uw.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 M_(e){let t=Kw(e,"Native portable Archive transaction");if(Yw(t,O_,"Native portable Archive transaction"),t.schema!==Zc)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!I_.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Uw.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!j_.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!$_.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(D_);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Zc,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Ur(e){let t=__.exec(e);if(t)return{kind:"archive",change:t[1]};let i=T_.exec(e);return i?{kind:"migration",change:i[1]}:null}function nr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Ur(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Yf.join(e.transactionsDir,i)}async function Ro(e,t){let i=Ur(t);if(!i)return null;let r=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Yf.join(e.transactionsDir,t);if(i.kind==="archive"){let s=M_(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=Kf(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function el(e,t){let i=nr(e,t);try{return await Ro(e,Yf.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Xw(e){let t;try{t=await A_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Ur(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function Qw(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as xo}from"fs";import Pt from"path";import{TextDecoder as V_}from"util";import{createHash as F_}from"node:crypto";import{constants as tl,promises as z}from"node:fs";import K from"node:path";import{TextDecoder as L_}from"node:util";function qe(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}function Zw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function qn(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ey(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Bn(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ar(e,t){let i=await z.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function or(e,t,i){let r=K.resolve(e),n=K.resolve(t);if(!qe(r,n))throw new Error(`${i} is outside its managed root`);let a=[await ar(r,i)],o=r;for(let s of K.relative(r,n).split(K.sep).filter(Boolean)){await ve(a,i),o=K.join(o,s);let c=await ar(o,i);if(!qe(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ve(a,i),a}async function ve(e,t){for(let i of e){let r=await z.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!qn(i,r)||await z.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function B_(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ie(e){let t=Zw(e.maxBytes),i=K.resolve(e.file),r=await or(e.root,K.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>ar(K.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ve(r,e.label);let a=await z.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=ey(a),s=await z.realpath(i);if(!qe(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>qe(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?tl.O_RDONLY:tl.O_RDONLY|tl.O_NOFOLLOW|tl.O_NONBLOCK,l=await z.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Bn(o,u)||!Bn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await B_(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Bn(o,v)||!Bn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:F_("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function il(e){let t=await ie(e),i;try{i=new L_("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function pt(e){let t=await or(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await z.readdir(e.directory,{withFileTypes:!0});else{let r=Zw(e.maxEntries);i=[];let n=await z.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ve(t,e.label),{entries:i,verify:()=>ve(t,e.label)}}async function Jt(e){let t=await or(e.root,e.directory,e.label);return{verify:()=>ve(t,e.label)}}async function q_(e){let t=K.resolve(e.directory),i=K.resolve(e.quarantine);if(K.dirname(i)!==K.dirname(t)||!qe(K.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await or(e.root,K.dirname(t),e.label),n=await ar(t,e.label);if(!qe(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ve(r,e.label);let a=await z.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!qn(n,a)||await z.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await z.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await z.rename(t,i),await ve(r,e.label);let o=await z.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!qn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await z.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function ty(e){await q_(e)}async function rl(e){let t=K.resolve(e.file),i=await or(e.root,K.dirname(t),e.label),r=await z.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=ey(r),a=await z.realpath(t);if(!qe(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Bn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ve(i,e.label);let[l,u]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Bn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await z.rm(t),await ve(i,e.label)}async function Xf(e){let t=K.resolve(e.directory),i=await or(e.root,K.dirname(t),e.label),r=await ar(t,e.label);if(!qe(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ve(i,e.label);let n=await z.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!qn(r,n)||await z.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await z.rmdir(t),await ve(i,e.label)}async function oi(e){let t=K.resolve(e.root),i=K.resolve(e.directory);if(!qe(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await ar(t,e.label)],n=t;for(let a of K.relative(t,i).split(K.sep).filter(Boolean)){await ve(r,e.label),n=K.join(n,a);try{await z.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await ar(n,e.label);if(!qe(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await ve(r,e.label)}async function Qf(e){let t=K.resolve(e.root),i=K.resolve(e.source),r=K.resolve(e.target);if(i===r||!qe(t,i)||!qe(t,r)||qe(i,r)||qe(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await oi({root:t,directory:K.dirname(r),label:`${e.label} target parent`});let n=await or(t,K.dirname(i),e.label),a=await or(t,K.dirname(r),e.label),o=await ar(i,e.label);if(!qe(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await z.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ve(n,e.label),ve(a,e.label)]);let s=await z.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!qn(o,s)||await z.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await z.rename(i,r),await Promise.all([ve(n,e.label),ve(a,e.label)]);let c=await z.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!qn(o,c)||!qe(n[0].realPath,await z.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await z.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function sr(e){let t=await ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await ow(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await z.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var W_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),z_=new Set(["id","type","source","target","staged","backup"]),J_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),G_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),U_=new Set(["sequence","timestamp","type","operationId"]),ay=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),oy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),K_=256*1024,Y_=1024*1024,sy=16*1024,al=1024,th=64*1024*1024,X_=2e4,cy=new V_("utf-8",{fatal:!0});function Co(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ao(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Wn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Zf(e,t){if(typeof e!="string"||e.length===0||Pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function nl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function iy(e,t){if(Zf(e,t),e.includes("\\")||e!==Pt.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 Q_(e,t){let i=Co(e,`transaction operations[${t}]`);if(Ao(i,z_,`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`);Zf(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Zf(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 sl(e){let t=Co(e,"Native Archive transaction journal");if(Ao(t,J_,"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"||!ay.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(!Wn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(nl(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=Co(s,`Archive transaction operations[${c}]`);if(Ao(l,G_,`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`);iy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&iy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&nl(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(nl(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`);nl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function ih(e){let t=Co(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return sl(t);if(Ao(t,W_,"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"||!ay.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Pt.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(!Wn(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(Q_),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function ly(e,t){let i=Co(e,`Native transaction event at line ${t}`);if(Ao(i,U_,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Wn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!oy.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function Z_(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Wn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Wn(e)}function Vn(e,t){return e.length<t.length&&t.startsWith(e)}function eT(e){let t='","operationId":"';if(Vn(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Vn(i.slice(r),'"}'):!1}function tT(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>sy)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Vn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!Z_(n))return!1;if(r.length<24)return!0;if(!Wn(n))return!1;let a='","type":"',o=r.slice(24);if(Vn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of oy){if(Vn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(eT(l))return!0}else if(Vn(l,'"}'))return!0}return!1}function iT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>sy)throw new Error(`Native transaction event at line ${t} is too large`);return ly(JSON.parse(e),t)}function rT(e){let t=e.split(`
172
+ `),i=t.at(-1)==="";if(i&&t.pop(),t.length>al)throw new Error(`Native transaction event log exceeds ${al} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(iT(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&tT(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function uy(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
167
173
  `)}
168
- `}function HC(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return nt.join(e.transactionsDir,t)}function Ms(e,t){let i=HC(e,t);return{directory:i,journal:nt.join(i,"transaction.json"),events:nt.join(i,"events.jsonl"),staged:nt.join(i,"staged"),backups:nt.join(i,"backups")}}async function $t(e,t){let i=Ms(e,t);return await Promise.all(Object.values(i).map(n=>_(e.nativeRoot,n))),i}function DC(e,t){if(t.length===0||nt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=nt.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!q(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function Pi(e,t){return _(e.nativeRoot,DC(e,t))}async function on(e){try{return await ya.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function od(e,t,i={}){let n=await $t(e,t);try{await ya.lstat(n.events)}catch(r){if(r.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw r}try{let r=await Z({root:e.nativeRoot,file:n.events,maxBytes:AC,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=Pv.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=$C(a),s=xv(o);return{exists:!0,hash:r.hash,size:r.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:r}):r}}async function kv(e,t,i){let n=await od(e,t);if(n.exists!==i.exists||n.hash!==i.hash||n.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function rt(e,t,i,n){let r=await $t(e,t),a=await od(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await Ve(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>kv(e,t,a)}),o;if(a.events.length>=Hs)throw new Error(`Native transaction event log ${t} exceeds ${Hs} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return Av(s,s.sequence),await ya.mkdir(r.directory,{recursive:!0}),await Ve(r.events,xv([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>kv(e,t,a)}),s}async function Tv(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=ad(t);let i=await $t(e,t.id);await ya.mkdir(i.staged,{recursive:!0}),await ya.mkdir(i.backups,{recursive:!0}),await ve(i.journal,t),await rt(e,t.id,"prepared")}async function Ye(e,t,i={}){let n=await $t(e,t),r=await Z({root:e.nativeRoot,file:n.journal,maxBytes:PC,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Pv.decode(r.bytes)),o=ad(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Ai(e,t,i={}){return(await od(e,t,i)).events}async function Ds(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=ad({...t,status:i});return await ve((await $t(e,t.id)).journal,n),n}async function nd(e,t,i){try{return await Z({root:e.nativeRoot,file:t,maxBytes:rd,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function sd(e,t,i,n){let r=await nd(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await nd(e,i,`${n} target`);await Ot({root:e.nativeRoot,directory:nt.dirname(i),label:`${n} target parent`}),await Ci({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:rd,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function Iv(e,t,i){let n=await nd(e,t,i);n&&await Os({root:e.nativeRoot,file:t,maxBytes:rd,expectedHash:n.hash,expectedSize:n.size,label:i})}async function Sv(e,t){if(!t.backup)return;let i=await Pi(e,t.target),n=await Pi(e,t.backup);!await on(i)||await on(n)||await sd(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function FC(e,t){let i=await Pi(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Sv(e,t),await sd(e,await Pi(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Sv(e,t),await Iv(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await Pi(e,t.source),[r,a]=await Promise.all([on(n),on(i)]);if(!r&&a){await(await Ke({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:xC})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!r)throw new Error(`Move source does not exist: ${t.source}`);await td({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function _v(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await Ds(e,t,"applying"):t,r=await Ai(e,t.id),a=new Set(r.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of n.operations)a.has(s.id)||(await rt(e,n.id,"operation-started",s.id),await FC(e,s),await rt(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await Ye(e,n.id),n}async function MC(e,t){let i=await Pi(e,t.target),n=t.backup?await Pi(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await Pi(e,t.source);if(await on(i)){if(await on(r))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await td({root:e.nativeRoot,source:i,target:r,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await on(n)?await sd(e,n,i,`Legacy Native transaction rollback restore ${t.id}`):await Iv(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Ls(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Ai(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Ds(e,t,"rolling-back");await rt(e,n.id,"rollback-started");let r=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...n.operations].reverse())r.has(a.id)&&await MC(e,a);return await rt(e,n.id,"rollback-completed"),n=await Ds(e,n,"rolled-back"),n}async function Gn(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await rt(e,t.id,i),i==="commit"?Ds(e,t,"committed"):t}async function qC(e,t){let i;try{i=await LC.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 Ye(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function VC(e,t){let i=Date.now()+5e3,n=BC.join(e.locksDir,"root-move.lock");for(;;)try{return await bi(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await wa(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 xe(e,t,i,n){let r=await VC(e,t);try{if(await Bn(e.projectRoot),await qC(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await ki(r)}}function jv(e){return Number.isSafeInteger(e)&&e>=1}async function Ov(e){if(!jv(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!jv(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Js}from"crypto";import{spawn as Wv}from"node:child_process";import{promises as ne}from"fs";import B from"path";import{createHash as $v}from"crypto";import{createReadStream as WC}from"fs";async function Nt(e){let t=$v("sha256");for await(let i of WC(e))t.update(i);return t.digest("hex")}function H(e){return $v("sha256").update(e).digest("hex")}var Bs={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},hd=1e3,JC=8*1024*1024,zC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),UC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),KC=new Set(["schema","include","exclude","hash"]),YC=new Set(["provider","gitSelection","physicalSelection","projection"]),XC=new Set(["provider","selection"]),QC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),ZC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),eP=new Set(["schema","status","before","after"]),tP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),iP=new Set(["path","hash","size","type","gitObjectId"]),nP=new Set(["path","size","type","reason"]),rP=new Set(["ref","hash","count"]),aP=new Set(["change-created","legacy-migration","explicit"]),oP=new Set(["file","directory","other"]),sP=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"]),zs=/^[a-f0-9]{64}$/u,Jv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,cP=new Set(["EACCES","EPERM"]),Qn=64*1024,dd=64*1024,lP=6e4,uP=1e3,dP=2,pd={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},fP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function zv(e){let t=e.deadlineMs??lP;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 bt(e){return Math.max(0,e.deadlineAt-Date.now())}function O(e){return bt(e)>=1}function cd(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 Yn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function hP(e){let t={...fP,...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 pP(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&&B.win32.isAbsolute(n)?B.win32.resolve(n):"C:\\Windows",a=B.win32.join(r,"System32","taskkill.exe");if(!B.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=Wv(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),uP),u.unref()}catch{d(!1)}});for(let s=0;s<dP;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 md(e,t,i,n){let r=bt(e);if(r<1)throw cd();let a=e.gitProcess,o=Wv(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=pP(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?cd(m.error):cd()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Gv(e){let t={...pd,...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 qs(e,t,i,n=dd){let{child:r,completion:a}=md(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>=Qn)return;let m=Qn-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 ld(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Sa(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}=md(e,t,i,n.stdin!==void 0),c=[],l=Js("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,b=!1,N=!1,k=S=>{let R=0;for(;R<S.byteLength;){let y=S.indexOf(0,R),w=y<0?S.byteLength:y,g=S.subarray(R,w);if(!v&&g.byteLength>0&&(h.byteLength+g.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,b=!0):h=Buffer.concat([h,g])),y<0)break;m+=1,h.byteLength===0&&!v&&(N=!0);let E=h.byteLength+1;!v&&m<=n.maxRecords&&p+E<=n.maxBytes?(c.push(h),p+=E):b=!0,h=Buffer.alloc(0),v=!1,R=y+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>n.maxBytes&&(b=!0);let R=n.outputChunkBytes;if(R===void 0){k(S);return}for(let y=0;y<S.byteLength;y+=R)k(S.subarray(y,Math.min(S.byteLength,y+R)))}),o.stderr.on("data",S=>{if(d>=Qn)return;let R=Qn-d,y=Buffer.from(S).subarray(0,R);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:R})=>{let y=n.acceptedExitCodes??[0];if(S!==null&&y.includes(S)&&R===null&&!N&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:b,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${R?`: ${R.message}`:N||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function Vs(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 mP(e,t,i){if(i.length===0)return new Set;let n=await Sa(e,t,["check-ignore","--no-index","-z","--stdin"],{...pd,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=Vs(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function vP(e,t,i){let{child:n,completion:r}=md(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>=Qn)return;let d=Qn-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 Xn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||B.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||B.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function gP(e,t){return e.map(i=>{let n=Xn(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function wP(e){let t=B.resolve(e);for(;;){try{return await ne.lstat(B.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=B.dirname(t);if(i===t)return!1;t=i}}async function Uv(e,t,i,n={}){let r=B.resolve(t.projectRoot),a=B.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let p=B.relative(r,B.resolve(f)).replaceAll("\\","/"),m=Xn(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 Sa(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await Sa(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await Sa(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Kv(e){return{stageBefore:ld(e.stagedBefore),combined:ld(e.combined),stageAfter:ld(e.stagedAfter)}}async function Yv(e,t,i=pd,n={}){let r=B.resolve(t.projectRoot);if(!await wP(r))return null;let a;try{a=await qs(e,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw Yn(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 Uv(e,t,i,n)}catch(N){throw Yn(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 S=Vs(k),R=S.indexOf(" ");if(R<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(S.slice(0,R))?.groups;if(!y)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=Xn(S.slice(R+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(Vs),h=gP(m,"combined"),v=new Set(h.filter(N=>!u.has(N))),b=new Set(h.filter((N,k)=>!u.has(N)&&m[k].endsWith("/")));for(let N of f)b.delete(N);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:Kv(o)}}function Ti(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Hv(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function yP(e,t){return!Ti(e.stageBefore,e.stageAfter)||!Ti(e.stageAfter,t.stageBefore)||!Ti(e.combined,t.combined)||!Ti(t.stageBefore,t.stageAfter)}async function Xv(e,t,i,n,r){let a;try{a=await Uv(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw Yn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=Kv(a),c=Hv(o)||Hv(s),l=yP(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:H(`comet.native.git-selection-overflow.v2
169
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var NP=(1n<<256n)-1n;function bP(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Dv(e){let t=B.resolve(e.paths.projectRoot),i=B.resolve(e.paths.nativeRoot),n=B.resolve(e.paths.configFile),r=B.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=()=>bt(e.execution)>=1?!0:(f=!0,m=!0,!1),v=k=>{let S=Buffer.from(`${k.type}\0${k.path}`,"utf8"),R=Js("sha256").update("comet.native.physical-selection-record.v1\0").update(S).digest();for(let y=0;y<s.length;y+=1)s[y]^=R[y];if(c=c+BigInt(`0x${R.toString("hex")}`)&NP,u+=1,d+=S.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(k)},b=async k=>{if(m||!h())return;let S;try{S=await ne.opendir(k)}catch(E){if(!h())return;if(!he(E)&&!fe(E)||k===t&&he(E))throw E;p||=fe(E),f||=he(E),m=!0;return}if(!h()){try{await S.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let R=!1,y;try{for(;!m&&h();){let E;try{E=await S.read()}catch(te){if(!h())break;if(!he(te)&&!fe(te)||k===t&&he(te))throw te;p||=fe(te),f||=he(te),m=!0;break}if(!h()||E===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let j=B.join(k,E.name),Q=SP(t,j);if(j===n||j===r||Ii(i,j)||e.denylist.some(te=>Ii(te,j))||It(Q)!==null)continue;if(!h())break;let J;try{J=await ne.lstat(j)}catch(te){if(!h())break;if(!he(te)&&!fe(te))throw te;if(p=!0,v({path:Q,type:"other"}),o.push({path:Q,size:null,type:"file",reason:he(te)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(Q),m||!h())break;continue}if(!h())break;let K=bP(J);if(K==="directory"){if(PP(e.policy,Q))continue;if(!h())break;let te;try{te=await ne.realpath(j)}catch(Pt){if(!h())break;if(!he(Pt)&&!fe(Pt))throw Pt;if(p=!0,v({path:Q,type:K}),o.push({path:Q,size:null,type:"directory",reason:he(Pt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(Q),m||!h())break;continue}if(!h())break;if(!q(e.physicalProjectRoot,te)||Ii(e.physicalNativeRoot,te))continue;if(v({path:Q,type:K}),await e.hooks?.afterNode?.(Q),!h()||(await b(j),m))break;continue}if(v({path:Q,type:K}),await e.hooks?.afterNode?.(Q),!h()||m)break}}catch(E){R=!0,y=E}let w;try{await S.close()}catch(E){w=E}let g=h();if(R)throw y;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await b(t),h(),f?(a.length=0,u=0,d=0):(a.sort((k,S)=>k.path.localeCompare(S.path,"en")),o.sort((k,S)=>k.path.localeCompare(S.path,"en")));let N=f?H(`comet.native.physical-selection-incomplete.v1
170
- ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):H(`comet.native.physical-selection.v1
171
- ${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 Qv(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 kP(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!Qv(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 Zv(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Fv(e,t){let n=(await qs(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Jv.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return H(`gitlink:${n}`)}async function Mv(e,t){let i=await Fv(e,t),n=await vP(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await Fv(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function ka(e,t){if(It(t)!==null)return!1;let i=B.resolve(e.projectRoot,...t.split("/"));return!Ii(B.resolve(e.nativeRoot),i)}function vd(e,t={}){let i=zt(e),n=t.maxRecordedPaths??20;if(!Number.isSafeInteger(n)||n<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let r=i.omitted.slice(0,n).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:r,sampleTruncated:r.length<i.omittedCount}}function SP(e,t){return B.relative(e,t).split(B.sep).join("/")}function EP(e,t){return t.map(i=>B.resolve(e,...i.split(/[\\/]/u)))}function Ii(e,t){let i=B.resolve(e),n=B.resolve(t);return n===i||q(i,n)}function he(e){return cP.has(e.code??"")}function fe(e){return e.code==="ENOENT"}function gd(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
172
- `)}function RP(e,t){return H(`comet.native.snapshot-policy.v1
173
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function ud(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 CP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Lv(e){let t=Cs(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?CP(r):void 0;if(a&&!a())return!1;let o=ud(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=ud(i,c,a),o===null||o.size===0)return!1}return ud(i,o,a)?.has(i.length)??!1}}function eg(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Cs(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Cs(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=RP(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(Lv),excludeMatchers:i.map(Lv),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 PP(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Bv(e,t,i){if(!e)return!0;let n=()=>O(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 Ea(e,t,i){let n=JSON.stringify(i);return H(`${e}
174
+ `}function nT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Pt.join(e.transactionsDir,t)}function cl(e,t){let i=nT(e,t);return{directory:i,journal:Pt.join(i,"transaction.json"),events:Pt.join(i,"events.jsonl"),staged:Pt.join(i,"staged"),backups:Pt.join(i,"backups")}}async function si(e,t){let i=cl(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function aT(e,t){if(t.length===0||Pt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=Pt.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function cr(e,t){let i=aT(e,t);return T(j(e,i),i)}async function Kr(e){try{return await xo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function rh(e,t,i={}){let r=await si(e,t);try{await xo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ie({root:e.runtimeDir,file:r.events,maxBytes:Y_,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=cy.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=rT(a),s=uy(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function ry(e,t,i){let r=await rh(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Rt(e,t,i,r){let n=await si(e,t),a=await rh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await ue(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>ry(e,t,a)}),o;if(a.events.length>=al)throw new Error(`Native transaction event log ${t} exceeds ${al} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return ly(s,s.sequence),await xo.mkdir(n.directory,{recursive:!0}),await ue(n.events,uy([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>ry(e,t,a)}),s}async function dy(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=ih(t);let i=await si(e,t.id);await xo.mkdir(i.staged,{recursive:!0}),await xo.mkdir(i.backups,{recursive:!0}),await te(i.journal,t,{containedRoot:e.runtimeDir}),await Rt(e,t.id,"prepared")}async function mt(e,t,i={}){let r=await si(e,t),n=await ie({root:e.runtimeDir,file:r.journal,maxBytes:K_,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(cy.decode(n.bytes)),o=ih(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function lr(e,t,i={}){return(await rh(e,t,i)).events}async function ol(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=ih({...t,status:i});return await te((await si(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function eh(e,t,i){try{return await ie({root:j(e,t),file:t,maxBytes:th,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function nh(e,t,i,r){let n=await eh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await eh(e,i,`${r} target`);await oi({root:j(e,i),directory:Pt.dirname(i),label:`${r} target parent`}),await sr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:th,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function fy(e,t,i){let r=await eh(e,t,i);r&&await rl({root:j(e,t),file:t,maxBytes:th,expectedHash:r.hash,expectedSize:r.size,label:i})}async function ny(e,t){if(!t.backup)return;let i=await cr(e,t.target),r=await cr(e,t.backup);!await Kr(i)||await Kr(r)||await nh(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function oT(e,t){let i=await cr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await ny(e,t),await nh(e,await cr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await ny(e,t),await fy(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await cr(e,t.source),[n,a]=await Promise.all([Kr(r),Kr(i)]);if(!n&&a){await(await pt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:X_})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Qf({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function hy(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await ol(e,t,"applying"):t,n=await lr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Rt(e,r.id,"operation-started",s.id),await oT(e,s),await Rt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await mt(e,r.id),r}async function sT(e,t){let i=await cr(e,t.target),r=t.backup?await cr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await cr(e,t.source);if(await Kr(i)){if(await Kr(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Qf({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Kr(r)?await nh(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await fy(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function ll(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await lr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await ol(e,t,"rolling-back");await Rt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await sT(e,a);return await Rt(e,r.id,"rollback-completed"),r=await ol(e,r,"rolled-back"),r}async function zn(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Rt(e,t.id,i),i==="commit"?ol(e,t,"committed"):t}async function uT(e,t,i){let r;try{r=await cT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await mt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Ur(n.name))try{let a=await Ro(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Qw(a))return!0}catch{return!0}return!1}async function dT(e,t){let i=Date.now()+5e3,r=lT.join(e.locksDir,"root-move.lock");for(;;)try{return await er(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bo(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 he(e,t,i,r){let n=await dT(e,t);try{if(await $n(e.projectRoot),await uT(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await tr(n)}}function py(e){return Number.isSafeInteger(e)&&e>=1}async function my(e){if(!py(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!py(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as pl}from"crypto";import{spawn as Py}from"node:child_process";import{promises as oe}from"fs";import q from"path";import{createHash as vy}from"crypto";import{createReadStream as fT}from"fs";async function Gt(e){let t=vy("sha256");for await(let i of fT(e))t.update(i);return t.digest("hex")}function F(e){return vy("sha256").update(e).digest("hex")}var ul={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},uh=1e3,hT=8*1024*1024,pT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mT=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),vT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),gT=new Set(["schema","include","exclude","hash"]),wT=new Set(["provider","gitSelection","physicalSelection","projection"]),yT=new Set(["provider","selection"]),NT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),bT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),kT=new Set(["schema","status","before","after"]),ST=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),ET=new Set(["path","hash","size","type","gitObjectId"]),PT=new Set(["path","size","type","reason"]),RT=new Set(["ref","hash","count"]),xT=new Set(["change-created","legacy-migration","explicit"]),CT=new Set(["file","directory","other"]),AT=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"]),ml=/^[a-f0-9]{64}$/u,Ry=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,_T=new Set(["EACCES","EPERM"]),Yn=64*1024,ch=64*1024,TT=6e4,IT=1e3,jT=2,dh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},$T={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function xy(e){let t=e.deadlineMs??TT;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 Ut(e){return Math.max(0,e.deadlineAt-Date.now())}function L(e){return Ut(e)>=1}function ah(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 Un(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function OT(e){let t={...$T,...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 HT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&q.win32.isAbsolute(r)?q.win32.resolve(r):"C:\\Windows",a=q.win32.join(n,"System32","taskkill.exe");if(!q.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=Py(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),IT),u.unref()}catch{d(!1)}});for(let s=0;s<jT;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function fh(e,t,i,r){let n=Ut(e);if(n<1)throw ah();let a=e.gitProcess,o=Py(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=HT(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?ah(v.error):ah()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Cy(e){let t={...dh,...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 dl(e,t,i,r=ch){let{child:n,completion:a}=fh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=Yn)return;let v=Yn-c,h=Buffer.from(p).subarray(0,v);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 oh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function To(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=fh(e,t,i,r.stdin!==void 0),c=[],l=pl("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,N=!1,y=!1,E=S=>{let k=0;for(;k<S.byteLength;){let b=S.indexOf(0,k),R=b<0?S.byteLength:b,w=S.subarray(k,R);if(!m&&w.byteLength>0&&(h.byteLength+w.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,N=!0):h=Buffer.concat([h,w])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let g=h.byteLength+1;!m&&v<=r.maxRecords&&p+g<=r.maxBytes?(c.push(h),p+=g):N=!0,h=Buffer.alloc(0),m=!1,k=b+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(N=!0);let k=r.outputChunkBytes;if(k===void 0){E(S);return}for(let b=0;b<S.byteLength;b+=k)E(S.subarray(b,Math.min(S.byteLength,b+k)))}),o.stderr.on("data",S=>{if(d>=Yn)return;let k=Yn-d,b=Buffer.from(S).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(S!==null&&b.includes(S)&&k===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:N,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||h.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 fl(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 DT(e,t,i){if(i.length===0)return new Set;let r=await To(e,t,["check-ignore","--no-index","-z","--stdin"],{...dh,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=fl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function MT(e,t,i){let{child:r,completion:n}=fh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Yn)return;let d=Yn-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 Kn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||q.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||q.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function FT(e,t){return e.map(i=>{let r=Kn(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function LT(e){let t=q.resolve(e);for(;;){try{return await oe.lstat(q.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=q.dirname(t);if(i===t)return!1;t=i}}async function Ay(e,t,i,r={}){let n=q.resolve(t.projectRoot),a=q.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=q.relative(n,q.resolve(f)).replaceAll("\\","/"),v=Kn(p);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 To(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await To(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await To(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function _y(e){return{stageBefore:oh(e.stagedBefore),combined:oh(e.combined),stageAfter:oh(e.stagedAfter)}}async function Ty(e,t,i=dh,r={}){let n=q.resolve(t.projectRoot);if(!await LT(n))return null;let a;try{a=await dl(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Un(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Ay(e,t,i,r)}catch(y){throw Un(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let E of y){let S=fl(E),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(S.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Kn(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};p(s.records),p(l.records);let v=c.records.map(fl),h=FT(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),N=new Set(h.filter((y,E)=>!u.has(y)&&v[E].endsWith("/")));for(let y of f)N.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:N,omissions:[],overflow:null,evidence:null,initialFence:_y(o)}}function dr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function gy(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function BT(e,t){return!dr(e.stageBefore,e.stageAfter)||!dr(e.stageAfter,t.stageBefore)||!dr(e.combined,t.combined)||!dr(t.stageBefore,t.stageAfter)}async function Iy(e,t,i,r,n){let a;try{a=await Ay(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Un(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=_y(a),c=gy(o)||gy(s),l=BT(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:F(`comet.native.git-selection-overflow.v2
175
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var qT=(1n<<256n)-1n;function VT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function wy(e){let t=q.resolve(e.paths.projectRoot),i=q.resolve(e.paths.nativeRoot),r=q.resolve(e.paths.runtimeDir),n=q.resolve(e.paths.configFile),a=q.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>Ut(e.execution)>=1?!0:(p=!0,h=!0,!1),N=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),b=pl("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=b[R];if(l=l+BigInt(`0x${b.toString("hex")}`)&qT,d+=1,f+=k.byteLength,Buffer.byteLength(S.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(S)},y=async S=>{if(h||!m())return;let k;try{k=await oe.opendir(S)}catch(P){if(!m())return;if(!ke(P)&&!be(P)||S===t&&ke(P))throw P;v||=be(P),p||=ke(P),h=!0;return}if(!m()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let b=!1,R;try{for(;!h&&m();){let P;try{P=await k.read()}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z)||S===t&&ke(Z))throw Z;v||=be(Z),p||=ke(Z),h=!0;break}if(!m()||P===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let D=q.join(S,P.name),O=zT(t,D);if(D===n||D===a||Kt(i,D)||Kt(r,D)||e.denylist.some(Z=>Kt(Z,D))||ii(O)!==null)continue;if(!m())break;let De;try{De=await oe.lstat(D)}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z))throw Z;if(v=!0,N({path:O,type:"other"}),s.push({path:O,size:null,type:"file",reason:ke(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;let ce=VT(De);if(ce==="directory"){if(KT(e.policy,O))continue;if(!m())break;let Z;try{Z=await oe.realpath(D)}catch(Zt){if(!m())break;if(!ke(Zt)&&!be(Zt))throw Zt;if(v=!0,N({path:O,type:ce}),s.push({path:O,size:null,type:"directory",reason:ke(Zt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;if(!$(e.physicalProjectRoot,Z)||Kt(e.physicalNativeRoot,Z))continue;if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||(await y(D),h))break;continue}if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||h)break}}catch(P){b=!0,R=P}let w;try{await k.close()}catch(P){w=P}let g=m();if(b)throw R;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let E=p?F(`comet.native.physical-selection-incomplete.v1
176
+ ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):F(`comet.native.physical-selection.v1
177
+ ${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:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function jy(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 WT(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!jy(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function $y(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function yy(e,t){let r=(await dl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Ry.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${r}`)}async function Ny(e,t){let i=await yy(e,t),r=await MT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await yy(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function _o(e,t){if(ii(t)!==null)return!1;let i=q.resolve(e.projectRoot,...t.split("/"));return!Kt(q.resolve(e.nativeRoot),i)&&!Kt(q.resolve(e.runtimeDir),i)}function hh(e,t={}){let i=Ei(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function zT(e,t){return q.relative(e,t).split(q.sep).join("/")}function JT(e,t){return t.map(i=>q.resolve(e,...i.split(/[\\/]/u)))}function Kt(e,t){let i=q.resolve(e),r=q.resolve(t);return r===i||$(i,r)}function ke(e){return _T.has(e.code??"")}function be(e){return e.code==="ENOENT"}function ph(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
178
+ `)}function GT(e,t){return F(`comet.native.snapshot-policy.v1
179
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function sh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function UT(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function by(e){let t=Mc(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?UT(n):void 0;if(a&&!a())return!1;let o=sh(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=sh(i,c,a),o===null||o.size===0)return!1}return sh(i,o,a)?.has(i.length)??!1}}function Oy(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Mc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>Mc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=GT(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(by),excludeMatchers:i.map(by),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 KT(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function ky(e,t,i){if(!e)return!0;let r=()=>L(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function Io(e,t,i){let r=JSON.stringify(i);return F(`${e}
174
180
  ${Buffer.byteLength(t)}:${t}
175
- ${Buffer.byteLength(n)}:${n}`)}function fd(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ws(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!fd(i))return e.splice(t,1),i}return null}function xi(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ce(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function AP(e,t,i,n){if(!O(n))return{status:"budget-exhausted"};let r;try{r=await ne.open(e,"r")}catch(c){if(!O(n))return{status:"budget-exhausted"};throw c}if(!O(n))return await r.close(),{status:"budget-exhausted"};let a=Js("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!O(n))return{status:"budget-exhausted"};let c=await r.stat();if(!O(n))return{status:"budget-exhausted"};if(!c.isFile()||!xi(i,c))return{status:"changed"};for(;;){if(!O(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(!O(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!O(n))return{status:"budget-exhausted"};let d=await r.stat();return O(n)?!d.isFile()||!xi(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 at(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ot(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Kn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ht(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function tg(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=B.posix.normalize(e);if(i!==e||B.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function xP(e,t){let i=at(e,`Native snapshot entry ${t}`);ot(i,iP,`Native snapshot entry ${t}`);let n=tg(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!zs.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:Ht(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Jv.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function TP(e,t){let i=at(e,`Native snapshot omission ${t}`);if(ot(i,nP,`Native snapshot omission ${t}`),!oP.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!sP.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:tg(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:Ht(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function IP(e){let t=at(e,"Native snapshot omission overflow");if(ot(t,rP,"Native snapshot omission overflow"),typeof t.hash!="string"||!zs.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:Kn(t.count,"Native snapshot omission overflow count")}}function Un(e,t){let i=at(e,t);if(ot(i,ZC,t),typeof i.hash!="string"||!zs.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=Ht(i.recordCount,`${t} recordCount`),r=Ht(i.storedRecordCount,`${t} storedRecordCount`),a=Ht(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 qv(e){let t=at(e,"Native Git selection evidence");if(ot(t,QC,"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=Un(t.stageBefore,"Native Git selection stageBefore"),n=Un(t.combined,"Native Git selection combined"),r=Un(t.stageAfter,"Native Git selection stageAfter"),a=Un(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Un(t.finalCombined,"Native Git selection finalCombined"),s=Un(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Ti(i,r)||!Ti(r,a)||!Ti(n,o)||!Ti(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 Vv(e,t){let i=at(e,t);if(ot(i,tP,t),typeof i.hash!="string"||!zs.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=Ht(i.visitedNodeCount,`${t} visitedNodeCount`),r=Ht(i.recordCount,`${t} recordCount`),a=Ht(i.storedRecordCount,`${t} storedRecordCount`),o=Ht(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 _P(e){let t=at(e,"Native physical selection evidence");if(ot(t,eP,"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=Vv(t.before,"Native physical selection before"),n=Vv(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Qv(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 zt(e){let t=at(e,"Native content snapshot manifest");if(ot(t,GC,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!aP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=at(t.capture,"Native content snapshot capture");if(ot(y,YC,"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:qv(y.gitSelection),g=y.physicalSelection===void 0?void 0:_P(y.physicalSelection),E=null;if(y.projection!==void 0){let j=at(y.projection,"Native content snapshot projection");if(ot(j,XC,"Native content snapshot projection"),j.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...j.selection===void 0?{}:{selection:qv(j.selection)}}}if(y.provider==="git"){if(g||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(g&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}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=at(t.limits,"Native content snapshot limits");ot(n,UC,"Native content snapshot limits");let r={maxFiles:Kn(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Kn(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Kn(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Kn(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Kn(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=at(t.policy,"Native snapshot policy");if(ot(y,KC,"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=eg({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(xP),s=t.omitted.map(TP),c=Ht(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:IP(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>hd||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 v=s.filter(y=>y.reason==="physical-enumeration-limit"),b=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...v,...b])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||b.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",S=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let R={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(gd(R)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return R}async function Gs(e,t,i={}){let n=zt(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=B.resolve(e.projectRoot),a=zv(i),o=Gv(i.gitSelectionLimits),s=await Yv(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(Zv(s).filter(g=>ka(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>ka(e,g)),d=(g,E)=>E.some(j=>g===j||g.startsWith(`${j}/`)),f=g=>d(g,l),p=g=>d(g,u),m=[...n.entries.map(g=>g.path),...n.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await mP(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!p(g.path)&&ka(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await Xv(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let g of l)b.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,E)=>g.path.localeCompare(E.path,"en"));let N=n.omitted.filter(g=>f(g.path)||p(g.path)||!ka(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(E=>E.startsWith(`${g.path}/`)):!0);for(let g of b)N.some(E=>E.path===g.path&&E.reason===g.reason)||N.push(g);N.sort((g,E)=>g.path.localeCompare(E.path,"en"));let k=n.omissionOverflow?.count??0,S=n.omissionOverflow?.hash??H("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,S=Ea(S,"git-selection",{source:"git-selection",...s.overflow}));let R=g=>{k+=1,S=Ea(S,"omission",g)};for(;N.length>hd;){let g=Ws(N);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");R(g)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:N.length+k===0,entries:v,omitted:N,omittedCount:N.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:k}}:{}}),w=y();for(;gd(w)>n.limits.maxManifestBytes;){let g=Ws(N);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");R(g),w=y()}return zt(w)}function ig(e,t){if(!zC.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=B.join(e.changesDir,t);if(!q(e.changesDir,i))throw new Error("Native change path escaped");return B.join(i,"runtime","baseline-manifest.json")}async function Us(e,t={}){let i={maxFiles:t.limits?.maxFiles??Bs.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Bs.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Bs.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Bs.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=eg(t.policy),r=zv({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Gv(t.gitSelectionLimits),o=hP(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=B.resolve(e.projectRoot),c=await ne.realpath(s),l=B.resolve(e.nativeRoot),u=await ne.realpath(l),d=B.resolve(e.configFile),f=B.join(s,".comet","current-change.json"),p=EP(s,t.denylist??[]),m=[],h=[],v=new Map,b=new Map,N=0,k=0,S=H("comet.native.snapshot-omission-overflow.v1"),R=0,y=!1,w=null,g=x=>{k+=1,S=Ea(S,"omission",x)},E=x=>{if(N+=1,h.length<hd){h.push(x);return}if(fd(x)){let A=Ws(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),h.push(x);return}g(x)},j=x=>{N+=x.count,k+=x.count,S=Ea(S,"git-selection",{source:"git-selection",...x})},Q=x=>{k+=1,S=Ea(S,"manifest-entry",{reason:"manifest-size",entry:x})},J=async(x,A)=>{m.push(x),R+=x.size,v.set(x.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},K=(x,A)=>{let T=m.findIndex(ie=>ie.path===x);if(T<0)return;let[F]=m.splice(T,1);R-=F.size,v.delete(x),E(A)},te=async(x,A,T,F)=>{if(!T.isFile()||T.isSymbolicLink()||!O(r))return;let ie;try{ie=await ne.realpath(x)}catch(P){if(!O(r))return;if(!he(P)&&!fe(P))throw P;E({path:A,size:T.size,type:"file",reason:fe(P)?"changed-during-read":"unreadable"});return}if(!O(r)||!q(c,ie)||Ii(u,ie))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(R+T.size>i.maxTotalBytes){E({path:A,size:T.size,type:"file",reason:"total-size"});return}let W,$,oe;try{if(W=await AP(ie,T.size,T,r),W.status==="budget-exhausted"||!O(r))return;if(W.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!O(r)||(oe=await ne.realpath(x),!O(r)))return;$=await ne.lstat(x)}catch(P){if(!O(r))return;if(!he(P)&&!fe(P))throw P;E({path:A,size:T.size,type:"file",reason:fe(P)?"changed-during-read":"unreadable"});return}if(O(r)){if(W.bytes!==T.size||oe!==ie||!xi(T,W.finalStat)||!xi(W.finalStat,$)||!$.isFile()||$.isSymbolicLink()||$.size!==T.size||$.mtimeMs!==T.mtimeMs||$.ctimeMs!==T.ctimeMs){E({path:A,size:$.isFile()?$.size:null,type:$.isFile()?"file":"other",reason:"changed-during-read"});return}O(r)&&await J({path:A,hash:W.hash,size:$.size,type:"file",...F===void 0?{}:{gitObjectId:F}},{kind:"file",target:x,realTarget:ie,stat:$})}},Pt=async(x,A,T)=>{if(!O(r))return;let F,ie,W;try{if(F=await ne.readlink(x,{encoding:"buffer"}),!O(r)||(W=await ne.lstat(x),!O(r)))return;ie=await ne.readlink(x,{encoding:"buffer"})}catch(P){if(!O(r))return;if(!he(P)&&!fe(P))throw P;E({path:A,size:null,type:"other",reason:fe(P)?"changed-during-read":"unreadable"});return}if(!O(r))return;if(!W.isSymbolicLink()||!xi(T,W)||W.mtimeMs!==T.mtimeMs||W.ctimeMs!==T.ctimeMs||!F.equals(ie)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let $=F.byteLength;if(m.length>=i.maxFiles){E({path:A,size:$,type:"other",reason:"file-count"});return}if($>i.maxFileBytes){E({path:A,size:$,type:"other",reason:"file-size"});return}if(R+$>i.maxTotalBytes){E({path:A,size:$,type:"other",reason:"total-size"});return}let oe=Js("sha256").update("symlink\0").update(F).digest("hex");O(r)&&await J({path:A,hash:oe,size:$,type:"file"},{kind:"symlink",target:x,rawTarget:F,stat:W})},At=async()=>{for(let[x,A]of[...v]){if(!O(r))return;if(A.kind==="file"){let $,oe;try{if($=await ne.realpath(A.target),!O(r))return;oe=await ne.lstat(A.target)}catch(P){if(!O(r))return;if(!he(P)&&!fe(P))throw P;K(x,{path:x,size:null,type:"file",reason:he(P)?"unreadable":"changed-during-read"});continue}if(!O(r))return;($!==A.realTarget||!oe.isFile()||oe.isSymbolicLink()||!xi(A.stat,oe)||oe.size!==A.stat.size||oe.mtimeMs!==A.stat.mtimeMs||oe.ctimeMs!==A.stat.ctimeMs)&&K(x,{path:x,size:oe.isFile()?oe.size:null,type:oe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let $,oe;try{if($=await ne.lstat(A.target),!O(r))return;oe=await ne.readlink(A.target,{encoding:"buffer"})}catch(P){if(!O(r))return;if(!he(P)&&!fe(P))throw P;K(x,{path:x,size:null,type:"other",reason:he(P)?"unreadable":"changed-during-read"});continue}if(!O(r))return;(!$.isSymbolicLink()||!xi(A.stat,$)||$.mtimeMs!==A.stat.mtimeMs||$.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(oe))&&K(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,F;try{if(T=await ne.realpath(A.target),!O(r))return;F=await ne.lstat(A.target)}catch{if(!O(r))return;K(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!O(r))return;if(!(T===A.realTarget&&F.isDirectory()&&!F.isSymbolicLink()&&xi(A.stat,F)&&q(c,T)&&!Ii(u,T))){K(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let W;try{if(!O(r))return;W=await Mv(r,T)}catch($){if(Yn($))throw $;K(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!O(r))return;W.dirty?K(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):W.hash!==A.hash&&K(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of b){if(!O(r))return;try{let T=await ne.lstat(A);if(!O(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(!O(r))return;if(fe(T))continue;if(!he(T))throw T;E({path:x,size:null,type:"file",reason:"unreadable"})}}},Ge=await Yv(r,e,a,t.gitSelectionHooks);if(Ge===null){let x=await Dv({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let F of x.records){if(F.type!=="file"&&F.type!=="symlink"||v.has(F.path))continue;if(bt(r)<1)break;if(!Bv(n,F.path,r))continue;if(bt(r)<1)break;let ie=B.resolve(s,...F.path.split("/")),W;try{W=await ne.lstat(ie)}catch($){if(!O(r))break;if(!he($)&&!fe($))throw $;E({path:F.path,size:null,type:"file",reason:fe($)?"changed-during-read":"unreadable"});continue}if(bt(r)<1)break;if(F.type==="symlink"&&W.isSymbolicLink()){if(await Pt(ie,F.path,W),bt(r)<1)break;continue}if(F.type!=="file"||!W.isFile()||W.isSymbolicLink()){E({path:F.path,size:W.isFile()?W.size:null,type:W.isDirectory()?"directory":W.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(ie,F.path,W),bt(r)<1)break}bt(r)>=1&&await At();let A=await Dv({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=kP(x.evidence,A.evidence);w=T.evidence;for(let F of[...x.omissions,...A.omissions,...T.omissions])h.some(ie=>ie.path===F.path&&ie.reason===F.reason)||E(F)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,T=!1;if(x){let P=zt(x);for(let se of P.entries)se.gitObjectId!==void 0&&A.set(se.path,se);T=A.size>0}let F=new Set,ie=!0;try{let P=await Sa(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)T=!1,ie=!1,A.clear();else for(let se of P.records){let ce=Vs(se),Oe=ce.indexOf(" "),Re=Oe<0?null:Xn(ce.slice(Oe+1));if(Oe!==1||Re===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ce[0]!=="H"&&F.add(Re)}}catch(P){if(Yn(P))throw P;T=!1,ie=!1,A.clear()}let W=new Set;try{let P=await qs(r,s,["ls-files","--modified","-z"],dd);for(let se of P.toString("utf8").split("\0")){let ce=Xn(se);ce!==null&&W.add(ce)}}catch{T=!1,ie=!1,A.clear()}let $=new Set,oe=new Set;for(let P of Zv(Ge)){if(v.has(P)||!ka(e,P))continue;if(bt(r)<1)break;if(!Bv(n,P,r))continue;if(bt(r)<1)break;let se=B.resolve(s,...P.split("/"));if(se===d||se===f||p.some(Ue=>Ii(Ue,se)))continue;if(Ge.gitlinks.has(P)){if(m.length>=i.maxFiles){E({path:P,size:0,type:"file",reason:"file-count"});continue}let Ue,fo;try{[Ue,fo]=await Promise.all([ne.realpath(se),ne.lstat(se)])}catch{E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(fo.isSymbolicLink()||!fo.isDirectory()||!q(c,Ue)||Ii(u,Ue)){E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Rn=await Mv(r,Ue);if(Rn.dirty){E({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await J({path:P,hash:Rn.hash,size:0,type:"file"},{kind:"gitlink",target:se,realTarget:Ue,stat:fo,hash:Rn.hash})}catch(Rn){if(Yn(Rn))throw Rn;E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ce;try{ce=await ne.lstat(se)}catch(Ue){if(fe(Ue)&&Ge.tracked.has(P)){b.set(P,se);continue}if(!he(Ue)&&!fe(Ue))throw Ue;E({path:P,size:null,type:"file",reason:fe(Ue)?"changed-during-read":"unreadable"});continue}if(ce.isSymbolicLink()){await Pt(se,P,ce);continue}if(!ce.isFile()){Ge.nestedRepositories.has(P)||E({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let Oe=Ge.trackedObjectIds.get(P),Re=Oe?A.get(P):void 0;if(T&&Re?.gitObjectId!==void 0&&Re.gitObjectId===Oe&&!F.has(P)&&!W.has(P)){if(m.length>=i.maxFiles){E({path:P,size:Re.size,type:"file",reason:"file-count"});continue}if(Re.size>i.maxFileBytes){E({path:P,size:Re.size,type:"file",reason:"file-size"});continue}if(R+Re.size>i.maxTotalBytes){E({path:P,size:Re.size,type:"file",reason:"total-size"});continue}m.push({...Re}),R+=Re.size,$.add(P);continue}let Yf=ie&&!F.has(P)&&!W.has(P)?Oe:void 0;await te(se,P,ce,Yf),Yf!==void 0&&oe.add(P)}if(await At(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Xv(r,e,a,Ge,t.gitSelectionHooks?.outputChunkBytes),$.size>0||T&&oe.size>0){let P=await qs(r,s,["ls-files","--modified","-z"],dd),se=new Set;for(let ce of P.toString("utf8").split("\0")){let Oe=Xn(ce);Oe!==null&&se.add(Oe)}for(let ce of $){if(!se.has(ce))continue;let Oe=m.find(Re=>Re.path===ce);K(ce,{path:ce,size:Oe?.size??null,type:"file",reason:"changed-during-read"})}for(let ce of oe){if(!se.has(ce))continue;let Oe=m.find(Re=>Re.path===ce);Oe&&delete Oe.gitObjectId}}for(let P of Ge.omissions)E(P);Ge.overflow&&j(Ge.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let WN=Ge===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Ge.evidence?{gitSelection:Ge.evidence}:{}},Kf=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:WN,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/${S}`,hash:S,count:k}}:{}}),Qc=Kf();for(;gd(Qc)>i.maxManifestBytes;){if(h.filter(A=>!fd(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let F=Ws(h);if(F===null)break;g(F)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))N+=1,Q(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Qc=Kf()}return Qc}async function wd(e,t,i={}){let r=(await We(e.projectRoot))?.native.snapshot??Ku;return Us(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 yd(e,t,i){let n=ig(e,t);await _(e.nativeRoot,n),await ve(n,zt(i))}async function Zn(e,t){let i=ig(e,t);await _(e.nativeRoot,i);try{let n=await js({root:e.nativeRoot,file:i,maxBytes:JC,label:"Native baseline snapshot manifest"});return zt(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as YP}from"crypto";import Zs from"path";var Xe=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{createHash as WP}from"node:crypto";import{constants as Ys,promises as He}from"node:fs";import Qe from"node:path";import{TextDecoder as JP}from"node:util";import LP from"path";var FP=po(ra(),1);var ng=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Ca(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 Ra(e,t){let i=Ca(e,t);if(LP.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 BP(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 rg(e){if(!e.run_id)return null;let t=Ca(e,"run_id"),i=Ca(e,"skill"),n=Ca(e,"skill_version"),r=Ca(e,"skill_hash"),a=Ra(e,"pending_ref"),o=Ra(e,"trajectory_ref"),s=Ra(e,"context_ref"),c=Ra(e,"artifacts_ref"),l=Ra(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:ng(e,"current_step"),iteration:u,pending:ng(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:BP(e)}}var RD=256*1024;var qP=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function VP(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=rg(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ks(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=>!qP.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 VP(t)}var Te={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 Aa(e,t){let i=Qe.relative(e,t);return i===""||!Qe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qe.sep}`)}function og(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Pa(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function zP(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function _i(e,t,i){let n=Xe[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Qe.resolve(e),a=Qe.resolve(r,...n.split("/"));if(!Aa(r,a))throw new Error("Native Run path must stay inside its change");return a}async function ag(e){let t=await He.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Nd(e,t){let i=Qe.resolve(e),n=Qe.resolve(t);if(!Aa(i,n))throw new Error("Native Run path is outside its change");let r=[await ag(i)],a=i;for(let o of Qe.relative(i,n).split(Qe.sep).filter(Boolean)){a=Qe.join(a,o);let s;try{s=await ag(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Aa(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function Xs(e){for(let t of e){let i=await He.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!zP(t,i)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function GP(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 sn(e,t,i,n,r){let a=await Nd(e,Qe.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await He.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=og(o),c=await He.realpath(t);if(!Aa(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Ys.O_RDONLY:Ys.O_RDONLY|Ys.O_NOFOLLOW|Ys.O_NONBLOCK,u;try{u=await He.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),He.lstat(t),He.realpath(t)]);if(await Xs(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Pa(s,d)||!Pa(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await GP(u,i,n);await r?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([u.stat(),He.lstat(t),He.realpath(t)]);if(await Xs(a),!v.isFile()||v.isSymbolicLink()||b!==c||!Pa(s,h)||!Pa(s,v))throw new Error(`${n} changed while reading`);let N;try{N=new JP("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()}}async function UP(e,t,i){let n=await Nd(e,Qe.dirname(t));if(!n)return{exists:!1};let r;try{r=await He.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await He.realpath(t);if(!Aa(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Xs(n),{exists:!0,identity:og(r),realPath:a}}async function KP(e,t,i,n){let r=await Nd(e,Qe.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await He.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Pa(i.identity,a)||await He.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await Xs(r)}async function Qs(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await UP(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Ve(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await KP(e.changeDir,e.file,i,e.label)}});let n=await sn(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function sg(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function cg(e){return`${JSON.stringify(e,null,2)}
176
- `}function ji(e){return Ks(e)}async function be(e,t){let i=_i(e,"stateRef"),n=await sn(e,i,Te.runStateBytes,"Native Run state",t);return n?Ks(sg(n.text,"Native Run state")):null}async function cn(e,t,i){let n=Ks(t);await Qs({changeDir:e,file:_i(e,"stateRef"),content:cg(n),maxBytes:Te.runStateBytes,label:"Native Run state",hooks:i})}async function De(e,t,i){let n=_i(e,"trajectoryRef",t),r=await sn(e,n,Te.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>Te.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Te.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 lg(e,t,i){return(await sn(e,_i(e,"trajectoryRef",t),Te.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function ug(e,t,i,n,r){if(!/^[a-f0-9]{64}$/u.test(n))throw new Error("Native Run trajectory expected hash is invalid");let a=_i(e,"trajectoryRef",t),o=await sn(e,a,Te.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(WP("sha256").update(o.text,"utf8").digest("hex")!==n)throw new Error("Native Run trajectory changed before repair");await Qs({changeDir:e,file:a,content:i,maxBytes:Te.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:r})}async function dg(e,t,i,n){let r=_i(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
177
- `;if(Buffer.byteLength(a,"utf8")>Te.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Te.trajectoryEventBytes} bytes`);let o=await sn(e,r,Te.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Te.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Te.trajectoryEvents} events`);await Qs({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Te.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function er(e,t,i){let n=await sn(e,_i(e,"checkpointRef",t),Te.checkpointBytes,"Native Run checkpoint",i);return n?sg(n.text,"Native Run checkpoint"):null}async function fg(e,t,i,n){await Qs({changeDir:e,file:_i(e,"checkpointRef",t),content:cg(i),maxBytes:Te.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var XP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ec=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function bd(e){return YP("sha256").update(e).digest("hex")}function QP(e,t){if(!XP.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Zs.join(e.changesDir,t);if(!q(e.changesDir,i))throw new Error("Native change path escaped");return Zs.join(i,"runtime","trajectory.jsonl")}function ZP(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 eA(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 tA(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=ZP(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(`
178
- `)])}catch(d){if(!eA(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:bd(t),targetHash:bd(l),tailHash:bd(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function hg(e,t){let i=QP(e,t);await _(e.nativeRoot,i);let n=Zs.join(e.changesDir,t),r=await lg(n,Xe.trajectoryRef);return r===null?{status:"clean",file:i}:tA(i,Buffer.from(r))}async function tr(e,t){let i=await hg(e,t);return"inspection"in i?i.inspection:i}async function tc(e,t){let i=await tr(e,t);if(i.status!=="clean")throw new ec(i)}async function pg(e,t,i){return xe(e,`repair trajectory tail for ${t}`,async()=>{let n=await hg(e,t);if(!("inspection"in n)){if(n.status==="clean")return null;throw new ec(n)}try{await ug(Zs.join(e.changesDir,t),Xe.trajectoryRef,n.targetContent,n.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await tr(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return n.inspection})}import{createHash as rA}from"node:crypto";import{promises as nc}from"node:fs";import Oi from"node:path";import{execFileSync as iA}from"child_process";import ic from"path";function kd(e,t){return iA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function nA(e,t){let i=ic.normalize(e),n=ic.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function mg(e){try{let t=ic.resolve(kd(e,["rev-parse","--show-toplevel"])),n=kd(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?ic.resolve(n.slice(9)):t,a=null;try{a=kd(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!nA(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var xa=/^[a-f0-9]{64}$/u,aA=16*1024,Sd=process.platform,oA=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ir(e){return oA.has(e)}function yg(e,t){let i=Oi.relative(e,t);return Oi.isAbsolute(i)||i===".."||i.startsWith(`..${Oi.sep}`)?null:i.replaceAll("\\","/")||"."}function Ng(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function bg(e,t){if(e.length===0||Ng(e)||e.includes("\\")||Oi.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=Oi.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Ed(e,t){return rA("sha256").update(`${e}
179
- ${t}`).digest("hex")}async function vg(e,t){let i=await nc.realpath(t),n=await nc.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Sd==="win32"?Oi.normalize(i).toLowerCase():i;return Ed(e,`${r}
180
- ${n.dev}
181
- ${n.ino}
182
- ${n.birthtimeMs}`)}async function gg(e,t){let i=await nc.realpath(t),n=await nc.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=Sd==="win32"?Oi.normalize(i).toLowerCase():i;return Ed(e,r)}function sA(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 wg(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Ng(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function kg(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(wg(e.changeBranch,"Native workspace change branch"),wg(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 Ta(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"||!xa.test(String(t.projectRootId))||!xa.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");sA(t.capturedAt),bg(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&&!xa.test(String(t.projectRootPathId))||a&&!xa.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!xa.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(kg(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 nr(e,t){return Oi.join(e.changesDir,t,"runtime","workspace.json")}function cA(e,t){let i=yg(e.nativeRoot,nr(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return bg(i,"Native workspace file ref")}async function Sg(e,t){try{let i=await $e({root:e.nativeRoot,ref:cA(e,t),maxBytes:aA});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Rd(e,t){let i=await Sg(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Ta(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function Eg(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=yg(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([vg("comet.native.workspace-project-root.v2",e.paths.projectRoot),vg("comet.native.workspace-native-root.v2",e.paths.nativeRoot),gg("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),gg("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&&kg(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:Ed("comet.native.workspace-session.v2",`${i}
181
+ ${Buffer.byteLength(r)}:${r}`)}function lh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function hl(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!lh(i))return e.splice(t,1),i}return null}function ur(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function YT(e,t,i,r){if(!L(r))return{status:"budget-exhausted"};let n;try{n=await oe.open(e,"r")}catch(c){if(!L(r))return{status:"budget-exhausted"};throw c}if(!L(r))return await n.close(),{status:"budget-exhausted"};let a=pl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!L(r))return{status:"budget-exhausted"};let c=await n.stat();if(!L(r))return{status:"budget-exhausted"};if(!c.isFile()||!ur(i,c))return{status:"changed"};for(;;){if(!L(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!L(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!L(r))return{status:"budget-exhausted"};let d=await n.stat();return L(r)?!d.isFile()||!ur(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ct(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Gn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ci(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hy(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=q.posix.normalize(e);if(i!==e||q.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function XT(e,t){let i=xt(e,`Native snapshot entry ${t}`);Ct(i,ET,`Native snapshot entry ${t}`);let r=Hy(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ci(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Ry.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function QT(e,t){let i=xt(e,`Native snapshot omission ${t}`);if(Ct(i,PT,`Native snapshot omission ${t}`),!CT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!AT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Hy(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ci(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function ZT(e){let t=xt(e,"Native snapshot omission overflow");if(Ct(t,RT,"Native snapshot omission overflow"),typeof t.hash!="string"||!ml.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:Gn(t.count,"Native snapshot omission overflow count")}}function Jn(e,t){let i=xt(e,t);if(Ct(i,bT,t),typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ci(i.recordCount,`${t} recordCount`),n=ci(i.storedRecordCount,`${t} storedRecordCount`),a=ci(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function Sy(e){let t=xt(e,"Native Git selection evidence");if(Ct(t,NT,"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=Jn(t.stageBefore,"Native Git selection stageBefore"),r=Jn(t.combined,"Native Git selection combined"),n=Jn(t.stageAfter,"Native Git selection stageAfter"),a=Jn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Jn(t.finalCombined,"Native Git selection finalCombined"),s=Jn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!dr(i,n)||!dr(n,a)||!dr(r,o)||!dr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Ey(e,t){let i=xt(e,t);if(Ct(i,ST,t),typeof i.hash!="string"||!ml.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ci(i.visitedNodeCount,`${t} visitedNodeCount`),n=ci(i.recordCount,`${t} recordCount`),a=ci(i.storedRecordCount,`${t} storedRecordCount`),o=ci(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function eI(e){let t=xt(e,"Native physical selection evidence");if(Ct(t,kT,"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=Ey(t.before,"Native physical selection before"),r=Ey(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!jy(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Ei(e){let t=xt(e,"Native content snapshot manifest");if(Ct(t,mT,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!xT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=xt(t.capture,"Native content snapshot capture");if(Ct(b,wT,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:Sy(b.gitSelection),w=b.physicalSelection===void 0?void 0:eI(b.physicalSelection),g=null;if(b.projection!==void 0){let P=xt(b.projection,"Native content snapshot projection");if(Ct(P,yT,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...P.selection===void 0?{}:{selection:Sy(P.selection)}}}if(b.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&g)throw new Error("Native physical-tree capture cannot combine selection and projection");i=g?{provider:"physical-tree",projection:g}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=xt(t.limits,"Native content snapshot limits");Ct(r,vT,"Native content snapshot limits");let n={maxFiles:Gn(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Gn(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Gn(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Gn(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Gn(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=xt(t.policy,"Native snapshot policy");if(Ct(b,gT,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Oy({include:b.include,exclude:b.exclude,hash:b.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(XT),s=t.omitted.map(QT),c=ci(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:ZT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,R)=>b+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>uh||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(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.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,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(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 m=s.filter(b=>b.reason==="physical-enumeration-limit"),N=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...N])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,E=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(E!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(N.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(ph(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function vl(e,t,i={}){let r=Ei(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=q.resolve(e.projectRoot),a=xy(i),o=Cy(i.gitSelectionLimits),s=await Ty(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set($y(s).filter(w=>_o(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>_o(e,w)),d=(w,g)=>g.some(P=>w===P||w.startsWith(`${P}/`)),f=w=>d(w,l),p=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)&&!p(w)),h=await DT(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!p(w.path)&&_o(e,w.path)&&(c.has(w.path)||!h.has(w.path)));await Iy(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let w of l)N.push({path:w,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((w,g)=>w.path.localeCompare(g.path,"en"));let y=r.omitted.filter(w=>f(w.path)||p(w.path)||!_o(e,w.path)?!1:h.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of N)y.some(g=>g.path===w.path&&g.reason===w.reason)||y.push(w);y.sort((w,g)=>w.path.localeCompare(g.path,"en"));let E=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,S=Io(S,"git-selection",{source:"git-selection",...s.overflow}));let k=w=>{E+=1,S=Io(S,"omission",w)};for(;y.length>uh;){let w=hl(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(w)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+E===0,entries:m,omitted:y,omittedCount:y.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:E}}:{}}),R=b();for(;ph(R)>r.limits.maxManifestBytes;){let w=hl(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(w),R=b()}return Ei(R)}function Dy(e,t){if(!pT.test(t))throw new Error(`Invalid Native change name: ${t}`);return q.join(H(e,t),"baseline-manifest.json")}async function gl(e,t={}){let i={maxFiles:t.limits?.maxFiles??ul.maxFiles,maxFileBytes:t.limits?.maxFileBytes??ul.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??ul.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??ul.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Oy(t.policy),n=xy({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Cy(t.gitSelectionLimits),o=OT(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=q.resolve(e.projectRoot),c=await oe.realpath(s),l=q.resolve(e.nativeRoot),u=await oe.realpath(l),d=q.resolve(e.runtimeDir),f=q.resolve(e.configFile),p=q.join(s,".comet","current-change.json"),v=JT(s,t.denylist??[]),h=[],m=[],N=new Map,y=new Map,E=0,S=0,k=F("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,w=null,g=_=>{S+=1,k=Io(k,"omission",_)},P=_=>{if(E+=1,m.length<uh){m.push(_);return}if(lh(_)){let A=hl(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),m.push(_);return}g(_)},D=_=>{E+=_.count,S+=_.count,k=Io(k,"git-selection",{source:"git-selection",..._})},O=_=>{S+=1,k=Io(k,"manifest-entry",{reason:"manifest-size",entry:_})},De=async(_,A)=>{h.push(_),b+=_.size,N.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ce=(_,A)=>{let I=h.findIndex(ae=>ae.path===_);if(I<0)return;let[V]=h.splice(I,1);b-=V.size,N.delete(_),P(A)},Z=async(_,A,I,V)=>{if(!I.isFile()||I.isSymbolicLink()||!L(n))return;let ae;try{ae=await oe.realpath(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n)||!$(c,ae)||Kt(u,ae))return;if(h.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let G,B,pe;try{if(G=await YT(ae,I.size,I,n),G.status==="budget-exhausted"||!L(n))return;if(G.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!L(n)||(pe=await oe.realpath(_),!L(n)))return;B=await oe.lstat(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(L(n)){if(G.bytes!==I.size||pe!==ae||!ur(I,G.finalStat)||!ur(G.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}L(n)&&await De({path:A,hash:G.hash,size:B.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:ae,stat:B})}},Zt=async(_,A,I)=>{if(!L(n))return;let V,ae,G;try{if(V=await oe.readlink(_,{encoding:"buffer"}),!L(n)||(G=await oe.lstat(_),!L(n)))return;ae=await oe.readlink(_,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:null,type:"other",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n))return;if(!G.isSymbolicLink()||!ur(I,G)||G.mtimeMs!==I.mtimeMs||G.ctimeMs!==I.ctimeMs||!V.equals(ae)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=V.byteLength;if(h.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(b+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let pe=pl("sha256").update("symlink\0").update(V).digest("hex");L(n)&&await De({path:A,hash:pe,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:G})},Dt=async()=>{for(let[_,A]of[...N]){if(!L(n))return;if(A.kind==="file"){let B,pe;try{if(B=await oe.realpath(A.target),!L(n))return;pe=await oe.lstat(A.target)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"file",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(B!==A.realTarget||!pe.isFile()||pe.isSymbolicLink()||!ur(A.stat,pe)||pe.size!==A.stat.size||pe.mtimeMs!==A.stat.mtimeMs||pe.ctimeMs!==A.stat.ctimeMs)&&ce(_,{path:_,size:pe.isFile()?pe.size:null,type:pe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,pe;try{if(B=await oe.lstat(A.target),!L(n))return;pe=await oe.readlink(A.target,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"other",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(!B.isSymbolicLink()||!ur(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(pe))&&ce(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,V;try{if(I=await oe.realpath(A.target),!L(n))return;V=await oe.lstat(A.target)}catch{if(!L(n))return;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;if(!(I===A.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&ur(A.stat,V)&&$(c,I)&&!Kt(u,I))){ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let G;try{if(!L(n))return;G=await Ny(n,I)}catch(B){if(Un(B))throw B;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;G.dirty?ce(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):G.hash!==A.hash&&ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!L(n))return;try{let I=await oe.lstat(A);if(!L(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!L(n))return;if(be(I))continue;if(!ke(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},ft=await Ty(n,e,a,t.gitSelectionHooks);if(ft===null){let _=await wy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||N.has(V.path))continue;if(Ut(n)<1)break;if(!ky(r,V.path,n))continue;if(Ut(n)<1)break;let ae=q.resolve(s,...V.path.split("/")),G;try{G=await oe.lstat(ae)}catch(B){if(!L(n))break;if(!ke(B)&&!be(B))throw B;P({path:V.path,size:null,type:"file",reason:be(B)?"changed-during-read":"unreadable"});continue}if(Ut(n)<1)break;if(V.type==="symlink"&&G.isSymbolicLink()){if(await Zt(ae,V.path,G),Ut(n)<1)break;continue}if(V.type!=="file"||!G.isFile()||G.isSymbolicLink()){P({path:V.path,size:G.isFile()?G.size:null,type:G.isDirectory()?"directory":G.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Z(ae,V.path,G),Ut(n)<1)break}Ut(n)>=1&&await Dt();let A=await wy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=WT(_.evidence,A.evidence);w=I.evidence;for(let V of[..._.omissions,...A.omissions,...I.omissions])m.some(ae=>ae.path===V.path&&ae.reason===V.reason)||P(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let C=Ei(_);for(let le of C.entries)le.gitObjectId!==void 0&&A.set(le.path,le);I=A.size>0}let V=new Set,ae=!0;try{let C=await To(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(C.overflow)I=!1,ae=!1,A.clear();else for(let le of C.records){let me=fl(le),Ge=me.indexOf(" "),Me=Ge<0?null:Kn(me.slice(Ge+1));if(Ge!==1||Me===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");me[0]!=="H"&&V.add(Me)}}catch(C){if(Un(C))throw C;I=!1,ae=!1,A.clear()}let G=new Set;try{let C=await dl(n,s,["ls-files","--modified","-z"],ch);for(let le of C.toString("utf8").split("\0")){let me=Kn(le);me!==null&&G.add(me)}}catch{I=!1,ae=!1,A.clear()}let B=new Set,pe=new Set;for(let C of $y(ft)){if(N.has(C)||!_o(e,C))continue;if(Ut(n)<1)break;if(!ky(r,C,n))continue;if(Ut(n)<1)break;let le=q.resolve(s,...C.split("/"));if(le===f||le===p||Kt(d,le)||v.some(ht=>Kt(ht,le)))continue;if(ft.gitlinks.has(C)){if(h.length>=i.maxFiles){P({path:C,size:0,type:"file",reason:"file-count"});continue}let ht,Es;try{[ht,Es]=await Promise.all([oe.realpath(le),oe.lstat(le)])}catch{P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Es.isSymbolicLink()||!Es.isDirectory()||!$(c,ht)||Kt(u,ht)){P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let fn=await Ny(n,ht);if(fn.dirty){P({path:C,size:null,type:"directory",reason:"gitlink-dirty"});continue}await De({path:C,hash:fn.hash,size:0,type:"file"},{kind:"gitlink",target:le,realTarget:ht,stat:Es,hash:fn.hash})}catch(fn){if(Un(fn))throw fn;P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let me;try{me=await oe.lstat(le)}catch(ht){if(be(ht)&&ft.tracked.has(C)){y.set(C,le);continue}if(!ke(ht)&&!be(ht))throw ht;P({path:C,size:null,type:"file",reason:be(ht)?"changed-during-read":"unreadable"});continue}if(me.isSymbolicLink()){await Zt(le,C,me);continue}if(!me.isFile()){ft.nestedRepositories.has(C)||P({path:C,size:null,type:"other",reason:"changed-during-read"});continue}let Ge=ft.trackedObjectIds.get(C),Me=Ge?A.get(C):void 0;if(I&&Me?.gitObjectId!==void 0&&Me.gitObjectId===Ge&&!V.has(C)&&!G.has(C)){if(h.length>=i.maxFiles){P({path:C,size:Me.size,type:"file",reason:"file-count"});continue}if(Me.size>i.maxFileBytes){P({path:C,size:Me.size,type:"file",reason:"file-size"});continue}if(b+Me.size>i.maxTotalBytes){P({path:C,size:Me.size,type:"file",reason:"total-size"});continue}h.push({...Me}),b+=Me.size,B.add(C);continue}let om=ae&&!V.has(C)&&!G.has(C)?Ge:void 0;await Z(le,C,me,om),om!==void 0&&pe.add(C)}if(await Dt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Iy(n,e,a,ft,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&pe.size>0){let C=await dl(n,s,["ls-files","--modified","-z"],ch),le=new Set;for(let me of C.toString("utf8").split("\0")){let Ge=Kn(me);Ge!==null&&le.add(Ge)}for(let me of B){if(!le.has(me))continue;let Ge=h.find(Me=>Me.path===me);ce(me,{path:me,size:Ge?.size??null,type:"file",reason:"changed-during-read"})}for(let me of pe){if(!le.has(me))continue;let Ge=h.find(Me=>Me.path===me);Ge&&delete Ge.gitObjectId}}for(let C of ft.omissions)P(C);ft.overflow&&D(ft.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let zS=ft===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...ft.evidence?{gitSelection:ft.evidence}:{}},am=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:zS,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:E,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),Hu=am();for(;ph(Hu)>i.maxManifestBytes;){if(m.filter(A=>!lh(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let V=hl(m);if(V===null)break;g(V)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))E+=1,O(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Hu=am()}return Hu}async function mh(e,t,i={}){let n=(await Ne(e.projectRoot))?.native.snapshot??Of;return gl(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function vh(e,t,i){let r=Dy(e,t);await T(j(e,r),r),await te(r,Ei(i))}async function Xn(e,t){let i=Dy(e,t),r=j(e,i);await T(r,i);try{let n=await il({root:r,file:i,maxBytes:hT,label:"Native baseline snapshot manifest"});return Ei(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as NI}from"crypto";import bI from"path";var vt=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{createHash as pI}from"node:crypto";import{constants as yl,promises as Ye}from"node:fs";import gt from"node:path";import{TextDecoder as mI}from"node:util";import uI from"path";var oI=hn(Lr(),1);var j1=4*1024*1024;var sI=null;function cI(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function My(e,t){return(...i)=>{let r=sI;if(r===null)return t(...i);let n=cI(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var M1=My("hookWritePolicy",async e=>(await _f(e))?.hook??{allow_paths:[]});var Fy=(e,t)=>{let i=e[t];return i==null?null:String(i)};function $o(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 jo(e,t){let i=$o(e,t);if(uI.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 dI(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Ly(e){if(!e.run_id)return null;let t=$o(e,"run_id"),i=$o(e,"skill"),r=$o(e,"skill_version"),n=$o(e,"skill_hash"),a=jo(e,"pending_ref"),o=jo(e,"trajectory_ref"),s=jo(e,"context_ref"),c=jo(e,"artifacts_ref"),l=jo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Fy(e,"current_step"),iteration:u,pending:Fy(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:dI(e)}}var Iq=256*1024;var fI=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function hI(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=Ly(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function wl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!fI.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return hI(t)}var Ve={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 Ho(e,t){let i=gt.relative(e,t);return i===""||!gt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gt.sep}`)}function qy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Oo(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function vI(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function fr(e,t,i){let r=vt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=gt.resolve(e),a=gt.resolve(n,...r.slice(8).split("/"));if(!Ho(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function By(e){let t=await Ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function gh(e,t){let i=gt.resolve(e),r=gt.resolve(t);if(!Ho(i,r))throw new Error("Native Run path is outside its change");let n=[await By(i)],a=i;for(let o of gt.relative(i,r).split(gt.sep).filter(Boolean)){a=gt.join(a,o);let s;try{s=await By(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ho(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Nl(e){for(let t of e){let i=await Ye.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!vI(t,i)||await Ye.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function gI(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Yr(e,t,i,r,n){let a=await gh(e,gt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Ye.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=qy(o),c=await Ye.realpath(t);if(!Ho(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?yl.O_RDONLY:yl.O_RDONLY|yl.O_NOFOLLOW|yl.O_NONBLOCK,u;try{u=await Ye.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Nl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Oo(s,d)||!Oo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await gI(u,i,r);await n?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([u.stat(),Ye.lstat(t),Ye.realpath(t)]);if(await Nl(a),!m.isFile()||m.isSymbolicLink()||N!==c||!Oo(s,h)||!Oo(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new mI("utf-8",{fatal:!0}).decode(v)}catch(E){throw new Error(`${r} is not valid UTF-8`,{cause:E})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function wI(e,t,i){let r=await gh(e,gt.dirname(t));if(!r)return{exists:!1};let n;try{n=await Ye.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Ye.realpath(t);if(!Ho(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Nl(r),{exists:!0,identity:qy(n),realPath:a}}async function yI(e,t,i,r){let n=await gh(e,gt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await Ye.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Oo(i.identity,a)||await Ye.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Nl(n)}async function bl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await wI(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ue(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await yI(e.changeDir,e.file,i,e.label)}});let r=await Yr(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Vy(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Wy(e){return`${JSON.stringify(e,null,2)}
182
+ `}function hr(e){return wl(e)}async function Ie(e,t){let i=fr(e,"stateRef"),r=await Yr(e,i,Ve.runStateBytes,"Native Run state",t);return r?wl(Vy(r.text,"Native Run state")):null}async function Xr(e,t,i){let r=wl(t);await bl({changeDir:e,file:fr(e,"stateRef"),content:Wy(r),maxBytes:Ve.runStateBytes,label:"Native Run state",hooks:i})}async function Xe(e,t,i){let r=fr(e,"trajectoryRef",t),n=await Yr(e,r,Ve.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>Ve.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ve.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 zy(e,t,i){return(await Yr(e,fr(e,"trajectoryRef",t),Ve.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Jy(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=fr(e,"trajectoryRef",t),o=await Yr(e,a,Ve.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(pI("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await bl({changeDir:e,file:a,content:i,maxBytes:Ve.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function Gy(e,t,i,r){let n=fr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
183
+ `;if(Buffer.byteLength(a,"utf8")>Ve.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ve.trajectoryEventBytes} bytes`);let o=await Yr(e,n,Ve.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ve.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ve.trajectoryEvents} events`);await bl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Ve.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Qn(e,t,i){let r=await Yr(e,fr(e,"checkpointRef",t),Ve.checkpointBytes,"Native Run checkpoint",i);return r?Vy(r.text,"Native Run checkpoint"):null}async function Uy(e,t,i,r){await bl({changeDir:e,file:fr(e,"checkpointRef",t),content:Wy(i),maxBytes:Ve.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var kI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kl=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function wh(e){return NI("sha256").update(e).digest("hex")}function SI(e,t){if(!kI.test(t))throw new Error(`Invalid Native change name: ${t}`);return bI.join(H(e,t),"trajectory.jsonl")}function EI(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function PI(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 RI(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=EI(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
184
+ `)])}catch(d){if(!PI(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:wh(t),targetHash:wh(l),tailHash:wh(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Ky(e,t){let i=SI(e,t);await T(j(e,i),i);let r=H(e,t),n=await zy(r,vt.trajectoryRef);return n===null?{status:"clean",file:i}:RI(i,Buffer.from(n))}async function Zn(e,t){let i=await Ky(e,t);return"inspection"in i?i.inspection:i}async function Sl(e,t){let i=await Zn(e,t);if(i.status!=="clean")throw new kl(i)}async function Yy(e,t,i){return he(e,`repair trajectory tail for ${t}`,async()=>{let r=await Ky(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new kl(r)}try{await Jy(H(e,t),vt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await Zn(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as CI}from"node:crypto";import{promises as El}from"node:fs";import Pi from"node:path";var Do=/^[a-f0-9]{64}$/u,Xy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,AI=16*1024,Nh=process.platform,_I=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ea(e){return _I.has(e)}function eN(e,t){let i=Pi.relative(e,t);return Pi.isAbsolute(i)||i===".."||i.startsWith(`..${Pi.sep}`)?null:i.replaceAll("\\","/")||"."}function tN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function iN(e,t){if(e.length===0||tN(e)||e.includes("\\")||Pi.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=Pi.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function bh(e,t){return CI("sha256").update(`${e}
185
+ ${t}`).digest("hex")}async function Qy(e,t){let i=await El.realpath(t),r=await El.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nh==="win32"?Pi.normalize(i).toLowerCase():i;return bh(e,`${n}
186
+ ${r.dev}
187
+ ${r.ino}
188
+ ${r.birthtimeMs}`)}async function Zy(e,t){let i=await El.realpath(t),r=await El.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nh==="win32"?Pi.normalize(i).toLowerCase():i;return bh(e,n)}function TI(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 yh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||tN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function rN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(yh(e.changeBranch,"Native workspace change branch"),yh(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 II(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Xy.test(t.baseCommit)||typeof t.targetCommit!="string"||!Xy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");yh(t.targetBranch,"Native workspace Git target branch")}function Mo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Do.test(String(t.projectRootId))||!Do.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");TI(t.capturedAt),iN(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Do.test(String(t.projectRootPathId))||a&&!Do.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Do.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&II(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(rN(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 ta(e,t){return Pi.join(H(e,t),"workspace.json")}function jI(e,t){let i=ta(e,t),r=j(e,i),n=eN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:iN(n,"Native workspace file ref")}}async function nN(e,t){try{let i=jI(e,t),r=await Q({root:i.root,ref:i.ref,maxBytes:AI});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function aN(e,t){let i=Ae(e.projectRoot),r={projectRoot:Pi.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await wt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await ia({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function kh(e,t){let i=await nN(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Mo(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function oN(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=eN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ae(e.paths.projectRoot),r=i.isGitWorktree?Nf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Nf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Qy("comet.native.workspace-project-root.v2",e.paths.projectRoot),Qy("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Zy("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Zy("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&rN(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:bh("comet.native.workspace-session.v2",`${s}
189
+ ${c}
190
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Mo(p),p}async function Pl(e){let t=await oN(e),i=ta(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await te(i,t,{containedRoot:r}),t}async function wt(e,t){let i=await nN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Mo(i),i)}async function sN(e){return await kh(e.paths,e.name)?Pl(e):null}async function Fo(e){Mo(e.identity);let t=await oN({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Nh==="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 ia(e){if(Mo(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 Fo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ae(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 cN(e,t){let i=await wt(e,t);if(i===null)return null;let r=await ia({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var uN=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],$I=new Set(uN),dN=new Set([...uN,"minimum_runtime_version","revision"]),OI=new Set([...dN,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),HI=new Set(["capability","operation","source","base_hash"]),DI=new Set(["shape","build","verify","archive"]),MI=new Set(["implicit","confirmed"]),FI=new Set(["pending","pass","fail"]),Re="comet-state.yaml",Eh=/^[a-f0-9]{64}$/u,fN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Lo=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"},Zr=class extends Error{constructor(i,r){super(i!==ge||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"},Bo=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"},qo=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"},ra=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"},PV=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
191
+ `);function Wo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hN(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function xl(e){if(!fN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function BI(e){if(!fN.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function pN(e,t){if(e.length===0||li.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function qI(e,t){let i=Wo(e,`spec_changes[${t}]`);if(hN(i,HI,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(BI(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"&&pN(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"||!Eh.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"||!Eh.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 VI(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 Ph(e,t){if(hN(e,t,Re),typeof e.name!="string")throw new Error("Native change name is required");if(xl(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"||!DI.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&&!MI.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(qI),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!FI.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"&&pN(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!VI(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 Gr(e){let t=Wo(e,Re);if(t.schema!==Ke)throw new Error(`Expected ${Ke}`);return{schema:Ke,...Ph(t,$I)}}function Vo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Sh(e,t,i){if(e===null)return null;let r=typeof e=="string"?LI.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function WI(e){if(e==null)return null;if(typeof e!="string"||!Eh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function zI(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 ai(e){let t=Wo(e,Re);if(t.schema!==we)throw new Error(`Expected ${we}`);if(Vo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${we} minimum_runtime_version must be 2`);return{schema:we,minimum_runtime_version:2,revision:Vo(t.revision,"Native v2 revision"),...Ph(t,dN)}}function st(e){let t=Wo(e,Re);if(t.schema!==ge){if(t.schema===Ke||t.schema===we){let o=t.schema===Ke?Gr(t):ai(t);throw new Lo(o.name,o.schema)}throw new Zr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Vo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Zr(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Vo(t.revision,"Native revision"),n=Ph(t,OI),a=WI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ge,minimum_runtime_version:3,revision:r,verification_protocol:zI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Sh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Sh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Sh(t.partial_allowance,"Native partial_allowance","allowances")}}function mN(e){let t=Wo(e,Re);if(t.schema===Ke){let n=Gr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema===we){let n=ai(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema!==ge){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Zr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Vo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Zr(t.schema,i).message};let r=st(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Qr(e){let t=st(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Cl(e){let t=ai(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function re(e,t){xl(t);let i=li.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function na(e,t){let i=H(e,t),r=li.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await lN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function aa(e,t){let i=H(e,t),r=li.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await lN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var JI=256*1024;async function Al(e,t=li.dirname(e)){let i=li.relative(t,e).split(li.sep).join("/"),r=await Q({root:t,ref:i,maxBytes:JI}),n=(0,Rl.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function ui(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=mN(await Al(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await na(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await GI(e,r.state),r)}async function _l(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=mN(await Al(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function GI(e,t){if(await Xn(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function $e(e,t){let i=await ui(e,t);if(i.status==="migration-required")throw new Lo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Zr(i.schema,i.minimumRuntimeVersion);return await cN(e,t),i.state}async function vN(e,t,i){let r={...t,schema:ge,minimum_runtime_version:3,revision:i+1},n=await my({expectedRevision:i,next:r,read:async()=>{let a=st(await Al(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ue(e,(0,Rl.stringify)(Qr(a))),equals:(a,o)=>JSON.stringify(Qr(a))===JSON.stringify(Qr(o)),conflict:a=>new Bo(t.name,i,a)});return Object.assign(t,n),n}async function Tl(e,t,i,r){if(await $n(e.projectRoot),await na(e,t.name))throw new Lo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await aa(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await $e(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Sl(e,t.name);let a=li.join(re(e,t.name),Re);return await T(e.nativeRoot,a),vN(a,t,i)}async function gN(e,t){return vN(e,t,t.revision)}async function wN(e){return st(await Al(e))}var NN=["Outcome","Scope","Non-goals","Acceptance examples"],UI=[...NN,"Constraints and invariants","Decisions","Open questions","Verification expectations"],KI=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],bN={maxFileBytes:lo};function kN(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
192
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function YI(e,t){let i=yN.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await Rh.realpath(e),n=await Rh.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Rh.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function zo(e){return{valid:e.length===0,findings:e}}async function xh(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:bN.maxFileBytes})).text}catch(o){return zo([{code:"brief-missing",message:o.message,path:t}])}let n=kN(r);for(let o of UI)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of NN)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),zo(i)}async function Ch(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:bN.maxFileBytes})).text}catch(a){return zo([{code:"verification-missing",message:a.message,path:t}])}let n=kN(r);for(let a of KI)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return zo(i)}function Il(e,t){return yN.join(e.specsDir,t,"spec.md")}async function SN(e,t){let i=[],r=re(e,t.name);for(let n of t.spec_changes){let a=Il(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await Gt(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 YI(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return zo(i)}import{promises as i0}from"node:fs";import ok from"node:path";import EN from"node:path";var XI="comet.native.archive-preflight.v1",QI="comet.native.archive-preflight.v1",ZI="comet.native.archive-operation.v1",ej=/^[a-f0-9]{64}$/u,PN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function jl(e,t){return e<t?-1:e>t?1:0}function ij(e,t){if(typeof e!="string"||!ej.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ri(e,t){return e===null?null:ij(e,t)}function rj(e,t){let i=EN.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||EN.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 nj(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function aj(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function oj(e,t){if(!PN.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=Ri(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Ri(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Ri(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function sj(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:Ri(e.contractHash,"Native archive contract hash"),acceptanceHash:Ri(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ri(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ri(e.reportHash,"Native archive report hash"),envelopeHash:Ri(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ri(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 cj(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!tj.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(jl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function lj(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(jl)}function RN(e){if(!PN.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(oj).sort((l,u)=>jl(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:M(ZI,l)})),r=sj(e.evidence),n=aj(e.workspace),a=[...new Set([...cj(e.findingCodes??[]),...lj({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(jl),o=nj(e.revision),s=rj(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:XI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:M(QI,c)}}import{createHash as uj}from"node:crypto";import xN from"node:path";var dj="comet.native.conflict-radar.v1",ct=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}),fj="comet.native.conflict-radar.v1",hj="comet.native.conflict-radar-signals.v1",pj=/^[a-f0-9]{64}$/u,_N=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mj=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),vj=new Set(["capability","operation","baseHash"]),gj=new Set(["path","kind"]);function oa(e,t){return e<t?-1:e>t?1:0}function Ah(e){return Buffer.byteLength(e,"utf8")}function _h(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Th(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(Ah(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function wj(e,t){let i=Th(e,t,ct.maxArtifactPathBytes),r=xN.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)||xN.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function TN(e,t){if(typeof e!="string"||!pj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yj(e,t){let i=_h(e,vj,t),r=Th(i.capability,`${t} capability`,ct.maxCapabilityBytes);if(!_N.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:TN(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function Nj(e,t){let i=_h(e,gj,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:wj(i.path,`${t} path`),kind:i.kind}}function bj(e,t){let i=_h(e,mj,`Conflict radar change ${t}`),r=Th(i.name,`Conflict radar change ${t} name`,ct.maxNameBytes);if(!_N.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ct.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>ct.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>yj(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>oa(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)=>Nj(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>oa(c.path,l.path)||oa(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:TN(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function kj(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ct.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(bj).sort((n,a)=>oa(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ct.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ct.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function Sj(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 Ej(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function Pj(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function Rj(e,t){let i=[],r=uj("sha256").update(`${hj}
193
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(ko(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ct.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(Sj(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Ej(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:Pj(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function CN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function xj(e,t){return CN(e.classification)-CN(t.classification)||oa(e.left,t.left)||oa(e.right,t.right)}function AN(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:dj,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function IN(e){let t=kj(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(Rj(t[s],t[c]));i.sort(xj);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=M(fj,{changes:t,relationships:r}),a=i.slice(0,ct.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=AN(t,i,a,n);for(;a.length>0&&Ah(JSON.stringify(o))>ct.maxSerializedBytes;)a=a.slice(0,-1),o=AN(t,i,a,n);if(Ah(JSON.stringify(o))>ct.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as M$}from"node:crypto";import{promises as Xt}from"node:fs";import hi from"node:path";import{createHash as LN}from"node:crypto";import jN from"path";var Ih="comet.native.implementation-scope.v2",BN="comet.native.content-snapshot-projection.v1",Jo="comet.native.content-snapshot-projection.v1",qN="comet.native.implementation-scope.v2",Cj="comet.native.unresolved-scope-id.v1",Aj="comet.native.scope-detail-overflow.v1",_j="comet.native.snapshot-projection-overflow.v2",Hh=/^[a-f0-9]{64}$/u,tn=1024*1024,Tj=128,Ij=128;function We(e,t){return e<t?-1:e>t?1:0}function jh(e){if(!Hh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function jj(e,t){return e===t?0:e===null?-1:t===null?1:We(e,t)}function mr(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=jN.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||jN.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function VN(e,t){return e==="."?e:mr(e,t)}function sa(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function $j(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:mr(e.path,`${t} path`),hash:e.hash,size:sa(e.size,`${t} size`),type:"file"}}function Oj(e,t){return{path:VN(e.path,`${t} path`),size:e.size===null?null:sa(e.size,`${t} size`),type:e.type,reason:e.reason}}function Hj(e,t){return We(e.path,t.path)||We(e.hash,t.hash)||e.size-t.size}function Dj(e,t){return We(e.path,t.path)||We(e.reason,t.reason)||We(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Uo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
194
+ `,"utf8")}function pr(e,t,i){let r=`${t}
195
+ ${ko(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function Mj(e){if(Uo(e)<=tn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=LN("sha256");a.update(`${_j}
196
+ `),e.omissionOverflow&&pr(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,pr(a,"omission",f)},s=f=>{r+=1,n+=1,pr(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:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Uo(u)>tn;){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 v=0;v<p;v+=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 v of t.splice(-p))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 $h(e){let t=Ei(e),i=t.entries.map((n,a)=>$j(n,`Snapshot entry ${a}`));if(i.sort(Hj),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>Oj(n,`Snapshot omission ${a}`));return r.sort(Dj),Mj({schema:BN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Ko(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:mr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>We(i.path,r.path)||We(i.kind,r.kind))}function Yo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function $N(e){return e?{hash:e.hash,size:e.size}:null}function Dh(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:We(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:$N(c),after:$N(l)})}}function WN(e,t){return{...e,attributedTo:t.filter(i=>Yo(i,e.path))}}function Mh(e){let t=Ko(e.declaredArtifacts),i=[];return Dh(e.baseline,e.current,r=>{i.push(WN(r,t))}),i}function xi(e,t){return{id:`scope:${M(Cj,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function Fj(e,t){let i=t.omitted.map(r=>xi({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(xi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(xi({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 ON(e,t){return Fj(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Oh(e,t){return We(e.kind,t.kind)||We(e.source,t.source)||jj(e.path,t.path)||We(e.id,t.id)}function Lj(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Oh)}function zN(e){return[...new Set(e.map((t,i)=>mr(t,`Git path ${i}`)))].sort(We)}function HN(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function Bj(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function JN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=zN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:HN(e.baseCommit,"Native external drift base commit"),targetBranch:Bj(e.targetBranch,"Native external drift target branch"),targetCommit:HN(e.targetCommit,"Native external drift target commit"),paths:t}}function GN(e){if(typeof e.contractHash!="string"||!Hh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Ko(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:zN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:JN(e.externalDrift)}}}function qj(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Dh(e,t,p=>{let v=i.some(h=>Yo(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<Tj){let h=WN(p,i),m=Uo(h);l+m<=tn?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function UN(e,t){return xi({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 Vj(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:sa(Number(t[1]),"Scope overflow change count"),unresolved:sa(Number(t[2]),"Scope overflow unresolved count"),unattributed:sa(Number(t[3]),"Scope overflow unattributed count")},r=en(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(UN(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function Wj(e){let t=LN("sha256");t.update(`${Aj}
197
+ `);let i=0;Dh(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){pr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Yo(o,n.path)&&(a+=1,pr(t,"change-attribution",o));pr(t,"change-end",{attributionCount:a}),a===0&&pr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&pr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function KN(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=qj(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(P=>!w.has(P)||n.some(D=>Yo(D,P)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=M(Jo,e),c=M(Jo,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=Ij)break;l.push(xi({kind:"snapshot-omission",source:R,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${R} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...ON("baseline",e),...ON("current",t),...o.totalChanges===0&&a===null?[xi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>R.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!R.has(w))}},v=R=>{let w=o.candidates.slice(0,R.detailedChangeCount),g=w.filter(Dt=>Dt.attributedTo.length===0&&!u.has(Dt.path)),P=o.totalChanges-w.length,D=o.totalUnattributed-g.length,O=d-R.detailedOmissionCount,De=D+O,ce=[...g.map(Dt=>xi({kind:"unattributed-change",source:"implementation-scope",path:Dt.path,evidence:{after:Dt.after,before:Dt.before,changeKind:Dt.kind}},`Changed path is not covered by a declared artifact: ${Dt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...De>0?[UN(R.overflowHash,{changes:P,unattributed:D,unresolved:De})]:[]],Z=Lj(ce),Zt=R.includeGitAdvisory?p():void 0;return{schema:Ih,contractHash:r,baselineProjectionRef:jh(s),baselineProjectionHash:s,currentProjectionRef:jh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:Z,noCodeReason:a,...Zt?{gitAdvisory:Zt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,N=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:y});if(Uo({...R,scopeHash:y})<=tn)break;if(N){N=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>h||d>m?Wj({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,k=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:S}),b={...k,scopeHash:M(qN,k)};if(Uo(b)>tn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Fh(e){let t=$h(e.baseline),i=$h(e.current),r=GN(e);return{authority:r,baseline:t,current:i,scope:KN(t,i,r)}}var zj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function en(e,t){if(typeof e!="string"||!Hh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function DN(e,t,i){let r=jh(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ca(e,t){let i=di(e,"Native snapshot projection");if(fi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==BN)throw new Error("Native snapshot projection schema is invalid");let r=Ei({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=$h(r);if(M(Jo,i)!==M(Jo,n))throw new Error("Native snapshot projection is not canonical");let a=M(Jo,n);if(t!==void 0&&en(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Lh(e,t){let i=di(e,`Declared artifact ${t}`);if(fi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:mr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function MN(e,t){if(e===null)return null;let i=di(e,t);return fi(i,["hash","size"],[],t),{hash:en(i.hash,`${t} hash`),size:sa(i.size,`${t} size`)}}function FN(e,t){let i=di(e,`Implementation change ${t}`);if(fi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Lh),n=Ko(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=MN(i.before,`Implementation change ${t} before`),o=MN(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:mr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function Jj(e,t){let i=di(e,`Unresolved scope ${t}`);fi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?VN(i.path,`Unresolved scope ${t} path`):mr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Go(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>mr(n,`${t} ${a}`)),r=[...new Set(i)].sort(We);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function YN(e){let t=di(e,"Native implementation external drift");if(fi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Go(t.paths,"Native external drift paths");return JN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function la(e){let t=di(e,"Native implementation scope"),i=[...zj].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(fi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Ih)throw new Error("Native implementation scope schema is invalid");let r=en(t.contractHash,"Implementation scope contractHash"),n=en(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=DN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=en(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=DN(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(Lh);if(JSON.stringify(c)!==JSON.stringify(Ko(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(FN),u=[...l].sort((g,P)=>We(g.path,P.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(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(P=>Yo(P,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(FN),p=t.externalDrift===void 0?void 0:YN(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(Jj),N=m.filter(g=>g.kind==="scope-detail-overflow");if(N.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=N[0]===void 0?null:Vj(N[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,S=[...h.map(g=>xi({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+(y?.changes??0)===0&&E===null?[xi({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")]:[]],k=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Oh))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(S.sort(Oh))||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 g=di(t.gitAdvisory,"Implementation scope Git advisory");if(fi(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=Go(g.changedPaths,"Git changed paths"),D=Go(g.pathsPresentInSnapshotChanges,"Git present paths"),O=Go(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),De=[...D,...O].sort(We);if(JSON.stringify(De)!==JSON.stringify(P)||O.some(ce=>l.some(Z=>Z.path===ce)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:D,pathsAbsentFromSnapshotChanges:O}}let R={schema:Ih,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:E,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},w=en(t.scopeHash,"Implementation scope scopeHash");if(M(qN,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function Gj(e){let t=di(e,"Native implementation scope authority");if(fi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Lh);if(JSON.stringify(i)!==JSON.stringify(Ko(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Go(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:YN(t.externalDrift),a=GN({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Xo(e){let t=di(e,"Native implementation scope bundle");fi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Gj(t.authority),r=ca(t.baseline),n=ca(t.current),a=la(t.scope),o=KN(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 XN(e){let t=la(e.scope);return Xo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import QN from"node:path";var Uj=/\b(Bearer|Basic)\s+[^\s"']+/giu,Kj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Yj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Xj=/\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,Qj=/("(?:[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,Zj=/(["'])((?:[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,e$=/\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 At(e){return e.replace(Uj,"$1 [REDACTED]").replace(Kj,"[REDACTED PRIVATE KEY]").replace(Yj,"$1[REDACTED]@").replace(Xj,"[REDACTED TOKEN]").replace(Qj,'$1"[REDACTED]"').replace(Zj,"$1$2$1$3$4[REDACTED]$4").replace(e$,"$1$2[REDACTED]")}var eb=/^[a-f0-9]{64}$/u;var t$="comet.native.acceptance-trace.v2",i$="comet.native.partial-allowance.v1",r$="comet.native.verification-evidence.v2";function Ci(e,t){if(!eb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function ib(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 Bh(e,t,i=2e3){let r=At(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Qo(e,t){let i=QN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||QN.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 n$(e,t,i){let r=Qo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ii(r),a=r.toLowerCase(),o=i?Qo(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function qh(e){let t=Qo(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 ua(e,t){return e<t?-1:e>t?1:0}function $l(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ol(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function rb(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 ZN(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function a$(e){let t=$l(e,"Native acceptance trace");if(Ol(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"||!eb.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=Qo(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=$l(o,`Native acceptance trace entry ${s}`);if(Ol(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=>qh(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ua))||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:Qo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Bh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>ua(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Ci(t.traceHash,"Native acceptance trace hash");if(M(t$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Hl(e){let t=$l(e,"Native partial allowance");if(Ol(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(ua))||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:ib(t.change),scopeHash:Ci(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Bh(t.reason,"Partial allowance reason"),confirmedSummary:Bh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:tb(t.sourceRevision),confirmedAt:rb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Ci(t.allowanceHash,"Native partial allowance hash");if(M(i$,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Zo(e){let t=$l(e,"Native verification evidence");if(Ol(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=Ci(t.implementationScopeHash,"Native verification implementation scope hash"),r=a$(t.acceptanceTrace),n=Ci(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Ci(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>qh(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ua)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(ua);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=>qh(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ua)))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:ib(t.change),sourceRevision:tb(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ci(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:ZN(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:n$(t.reportRef,"Native verification report ref"),reportHash:Ci(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:ZN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:rb(t.createdAt,"Native verification timestamp")},d=Ci(t.envelopeHash,"Native verification envelope hash");if(M(r$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import nb from"node:path";var ab="comet.native.check-receipt.v1",o$="comet.native.check-receipt.v1",da="scoped-text-safety",Vh=1,lt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),s$=/^[a-f0-9]{64}$/u,c$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,l$="comet.native.checker-policy.v1",u$="comet.native.check-input.v1",d$=2048,ob=M(l$,{policy:da,version:Vh,limits:lt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),f$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),sb=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],lb=["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"],h$=new Set(lb);function vr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Ai(e,t){if(typeof e!="string"||!s$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ub(e,t){let i=yt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function cb(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 p$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>d$||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=nb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||nb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function m$(e){let t=vr(e,"Native check receipt checker");gr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=vr(t.limits,"Native check receipt limits");if(gr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==da||t.version!==Vh||t.hash!==ob||i.maxFiles!==lt.maxFiles||i.maxFileBytes!==lt.maxFileBytes||i.maxTotalBytes!==lt.maxTotalBytes||i.maxIssues!==lt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:da,version:Vh,hash:ob,limits:{...lt}}}function v$(e){let t=vr(e,"Native check receipt contract");return gr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Ai(t.expectedHash,"Native check expected contract hash"),beforeHash:Ai(t.beforeHash,"Native check before contract hash"),afterHash:Ai(t.afterHash,"Native check after contract hash")}}function g$(e){let t=vr(e,"Native check receipt implementation");return gr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Ai(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Ai(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Ai(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Ai(t.afterSnapshotHash,"Native check after snapshot hash")}}function w$(e,t){let i=vr(e,`Native check batch ${t}`);gr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:yt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:yt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:yt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:yt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:yt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:yt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>lt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>lt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function y$(e){let t=vr(e,"Native check receipt counts");gr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:yt(t.filesSelected,"Native check filesSelected"),filesScanned:yt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:yt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:yt(t.bytesScanned,"Native check bytesScanned"),issueCount:yt(t.issueCount,"Native check issueCount"),recordedIssueCount:yt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(w$):(()=>{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>lt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>lt.maxFiles||i.bytesScanned>lt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function N$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||sb.indexOf(e.kind)-sb.indexOf(t.kind)}function b$(e){if(!Array.isArray(e)||e.length>lt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=vr(r,`Native check issue ${n}`);if(gr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!f$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:p$(a.path,`Native check issue ${n} path`),line:ub(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(N$);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function k$(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!h$.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=lb.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function S$(e){return M(u$,e)}function Dl(e){let t=vr(e,"Native check receipt");if(gr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==ab)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!c$.test(t.change))throw new Error("Native check receipt change name is invalid");let i=ub(t.sourceRevision,"Native check source revision"),r=m$(t.checker),n=v$(t.contract),a=g$(t.implementation),o=S$({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Ai(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=cb(t.startedAt,"Native check receipt startedAt"),c=cb(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=y$(t.counts),u=b$(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=k$(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>lt.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>lt.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:ab,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Ai(t.receiptHash,"Native check receipt content hash");if(M(o$,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var zh="comet.native.verification-receipt.v3",E$=zh,P$="comet.native.declared-artifacts.v1",R$=/^[a-f0-9]{64}$/u,x$=/^acceptance-[a-f0-9]{64}$/u,C$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,_$=4096,T$=256,I$=1024;function fa(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 wr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function _i(e,t){if(typeof e!="string"||!R$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=At(e).trim();if(!i||i.length>_$||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Wh(e,t){let i=Yt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function es(e,t,i=Yt,r=!1,n=T$){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function j$(e,t){if(typeof e!="string"||!x$.test(e))throw new Error(`${t} is invalid`);return e}function $$(e){let t=fa(e,"Native verification receipt bindings");if(wr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!C$.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:_i(t.contractHash,"Native verification receipt contract hash"),scopeHash:_i(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:_i(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:_i(t.artifactHash,"Native verification receipt artifact hash")}}function O$(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=A$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function H$(e,t,i,r){let n=fa(t,`Native ${e} evidence`);if(e==="automated-check"){if(wr(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=Wh(n.startedAt,"Native automated-check start time"),o=Wh(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=fa(n.worktree,"Native automated-check worktree");if(wr(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=fa(n.afterFence,"Native automated-check after fence");if(wr(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:Yt(n.executable,"Native automated-check executable"),args:es(n.args,"Native automated-check arguments",Yt,!0),cwd:Yt(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:Yt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:_i(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:_i(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:_i(n.outputHash,"Native automated-check output hash"),outputSummary:Yt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){wr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=O$(n.checkReceiptRef);if(_i(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:es(n.subjects,"Native static inspection subjects",Yt,r==="required-check"),rule:Yt(n.rule,"Native static inspection rule"),resultSummary:Yt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return wr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:es(n.steps,"Native manual evidence steps"),observations:es(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function D$(e){let t=fa(e,"Native verification receipt");if(wr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=Yt(t.actor,"Native verification receipt actor"),o=es(t.acceptanceIds,"Native receipt acceptance IDs",j$,r==="required-check",I$).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:zh,kind:i,role:r,status:n,bindings:$$(t.bindings),acceptanceIds:o,actor:a,issuedAt:Wh(t.issuedAt,"Native verification receipt issue time"),evidence:H$(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==da||s.actor!==`native-runtime:${da}`))throw new Error("Native required check policy identity is invalid");return s}function Ml(e){let t=fa(e,"Native verification receipt");if(wr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==zh)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=D$(r),a=_i(t.receiptHash,"Native verification receipt hash");if(M(E$,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Jh(e){return M(P$,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var pb=/^[a-f0-9]{64}$/u,yr=tn,mW=3*yr;function Gh(e,t){let i=hi.relative(e,t);return i===""||!hi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${hi.sep}`)}function F$(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function db(e){let t=await Xt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Xt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function L$(e,t){let i=hi.resolve(e),r=hi.resolve(t);if(!Gh(i,r))throw new Error("Native evidence path is outside its change");let n=[await db(i)],a=i;for(let o of hi.relative(i,r).split(hi.sep).filter(Boolean)){a=hi.join(a,o);let s=await db(a);if(!Gh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function fb(e){for(let t of e){let i=await Xt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!F$(t,i)||await Xt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function B$(e,t,i={}){let r=await L$(t,hi.dirname(e));await i.afterParentChainCaptured?.();let n=await Xt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Xt.realpath(e);if(!Gh(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Xt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await fb(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fl(s,n)||!Fl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>yr)throw new Error(`Native evidence document exceeds ${yr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=yr+1-d,N=await o.read(f,0,Math.min(f.length,m),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>yr)throw new Error(`Native evidence document exceeds ${yr} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await fb(r),!v.isFile()||v.isSymbolicLink()||h!==a||!Fl(s,p)||!Fl(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 pa(e,t){if(!pb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function mb(e){return pa("reports",e)}async function q$(e,t,i,r,n){if(!pb.test(i))throw new Error("Native report evidence hash is invalid");let a=await rn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||M$("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 ha(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 V$(e,t,i,r,n){let a=pa(i,r);return n?hi.join(n,...a.split("/")):Qi(H(e,t),a)}async function rn(e){let t=V$(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),B$(t,i,e.hooks)}function hb(e,t){return ca(e,t)}function W$(e,t){let i=la(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function z$(e,t,i){let r=Hl(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function J$(e,t,i){let r=Zo(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function G$(e,t,i,r=!1,n){let a=await Ll(e,t,i.implementationScopeRef,void 0,n);if(r&&await q$(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await vb(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function ts(e,t,i,r,n){let a=ha(i,"scopes"),o=W$(await rn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=ha(o.baselineProjectionRef,"snapshots"),c=ha(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([rn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>hb(d,s)),rn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>hb(d,c))]);return XN({baseline:l,current:u,scope:o})}async function Ll(e,t,i,r,n){return(await ts(e,t,i,r,n)).scope}async function vb(e,t,i,r,n){let a=ha(i,"allowances");return z$(await rn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function is(e,t,i,r,n){let a=ha(i,"receipts"),o=Ml(await rn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function ma(e,t,i,r,n){let a=ha(i,"verifications"),o=J$(await rn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await G$(e,t,o,!1,n),o}var U$=4096;async function K$(e,t=ct.maxChanges){try{let i=await pt({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 gb(e,t){let i=await $e(e,t),[r,n]=await Promise.all([i.implementation_scope?Ll(e,t,i.implementation_scope):null,wt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Bl(e,t,i={}){let n=(await K$(e,U$)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await gb(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await gb(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=IN([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as fO}from"fs";import hO from"path";import{isDeepStrictEqual as Vl}from"util";var va={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var Y$=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function X$(e,t){return e<t?-1:e>t?1:0}function Q$(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!Y$.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(X$)}function Uh(e=[]){return Q$(e,"Native repair failed check IDs",va.maxFailedCheckIds,!0)}function wb(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function Z$(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:wb(e.failedAcceptanceIds,t.failedAcceptanceIds)&&wb(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Kh(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(Z$(r,a))break;i+=1,r=a}return i}function Yh(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 yb="repairStagnation",Nt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},tO=/^[a-f0-9]{64}$/u;var iO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),rO=["data","runId","sequence","timestamp","type"],Nb=["disposition","overrideSummaryHash","signatureHash"],nO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],bb=12;function Qh(e,t){return e<t?-1:e>t?1:0}function kb(e,t,i){let r=Object.keys(e).sort(Qh);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function ql(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 rs(e,t){if(typeof e!="string"||!tO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function aO(e){if(!Array.isArray(e)||e.length>va.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(Qh)}function Sb(e){if(typeof e!="string"||e.length===0||e.length>Nt.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 Xh(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Nt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Nt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Nt.maxTextCharacters&&(!n||e.length>Nt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Nt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Xh(s,t+1,i,`${r}[${c}]`));return}let a=ql(e,r),o=Object.keys(a);if(o.length>Nt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Nt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Xh(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function oO(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 sO(e,t,i){let r=ql(e,`Native repair trajectory event ${t+1}`);if(kb(r,rO,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(oO(r.timestamp),typeof r.type!="string"||!iO.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Sb(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 Xh(r.data,0,n,"Native trajectory event data"),ql(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Zh(e){let t=ql(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Qh),r=i.length===Nb.length&&i.every((l,u)=>l===Nb[u]);r||kb(t,nO,"Native repair trajectory projection");let n=rs(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:rs(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=rs(t.contractHash,"Native repair trajectory contract hash"),s=aO(t.failedAcceptanceIds),c=Uh(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function cO(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 lO(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??bb;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Kh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<va.warningAtConsecutiveFailures?"continue":a<va.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function uO(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??bb;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Eb(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Nt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Sb(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=sO(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Nt.maxTotalDataNodes||c>Nt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?rs(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?rs(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,yb)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Zh(f[yb]);if(cO(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&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),lO(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&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");uO(v,i,r);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:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>va.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Pb(e){return Eb(e).history}function Rb(e){let t=Eb(e).latestProjection;return t?{...t}:null}var pi={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:[]},ns=F("comet-native-runtime:v3:scope-reopen"),dO=[{skillVersion:"3",skillHash:F("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function xb(e){return e.skillVersion===pi.definition.metadata.version&&e.skillHash===ns||dO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var ep={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Nr(e){let i={sequence:(await Xe(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await Gy(e.changeDir,e.run.trajectoryRef,i),i}async function nn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Uy(e.changeDir,e.run.checkpointRef,t),t}function Cb(e){return F(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Hb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],pO=new Set(Hb),Db=new Set([...Hb,"minimum_runtime_version","revision"]),mO=new Set([...Db,"operation"]),vO=512*1024,tp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),gO=new Set([...tp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),as=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 ze(e,t){return hO.join(H(e,t),"transition.json")}function wO(e){return`transition-${e}`}async function yO(e,t,i){let r=wO(t);return er(e,r,i)}async function an(e,t,i,r){let n=await yO(e,t,i);try{return await r()}finally{await tr(n)}}function zl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function rp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Wl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){return Vl(e,t)}function ip(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!gO.has(u)),a=[...tp].find(u=>!Object.hasOwn(i,u)),o=tp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Yh(i.summary,"Native transition journal event summary"),At(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&&(Yh(i.noCodeReason,"Native transition journal event no-code reason"),At(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")?Zh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function NO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return ip({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return ip(e,t)}function np(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?NO(e.eventData,e.evidenceHash):ip(e.eventData,e.evidenceHash),n=hr(e.nextRun),a=e.previousRun===null?null:hr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Ab(e,t,i=!1){if(e.skill!==pi.definition.metadata.name||(i?!xb(e):e.skillVersion!==pi.definition.metadata.version||e.skillHash!==ns)||e.orchestration!==pi.definition.orchestration.mode||e.pendingRef!==vt.pendingRef||e.trajectoryRef!==vt.trajectoryRef||e.contextRef!==vt.contextRef||e.artifactsRef!==vt.artifactsRef||e.checkpointRef!==vt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function _b(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Tb(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 ap(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Ab(o,"next Run",r||a!==null),Tb(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Ab(a,"previous Run",!0),Tb(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Vl(_b(a),_b(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function bO(e,t,i){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Mb(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Ib(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function op(e,t,i,r,n=!1){let a=i.eventData,o=Ib(e),s=Ib(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Vl(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Vl(e.spec_changes,t.spec_changes),l=Cb({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=bO(e.name,a.summary,t.spec_changes),l=F(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function sp(e,t){let i=zl(e);if(rp(i,mO),i.schema!==rr)throw new Error(`Expected Native transition schema ${rr}`);let r=Wl(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 ${rr} minimum_runtime_version must be ${3}`);let n=Wl(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=np(i,t),o=st(i.previousState),s=st(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(op(o,s,a,i.operation),ap(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:rr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function kO(e,t){let i=zl(e);if(rp(i,pO),i.schema!==Jr)throw new Error(`Expected Native transition schema ${Jr}`);let r=np(i,t,!0),n=Gr(i.previousState),a=Gr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return op(n,a,r,Mb(n,a,r.eventData),!0),ap(n,a,r,!0),{schema:Jr,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function cp(e,t){let i=zl(e);if(rp(i,Db),i.schema!==Si)throw new Error(`Expected Native transition schema ${Si}`);if(Wl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Si} minimum_runtime_version must be 2`);let n=Wl(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=np(i,t,!0),o=ai(i.previousState),s=ai(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(op(o,s,a,Mb(o,s,a.eventData),!0),ap(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Si,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function SO(e,t){let i=zl(e);if(i.schema===rr)return{status:"current",journal:sp(i,t)};if(i.schema===Jr)return{status:"migration-required",journal:kO(i,t)};if(i.schema===Si)return{status:"migration-required",journal:cp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function lp(e,t){let i=ze(e,t),r=j(e,i);await T(r,i);try{let n=await ie({root:r,file:i,maxBytes:vO,label:`Native transition journal ${t}`});return SO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ti(e,t){let i=await lp(e,t);if(!i)return null;if(i.status==="migration-required")throw new as(t);return i.journal}function jb(e,t){if(mi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(mi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function $b(e,t){if(mi(e,t.nextState))return"next";if(mi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function EO(e){let{journal:t}=e;return Fb({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Fb(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Ob(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=EO({sequence:a.index+1,journal:t,type:a.event.type});if(!mi(Fb(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function Jl(e,t,i){if(await na(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Sl(e,t);let r=await Ti(e,t);if(!r)return null;let n=H(e,t),a=Ob(await Xe(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Ie(n),$e(e,t)]),c=jb(o,r),l=$b(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Xr(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!mi(await Ie(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let m=await Tl(e,r.nextState,r.previousState.revision);if(!mi(m,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!mi(await $e(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Ti(e,t);if(!u||!mi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Ob(await Xe(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Nr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await Nr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await nn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[p,v]=await Promise.all([Ie(n),$e(e,t)]);jb(p,{...r,previousRun:r.nextRun}),$b(v,{...r,previousState:r.nextState});let h=await Ti(e,t);if(!h||!mi(h,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await fO.rm(ze(e,t),{force:!0}),r.nextState}async function Lb(e,t,i){return he(e,`continue transition ${t}`,()=>an(e,t,`continue transition ${t}`,()=>Jl(e,t,i)))}import Bb from"node:path";var PO="comet.native.contract.v1",RO="comet.native.acceptance-set.v1",qb=/^[a-f0-9]{64}$/u,os={maxAcceptanceCriteria:Eo.maxCriteria};function Vb(e,t){let i=Bb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Bb.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 Wb(e){return M("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
198
+ `))}function xO(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(qb))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(qb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Vb(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Wb(e.markdown)},markdown:e.markdown}}function CO(e,t){return zb(e.id,t.id)}function zb(e,t){return e<t?-1:e>t?1:0}function Jb(e){let t=Vb(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(xO).sort((d,f)=>zb(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Vc(e.briefMarkdown,t,os.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Wc(f,d.source,os.maxAcceptanceCriteria-a.length)),a.push(...zc(f,d.source,os.maxAcceptanceCriteria-a.length)));if(a.sort(CO),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>os.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${os.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:Wb(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=M(RO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(PO,u)}}var Gl={maxSpecs:64,maxFileBytes:lo,maxTotalBytes:4*1024*1024};async function ga(e){if(e.specChanges.length>Gl.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Q({root:e.changeDir,ref:e.briefRef,maxBytes:Gl.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Q({root:e.changeDir,ref:n.source,maxBytes:Gl.maxFileBytes});if(i+=a.size,i>Gl.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:Jb({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as GO}from"node:child_process";import{promisify as UO}from"node:util";var g2=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as OO}from"fs";import wa from"path";var kr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},ya=/^[a-f0-9]{64}$/u;function Ul(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kl(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function br(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 Gb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function up(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||wa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=wa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function dp(e,t){return wa.join(H(e,t),"checkpoints","progress.json")}function Sr(e,t){return wa.join(H(e,t),"checkpoint-journal.json")}function fp(e,t,i){if(!ya.test(i))throw new Error("Native checkpoint manifest hash is invalid");return wa.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function _O(e){if(!ya.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function hp(e,t,i){let r=await ie({root:e,file:t,maxBytes:kr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function TO(e,t){let i=Ul(e,`checkpoint manifest artifact ${t}`);Kl(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=AO(br(i.path,`checkpoint artifact ${t} path`,4096)),n=ii(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!ya.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:up(i.size,`checkpoint artifact ${t} size`)}}function Yl(e,t){let i=Ul(e,"Native checkpoint manifest");if(Kl(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>kr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(TO),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=up(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>kr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function pp(e){return F(JSON.stringify(Yl(e,e.change)))}function mp(e,t){let i=Ul(e,"Native progress checkpoint");if(Kl(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Gb(i.previousRevision,"Native checkpoint previousRevision"),a=Gb(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=br(i.manifestHash,"Native checkpoint manifestHash",64);if(!ya.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=_O(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=br(i.inputHash,"Native checkpoint inputHash",64);if(!ya.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=br(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=up(i.artifactCount,"Native checkpoint artifactCount");if(u>kr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=br(i.summary,"Native checkpoint summary"),f=br(i.nextAction,"Native checkpoint nextAction");if(At(d)!==d||At(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:br(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function IO(e,t){let i=Ul(e,"Native checkpoint journal");if(Kl(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=st(i.previousState),n=st(i.nextState),a=mp(i.checkpoint,t),o=Yl(i.manifest,t),s=br(i.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!ya.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==pp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function jO(e,t,i){let r=wa.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=kf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ie({root:e.projectRoot,file:r,maxBytes:kr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function $O(e,t){let i=dp(e,t),r=j(e,i);await T(r,i);try{return mp(await hp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function vp(e,t,i){let r=fp(e,t,i),n=j(e,r);await T(n,r);let a=await hp(n,r,"Native checkpoint manifest"),o=Yl(a,t);if(gp(e,o),pp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Er(e,t){let i=Sr(e,t),r=j(e,i);await T(r,i);try{let n=IO(await hp(r,i,"Native checkpoint journal"),t);return gp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ub(e,t,i,r){let n=Yl(i,t);gp(e,n);let a=pp(n),o=fp(e,t,a),s=j(e,o);await T(s,o);try{let c=await vp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await te(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function gp(e,t){for(let i of t.artifacts){let r=kf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Kb(e,t){let i=mp(t,t.change),r=await vp(e,i.change,i.manifestHash),n=F(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=dp(e,t.change),o=j(e,a);await T(o,a),await te(a,i,{containedRoot:o})}async function Yb(e){let t;try{t=await $O(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:dp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await vp(e.paths,e.name,t.manifestHash);let a=F(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await jO(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:fp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Xb(e,t,i){let r=await Er(e,t);if(!r)return null;if(await Ub(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Tl(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Kb(e,r.checkpoint),await i?.afterProgressWritten?.(r),await OO.rm(Sr(e,t),{force:!0}),r}async function Qb(e,t,i){return he(e,`continue checkpoint ${t}`,()=>an(e,t,`continue checkpoint ${t}`,async()=>(await Jl(e,t),Xb(e,t,i))))}import{constants as wp,promises as _t}from"node:fs";import Na from"node:path";var HO=/^[a-f0-9]{64}$/u,DO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ss=512*1024;function MO(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function FO(e,t){let i=Na.resolve(e),r=Na.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Na.relative(i,r).split(Na.sep).filter(Boolean)]){o&&(a=Na.join(a,o));let s=await _t.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await _t.realpath(a);if(n.length>0&&!$(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 Zb(e){for(let t of e){let i=await _t.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!MO(t,i)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function LO(e){if(!HO.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function BO(e){let t=DO.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function qO(e,t,i){return Qi(H(e,t),LO(i))}async function VO(e,t,i){let r=await FO(i,Na.dirname(e)),n=await _t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>ss)throw new Error(`Native check receipt exceeds ${ss} bytes`);let[a,o]=await Promise.all([_t.realpath(t),_t.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":wp.O_RDONLY|wp.O_NOFOLLOW|wp.O_NONBLOCK,c=await _t.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(),_t.lstat(e),_t.realpath(e)]);if(await Zb(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Xl(n,l)||!Xl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=ss+1-p,E=await c.read(v,0,Math.min(v.length,y),null);if(E.bytesRead===0)break;if(p+=E.bytesRead,p>ss)throw new Error(`Native check receipt exceeds ${ss} bytes`);f.push(Buffer.from(v.subarray(0,E.bytesRead)))}let[h,m,N]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await Zb(r),!m.isFile()||m.isSymbolicLink()||N!==o||!$(a,N)||!Xl(l,h)||!Xl(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function ek(e,t,i){let r=BO(i),n=H(e,t),a=qO(e,t,r),o=j(e,a);await T(o,a);let s=Dl(await VO(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var cs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var fz=64*1024;var hz=3600*1e3;var pz=UO(GO);var KO=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function tk(e,t){let i=[];for(let r of KO){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function ik(e){if(e.receipt.kind!=="static-inspection")return null;let t=await ek(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 Pr=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function YO(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 XO(e){let t=YO(e.bundle.baseline),i=await mh(e.paths,t,{origin:"explicit",now:e.now});return Fh({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function nk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ts(e.paths,e.state.name,e.state.implementation_scope),i=await ga({changeDir:re(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await XO({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function ak(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await nk(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 QO(e){let t=await Q({root:re(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Fw(t.text)}}function ZO(e){let{receipt:t,implementationScope:i}=e,r=[],n=Mh({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function e0(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:Jh(e.implementationScope.scope.declaredArtifacts)}}async function rk(e){let t=await is(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=tk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Pr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await ik({paths:e.paths,state:e.state,receipt:t});if(n){let a=ZO({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function t0(e){let t=e0({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await rk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Pr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await rk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Pr)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 Pr(i)}function yp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ql(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:yp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([nk(e),ma(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:yp(e.state.verification_result,"stale"),envelope:null};let r=await QO({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await t0({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:yp(e.state.verification_result,"invalid"),envelope:null}}}function r0(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function sk(e){try{return await i0.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function n0(e,t){try{return(await Q({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function a0(e,t,i){let r=Il(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=ok.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await n0(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Q({root:re(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 o0(e,t){return sk(ze(e,t))}async function Zl(e){let t=e.now??new Date,i=await $e(e.paths,e.name),r=await wt(e.paths,e.name),n=await Ne(e.paths.projectRoot),a=r0(i.name,t),o=ok.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(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(v=>a0(e.paths,i.name,v))),Ql({paths:e.paths,state:i,now:t}),Bl(e.paths,i.name),na(e.paths,i.name),aa(e.paths,i.name),o0(e.paths,i.name),sk(o)]);return RN({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:p,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]})}import{promises as Np}from"node:fs";import Ii from"node:path";var s0="comet.native.archive-tree.v1",c0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function uk(e){let t={...c0,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function ck(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function lk(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function dk(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await pt({root:e,directory:t,label:`Native Archive content directory ${Ii.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=ck(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ii.join(t,u.name),f=Ii.relative(e,d).replaceAll("\\","/"),p=await Np.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){lk(i,{ref:f,kind:"directory"},r,n),await dk(e,d,i,r,n,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await ie({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);lk(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await pt({root:e,directory:t,label:`Native Archive content directory ${Ii.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(ck(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ii.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function fk(e,t={}){let i=uk(t);e=Ii.resolve(e);let r=await Np.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await dk(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return F(`${s0}\0${o}`)}async function Qt(e,t={}){let i=uk(t);e=Ii.resolve(e);let r;try{r=await Np.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ie({root:Ii.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ii.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await fk(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Qe}from"node:fs";import Pe from"node:path";var kp=16*1024*1024,l0=256*1024,u0=16*1024,ls="comet.native.archive-cas.v1";function d0(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Pe.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Oe(e,t){let i=d0(e,t);return T(j(e,i),i)}function Rr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function ba(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ut(e){let t=await Qt(e.target);if(!Rr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ba(t)}`);return t}async function Sp(e,t){let i=await si(e,t),r=await ie({root:e.runtimeDir,file:i.journal,maxBytes:l0,label:`Native Archive transaction journal ${t}`}),n=sl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function eu(e,t,i){let r=sl({...t,status:i}),n=await si(e,r.id);return await te(n.journal,r,{containedRoot:e.runtimeDir}),r}function tu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function hk(e){return{...tu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function xr(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function f0(e,t){return xr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ee(e){try{return await Qe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vi(e){let t=await Qe.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=hk(t),r=await ie({root:j(e.paths,e.file),file:e.file,maxBytes:kp,label:e.label}),n=await Qe.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!f0(i,hk(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:tu(n),size:r.size}}function h0(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==ls||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:ls,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function gi(e,t,i,r){let n=await si(e,t.id),a=Pe.join(n.backups,".cas"),o=`.${Pe.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Pe.join(a,`${i.id}.original.json`),postRecord:Pe.join(a,`${i.id}.post.json`),candidate:Pe.join(a,`${i.id}.candidate`),originalQuarantine:Pe.join(Pe.dirname(r),`${o}.original`),rollbackQuarantine:Pe.join(Pe.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Tt(e){if(!await ee(e.file))return null;let t=await ie({root:e.paths.runtimeDir,file:e.file,maxBytes:u0,label:`Archive CAS ${e.operation.id} ${e.role} record`});return h0(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function iu(e){let t=await Tt(e);if(t){if(!xr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await oi({root:e.paths.runtimeDir,directory:Pe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ls,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await te(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Tt(e);if(!r||!xr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Se(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!xr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function p0(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await iu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Se({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function m0(e){if(!await ee(e.quarantine)||await ee(e.target))return;let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Qe.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Qe.lstat(e.quarantine),Qe.lstat(e.target)]);if(!xr(tu(i),tu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Qe.unlink(e.quarantine),await t.verify()}async function gk(e){if(await ee(e.quarantine)){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Qe.rename(e.target,e.quarantine),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await m0(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function on(e){if(!await ee(e.file))return;await Se(e);let t=await Jt({root:j(e.paths,e.file),directory:Pe.dirname(e.file),label:e.label});await t.verify(),await Se(e),await Qe.unlink(e.file),await t.verify()}async function pk(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Oe(e,t.target),n=await Oe(e,t.backup),a=await Qt(n);if(a!==null){if(!Rr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ut({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await sr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:kp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ut({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function wk(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ee(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Se({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await pk(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ee(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await p0({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await pk(e.paths,e.operation,e.hooks),await gk({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function mk(e){let t=await gi(e.paths,e.journal,e.operation,e.target);return await ee(t.candidate)?(await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await oi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await sr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:kp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function v0(e){let t=e.operation.stagedHash,i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ee(e.target))return await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ee(i.candidate)&&await on({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ee(e.target)){let c=await mk(e),l=await vi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await iu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await on({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await mk(e),a=await vi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await oi({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Se({paths:e.paths,file:n,operation:e.operation,record:{schema:ls,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Qe.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!xr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await iu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await on({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function g0(e,t,i,r){let n=await Oe(e,i.target),a=await Oe(e,i.staged);if(await ut({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await gi(e,t,i,n);(!await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ee(n))&&await wk({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Qt(n);if(o!==null&&!Rr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${ba(o)}`)}await v0({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ut({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function w0(e,t,i,r){let n=await Oe(e,i.target);await wk({paths:e,journal:t,operation:i,target:n,hooks:r}),await ut({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function y0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(n===null&&Rr(a,t.expectedSourceHash,"directory"))){if(!Rr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ba(n)}, target=${ba(a)}`);await Qe.mkdir(Pe.dirname(r),{recursive:!0}),await Qe.rename(i,r),await ut({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function N0(e,t,i,r){return i.type==="write"?g0(e,t,i,r):i.type==="remove"?w0(e,t,i,r):y0(e,i)}function b0(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function k0(e,t,i,r){let n=await Oe(e,i.target);if(i.type==="write"){let a=await Oe(e,i.staged);await ut({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await gi(e,t,i,n),s=await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Se({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ut({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Tt({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ee(o.originalQuarantine))await Se({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ut({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ut({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await gi(e,t,i,n),o=await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ee(a.originalQuarantine))await Se({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ut({target:await Oe(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ut({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function yk(e,t,i){let r=t.status==="prepared"?await eu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await lr(e,r.id),a=b0({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await k0(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Rt(e,r.id,"operation-started",l.id),await N0(e,r,l,i),await Rt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Sp(e,r.id),r}async function S0(e){try{return await Se(e),!0}catch{return!1}}async function E0(e){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Qe.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function bp(e){if(e.operation.type!=="write")return;let t=await gi(e.paths,e.journal,e.operation,e.target);if(!await ee(t.candidate))return;let i=await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await on({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ls,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function P0(e,t,i,r){let n=await Oe(e,i.target),a=await gi(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Tt({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ee(a.candidate)&&await ee(n)){let l=await vi({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await vi({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});xr(l.identity,u.identity)&&(c=await iu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ee(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Se({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ee(n)&&!(s!==null&&await S0({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Qt(n);if(Rr(u,o)){await bp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await gk({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ee(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ee(n)){if(!s||!await ee(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await E0({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ee(a.originalQuarantine)&&await on({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ee(a.rollbackQuarantine)&&await on({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await bp({paths:e,journal:t,operation:i,target:n}),await ut({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function R0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(Rr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Rr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ba(n)}, target=${ba(a)}`);await Qe.mkdir(Pe.dirname(i),{recursive:!0}),await Qe.rename(r,i)}}async function Nk(e,t,i){let r=await lr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await eu(e,t,"rolling-back");await Rt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await R0(e,o):await P0(e,n,o,i));return await Rt(e,n.id,"rollback-completed"),n=await eu(e,n,"rolled-back"),n}async function vk(e,t,i){let r=await Oe(e,i.target);if(i.type==="write"){let n=await gi(e,t,i,r),a=await Tt({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Se({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ut({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function x0(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Oe(e,i.target),n=await gi(e,t,i,r);if(await ee(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await vk(e,t,i),i.expectedTargetHash!==null){let a=await Tt({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ee(n.originalQuarantine)&&await on({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await bp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await vk(e,t,i)}async function ru(e,t,i){return i==="commit"&&await x0(e,t),await Rt(e,t.id,i),i==="commit"?eu(e,t,"committed"):t}var sJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as C0}from"fs";import A0 from"path";var Ep="comet.selection.v2",_0=16*1024;function nu(e){return A0.join(e,".comet","current-change.json")}function T0(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function bk(e){return e===null||typeof e=="string"}function I0(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(!T0(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&&!bk(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ep,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ep)throw new Error(`current change selection schema must be ${Ep}`);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(!bk(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 Pp(e){let t;try{let r=nu(e),{bytes:n}=await qr(r,_0,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...I0(t)}}async function kk(e){await C0.rm(nu(e),{force:!0})}async function Sk(e,t,i){let r=await Pp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await kk(e),!0)}import{promises as fs}from"node:fs";import _r from"node:path";var _p=hn(Lr(),1);import{promises as Ak}from"node:fs";import It from"node:path";import{execFileSync as j0}from"node:child_process";var $0=3e4,O0=8*1024*1024,Rp=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function H0(e,t){try{return j0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$0,maxBuffer:O0,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Rp(e,t,r)}}function xp(e,t){return H0(e,t).trim()}var Ek="children.yaml",Cp="comet.native.children.v1",D0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,M0=new Set(["schema","children"]),F0=new Set(["name","depends_on","covers"]);function Pk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Rk(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0)throw new Error(`${i} fields are invalid`)}function xk(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function Ap(e,t){let i=It.normalize(It.resolve(e)),r=It.normalize(It.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function L0(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function B0(e,t){let i=new Set(t);for(let a of e){let o=a.covers.filter(s=>!i.has(s));if(o.length>0)throw new Error(`Native child ${a.name} covers unknown acceptance: ${o.join(", ")}`)}let r=new Set(e.flatMap(a=>a.covers)),n=t.filter(a=>!r.has(a));if(n.length>0)throw new Error(`Native children do not cover parent acceptance: ${n.join(", ")}`)}function q0(e,t){let i=(0,_p.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let r=Pk(i.toJS({mapAsMap:!1}),"Native children contract");if(Rk(r,M0,"Native children contract"),r.schema!==Cp)throw new Error(`Native children schema must be ${Cp}`);if(!Array.isArray(r.children)||r.children.length===0)throw new Error("Native children must be a non-empty array");let n=r.children.map((s,c)=>{let l=Pk(s,`Native child ${c}`);if(Rk(l,F0,`Native child ${c}`),typeof l.name!="string"||!D0.test(l.name))throw new Error(`Native child ${c} name is invalid`);return{name:l.name,depends_on:xk(l.depends_on,`Native child ${l.name} depends_on`),covers:xk(l.covers,`Native child ${l.name} covers`)}}),a=n.map(({name:s})=>s);if(new Set(a).size!==a.length)throw new Error("Native child names must be unique");let o=new Set(a);for(let s of n){let c=s.depends_on.filter(l=>!o.has(l));if(c.length>0)throw new Error(`Native child ${s.name} depends on unknown child: ${c.join(", ")}`)}return L0(n),t&&B0(n,t),{schema:Cp,children:n}}async function Tp(e){let t=It.join(e.changeDir,Ek);try{await Ak.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await Q({root:e.changeDir,ref:Ek});return{contract:q0(i.text,e.acceptanceIds),size:i.size}}function Ip(e){return M("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function V0(e){let t=Rn(e.projectRoot);t.some(r=>Ap(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>It.resolve(n)))]){let n=await Ne(r);n&&i.push({projectRoot:r,paths:await Be(r,n.native.artifact_root),parent:Ap(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function W0(e,t){let i=It.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ue(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function z0(e,t){let i;try{i=await Ak.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=It.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ue(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function J0(e,t,i){let r=It.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${It.sep}`))return null;let n=r.split(It.sep).join("/");try{let a=(0,_p.parseDocument)(xp(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:nt(a.toJS({mapAsMap:!1}))}catch{return null}}function G0(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Ck(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function us(e){let t=It.join(e.paths.changesDir,e.state.name),i=await Tp({changeDir:t,...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=Ip({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await V0(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:h})=>h)),c=new Map,l=new Map;for(let h of a){let m=h.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await z0(h,s)){let y={...N,source:h,committedState:J0(h,N.file,m)};c.set(N.state.name,[...c.get(N.state.name)??[],y])}for(let N of s){let y=await W0(h,N);y&&l.set(N,[...l.get(N)??[],{source:h,state:y}])}}let u=new Map;for(let h of i.contract.children){let m=(c.get(h.name)??[]).find(({source:E,committedState:S})=>E.parent&&S?.name===h.name&&Ck(S,o));if(m){u.set(h.name,{kind:"done",phase:m.state.phase,projectRoot:m.source.projectRoot,message:null});continue}let N=c.get(h.name)?.[0];if(N){u.set(h.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=l.get(h.name)??[];y.length>1?u.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&u.set(h.name,G0(y[0].state,y[0].source,o))}let d=new Map(i.contract.children.map(h=>[h.name,h])),f=new Map,p=h=>{let m=f.get(h);if(m)return m;let N=d.get(h),E=N.depends_on.map(p).every(({status:g})=>g==="done"),S=u.get(h),k=S?.kind==="active"&&E?N.depends_on.filter(g=>!(c.get(g)??[]).some(({source:P,committedState:D})=>Ap(P.projectRoot,S.projectRoot)&&D?.name===g&&Ck(D,o))):[],b,R=S?.message??null;S?.kind==="done"?(b=E?"done":"blocked",E||(R=`Native child ${h} was merged before its dependencies`)):S?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(R=`Native child ${h} does not include merged dependencies: ${k.join(", ")}`):R=`Native child ${h} started before its dependencies merged`):S?.kind==="blocked"?b="blocked":(b=n&&E?"ready":"pending",n||(R="Parent Shape confirmation is required"));let w={name:h,dependsOn:[...N.depends_on],covers:[...N.covers],status:b,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:R};return f.set(h,w),w},v=i.contract.children.map(({name:h})=>p(h));return{contractHash:r,confirmed:n,parentBranch:o,children:v,readyChildren:v.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:v.every(({status:h})=>h==="done")}}var au="skill-coordinated";function K0(e){return e.state_version+1}function Y0(e){return e.map(t=>({...t,result:"pending",reason:null}))}function X0(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:ir(e.summary),completed_at:e.completedAt}}function jp(e){let t=nt(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Ln(t,X0({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return nt({...r,phase:"build",status:"active",state_version:K0(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:Y0(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Tk}from"node:fs";import ds from"node:path";function ou(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function su(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function wi(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function _k(e,t){return e===null?null:wi(e,t)}function lu(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function Q0(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function Z0(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function cu(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function $p(e,t){if(e===null)return null;let i=wi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Op(e,t){let i=wi(e,t);if(!ds.isAbsolute(i))throw new Error(`${t} must be absolute`);return ds.resolve(i)}function eH(e,t){let i=`Native local checks[${t}]`,r=ou(e,i);if(su(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)=>wi(l,`${i}.argv[${u}]`,!0)),a=cu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=$p(r.startedAt,`${i}.startedAt`),s=$p(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=lu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:wi(r.id,`${i}.id`),name:wi(r.name,`${i}.name`),operationId:wi(r.operationId,`${i}.operationId`),status:a,repeatable:Z0(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:lu(r.executionCount,`${i}.executionCount`),argv:n,cwd:Op(r.cwd,`${i}.cwd`),exitCode:Q0(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:wi(r.log,`${i}.log`)}}function Hp(e){let t="Native local execution state",i=ou(e,t);if(su(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Po)throw new Error(`Native local execution schema must be ${Po}`);let r=ou(i.workspace,"Native local workspace");su(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=ou(i.execution,"Native local execution");su(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=$p(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:wi(o.operationId,"Native local execution.operationId"),stage:cu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:cu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:_k(o.executionId,"Native local execution.executionId"),status:cu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:lu(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(eH);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:Po,change:wi(i.change,"Native local change"),basedOnStateVersion:lu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Op(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Op(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:_k(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function sn(e){return Hp({schema:Po,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:ds.resolve(e.projectRoot),worktreeRoot:ds.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function uu(e){let t;try{t=await Tk.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Hp(i)}async function Cr(e,t,i={}){let r=Hp(t);await Tk.mkdir(ds.dirname(e),{recursive:!0}),await te(e,r,i)}import{promises as tH}from"node:fs";function Ar(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
199
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function ji(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function iH(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function rH(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===au?au:"host-attested")}function nH(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${ji(o.id)} | ${ji(o.result)} | ${ji(o.source)} | ${ji(o.text)} | ${ji(Ar(o.reason))} |`).join(`
200
+ `),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(Ar).join(" ");return`| ${ji(Ar(o.name))} | ${ji(s||"—")} | ${ji(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
201
+ `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${Ar(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
202
+ `),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${Ar(o)}`).join(`
203
+ `),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${ji(Ar(o.summary))} | ${o.completed_at} |`)].join(`
204
+ `);return`---
205
+ generated_from_state_version: ${e.state_version}
206
+ ---
207
+
208
+ # Verification
209
+
210
+ ## Current result
211
+
212
+ - Result: **${iH(e)}**
213
+ - Assurance: **${rH(e)}**
214
+ - Goal cycle: ${e.loop.goal_cycle}
215
+ - Iteration: ${e.verification.iteration}
216
+ - Verifier attempt: ${e.verification.attempt}
217
+ - Completed: ${e.verification.completed_at}
218
+ - Summary: ${Ar(e.verification.summary)}
219
+
220
+ ## Acceptance
221
+
222
+ | ID | Result | Source | Criterion | Reason |
223
+ | --- | --- | --- | --- | --- |
224
+ ${t}
225
+
226
+ ## Checks
227
+
228
+ ${i}
229
+
230
+ ## Blockers
231
+
232
+ ${r}
233
+
234
+ ## Risks and skipped work
235
+
183
236
  ${n}
184
- ${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return Ta(c),c}async function Ia(e){let t=await Eg(e),i=nr(e.paths,e.name);return await _(e.paths.nativeRoot,i),await ve(i,t,{containedRoot:e.paths.nativeRoot}),t}async function Dt(e,t){let i=await Sg(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Ta(i),i)}async function Rg(e){return await Rd(e.paths,e.name)?Ia(e):null}async function _a(e){Ta(e.identity);let t=await Eg({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")),Sd==="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 ja(e){if(Ta(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 _a(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=mg(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 Cg(e,t){let i=await Dt(e,t);if(i===null)return null;let n=await ja({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var ge="comet.native.v3",we="comet.native.v2",st="comet.native.v1",$i="comet.native.transition.v3",Gt="comet.native.transition.v2",ln="comet.native.transition.v1";var Ag=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],lA=new Set(Ag),xg=new Set([...Ag,"minimum_runtime_version","revision"]),uA=new Set([...xg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),dA=new Set(["capability","operation","source","base_hash"]),fA=new Set(["shape","build","verify","archive"]),hA=new Set(["implicit","confirmed"]),pA=new Set(["pending","pass","fail"]),Se="comet-state.yaml",Pd=/^[a-f0-9]{64}$/u,Tg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mA=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Oa=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"},dn=class extends Error{constructor(i,n){super(i!==ge||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"},$a=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"},rc=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"},rr=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"},kF=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
185
- `);function Da(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ig(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 oc(e){if(!Tg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vA(e){if(!Tg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function _g(e,t){if(e.length===0||Ut.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function gA(e,t){let i=Da(e,`spec_changes[${t}]`);if(Ig(i,dA,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(vA(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"&&_g(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"||!Pd.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"||!Pd.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 wA(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 Ad(e,t){if(Ig(e,t,Se),typeof e.name!="string")throw new Error("Native change name is required");if(oc(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"||!fA.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&&!hA.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(gA),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"||!pA.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"&&_g(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!wA(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 Fa(e){let t=Da(e,Se);if(t.schema!==st)throw new Error(`Expected ${st}`);return{schema:st,...Ad(t,lA)}}function Ha(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Cd(e,t,i){if(e===null)return null;let n=typeof e=="string"?mA.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 yA(e){if(e==null)return null;if(typeof e!="string"||!Pd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function NA(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 Hi(e){let t=Da(e,Se);if(t.schema!==we)throw new Error(`Expected ${we}`);if(Ha(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${we} minimum_runtime_version must be 2`);return{schema:we,minimum_runtime_version:2,revision:Ha(t.revision,"Native v2 revision"),...Ad(t,xg)}}function ct(e){let t=Da(e,Se);if(t.schema!==ge){if(t.schema===st||t.schema===we){let o=t.schema===st?Fa(t):Hi(t);throw new Oa(o.name,o.schema)}throw new dn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Ha(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new dn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Ha(t.revision,"Native revision"),r=Ad(t,uA),a=yA(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ge,minimum_runtime_version:3,revision:n,verification_protocol:NA(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Cd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Cd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Cd(t.partial_allowance,"Native partial_allowance","allowances")}}function bA(e){let t=Da(e,Se);if(t.schema===st){let r=Fa(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${ge}`}}if(t.schema===we){let r=Hi(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${ge}`}}if(t.schema!==ge){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 dn(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=Ha(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new dn(t.schema,i).message};let n=ct(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function un(e){let t=ct(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function sc(e){let t=Hi(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function I(e,t){oc(t);let i=Ut.join(e.changesDir,t);if(!q(e.changesDir,i))throw new Error("Native change path escaped");return i}async function ar(e,t){let i=Ut.join(I(e,t),"runtime","schema-migration.json");await _(e.nativeRoot,i);try{return await Pg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function or(e,t){let i=Ut.join(I(e,t),"runtime","checkpoint-journal.json");await _(e.nativeRoot,i);try{return await Pg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var kA=256*1024;async function xd(e,t=Ut.dirname(e)){let i=Ut.relative(t,e).split(Ut.sep).join("/"),n=await $e({root:t,ref:i,maxBytes:kA}),r=(0,ac.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 lt(e,t){let i=Ut.join(I(e,t),Se);await _(e.nativeRoot,i);let n=bA(await xd(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await ar(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 SA(e,n.state),n)}async function SA(e,t){if(await Zn(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Ie(e,t){let i=await lt(e,t);if(i.status==="migration-required")throw new Oa(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new dn(i.schema,i.minimumRuntimeVersion);return await Cg(e,t),i.state}async function jg(e,t,i){let n={...t,schema:ge,minimum_runtime_version:3,revision:i+1},r=await Ov({expectedRevision:i,next:n,read:async()=>{let a=ct(await xd(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Ve(e,(0,ac.stringify)(un(a))),equals:(a,o)=>JSON.stringify(un(a))===JSON.stringify(un(o)),conflict:a=>new $a(t.name,i,a)});return Object.assign(t,r),r}async function cc(e,t,i,n){if(await Bn(e.projectRoot),await ar(e,t.name))throw new Oa(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await or(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Ie(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await tc(e,t.name);let a=Ut.join(I(e,t.name),Se);return await _(e.nativeRoot,a),jg(a,t,i)}async function Og(e,t){return jg(e,t,t.revision)}async function $g(e){return ct(await xd(e))}var Dg=["Outcome","Scope","Non-goals","Acceptance examples"],EA=[...Dg,"Constraints and invariants","Decisions","Open questions","Verification expectations"],RA=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Fg={maxFileBytes:aa};function Mg(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
186
- `).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 CA(e,t){let i=Hg.resolve(e,...t.split(/[\\/]/u));if(!q(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Td.realpath(e),r=await Td.realpath(i);if(!q(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Td.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Ma(e){return{valid:e.length===0,findings:e}}async function Id(e,t){let i=[],n;try{n=(await $e({root:e,ref:t,maxBytes:Fg.maxFileBytes})).text}catch(o){return Ma([{code:"brief-missing",message:o.message,path:t}])}let r=Mg(n);for(let o of EA)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Dg)(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}),Ma(i)}async function _d(e,t){let i=[],n;try{n=(await $e({root:e,ref:t,maxBytes:Fg.maxFileBytes})).text}catch(a){return Ma([{code:"verification-missing",message:a.message,path:t}])}let r=Mg(n);for(let a of RA)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 Ma(i)}function lc(e,t){return Hg.join(e.specsDir,t,"spec.md")}async function Lg(e,t){let i=[],n=I(e,t.name);for(let r of t.spec_changes){let a=lc(e,r.capability),o=null;try{await _(e.nativeRoot,a),o=await Nt(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 CA(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Ma(i)}import{promises as UI}from"node:fs";import Iy from"node:path";import Bg from"node:path";import{createHash as PA}from"crypto";function kt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function AA(e,t){t.has(e)&&kt("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)||kt("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&kt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&kt("symbol properties are not supported"),`[${e.map(n=>jd(n,t)).join(",")}]`}finally{t.delete(e)}}function xA(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&kt("only plain objects are supported"),t.has(e)&&kt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&kt("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))&&kt("accessor properties are not supported"),`${JSON.stringify(o)}:${jd(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function jd(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)||kt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?AA(e,t):xA(e,t);case"bigint":case"function":case"symbol":case"undefined":return kt(`${typeof e} values are not supported`)}return kt("unsupported value type")}function La(e){return jd(e,new Set)}function D(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 PA("sha256").update(`${e}
187
- ${La(t)}`).digest("hex")}var TA="comet.native.archive-preflight.v1",IA="comet.native.archive-preflight.v1",_A="comet.native.archive-operation.v1",jA=/^[a-f0-9]{64}$/u,qg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function uc(e,t){return e<t?-1:e>t?1:0}function $A(e,t){if(typeof e!="string"||!jA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Kt(e,t){return e===null?null:$A(e,t)}function HA(e,t){let i=Bg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Bg.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 DA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function FA(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 MA(e,t){if(!qg.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=Kt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=Kt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=Kt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(r===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:n,proposedHash:r}}function LA(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Kt(e.contractHash,"Native archive contract hash"),acceptanceHash:Kt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Kt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Kt(e.reportHash,"Native archive report hash"),envelopeHash:Kt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Kt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function BA(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!OA.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(uc);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function qA(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(uc)}function Vg(e){if(!qg.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(MA).sort((l,u)=>uc(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:D(_A,l)})),n=LA(e.evidence),r=FA(e.workspace),a=[...new Set([...BA(e.findingCodes??[]),...qA({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(uc),o=DA(e.revision),s=HA(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:TA,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:D(IA,c)}}import{createHash as VA}from"node:crypto";import Wg from"node:path";var WA="comet.native.conflict-radar.v1",Je=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}),JA="comet.native.conflict-radar.v1",zA="comet.native.conflict-radar-signals.v1",GA=/^[a-f0-9]{64}$/u,Gg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,UA=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),KA=new Set(["capability","operation","baseHash"]),YA=new Set(["path","kind"]);function sr(e,t){return e<t?-1:e>t?1:0}function Od(e){return Buffer.byteLength(e,"utf8")}function $d(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 Hd(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(Od(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function XA(e,t){let i=Hd(e,t,Je.maxArtifactPathBytes),n=Wg.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)||Wg.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 Ug(e,t){if(typeof e!="string"||!GA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function QA(e,t){let i=$d(e,KA,t),n=Hd(i.capability,`${t} capability`,Je.maxCapabilityBytes);if(!Gg.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:Ug(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 ZA(e,t){let i=$d(e,YA,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:XA(i.path,`${t} path`),kind:i.kind}}function ex(e,t){let i=$d(e,UA,`Conflict radar change ${t}`),n=Hd(i.name,`Conflict radar change ${t} name`,Je.maxNameBytes);if(!Gg.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>Je.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>Je.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>QA(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>sr(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)=>ZA(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>sr(c.path,l.path)||sr(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:Ug(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function tx(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Je.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(ex).sort((r,a)=>sr(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)>Je.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>Je.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function ix(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 nx(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 rx(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function ax(e,t){let i=[],n=VA("sha256").update(`${zA}
188
- [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(La(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Je.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(ix(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=nx(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:rx(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Jg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function ox(e,t){return Jg(e.classification)-Jg(t.classification)||sr(e.left,t.left)||sr(e.right,t.right)}function zg(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:WA,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 Kg(e){let t=tx(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(ax(t[s],t[c]));i.sort(ox);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=D(JA,{changes:t,relationships:n}),a=i.slice(0,Je.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=zg(t,i,a,r);for(;a.length>0&&Od(JSON.stringify(o))>Je.maxSerializedBytes;)a=a.slice(0,-1),o=zg(t,i,a,r);if(Od(JSON.stringify(o))>Je.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as gT}from"node:crypto";import{promises as Rt}from"node:fs";import Ft from"node:path";import{createHash as iw}from"node:crypto";import Yg from"path";var Dd="comet.native.implementation-scope.v2",nw="comet.native.content-snapshot-projection.v1",Ba="comet.native.content-snapshot-projection.v1",rw="comet.native.implementation-scope.v2",sx="comet.native.unresolved-scope-id.v1",cx="comet.native.scope-detail-overflow.v1",lx="comet.native.snapshot-projection-overflow.v2",Bd=/^[a-f0-9]{64}$/u,hn=1024*1024,ux=128,dx=128;function _e(e,t){return e<t?-1:e>t?1:0}function Fd(e){if(!Bd.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function fx(e,t){return e===t?0:e===null?-1:t===null?1:_e(e,t)}function Fi(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=Yg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Yg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function aw(e,t){return e==="."?e:Fi(e,t)}function cr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function hx(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:Fi(e.path,`${t} path`),hash:e.hash,size:cr(e.size,`${t} size`),type:"file"}}function px(e,t){return{path:aw(e.path,`${t} path`),size:e.size===null?null:cr(e.size,`${t} size`),type:e.type,reason:e.reason}}function mx(e,t){return _e(e.path,t.path)||_e(e.hash,t.hash)||e.size-t.size}function vx(e,t){return _e(e.path,t.path)||_e(e.reason,t.reason)||_e(e.type,t.type)||(e.size??-1)-(t.size??-1)}function qa(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
189
- `,"utf8")}function Di(e,t,i){let n=`${t}
190
- ${La(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function gx(e){if(qa(e)<=hn)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=iw("sha256");a.update(`${lx}
191
- `),e.omissionOverflow&&Di(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,Di(a,"omission",f)},s=f=>{n+=1,r+=1,Di(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(;qa(u)>hn;){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 Md(e){let t=zt(e),i=t.entries.map((r,a)=>hx(r,`Snapshot entry ${a}`));if(i.sort(mx),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)=>px(r,`Snapshot omission ${a}`));return n.sort(vx),gx({schema:nw,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 fc(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:Fi(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)=>_e(i.path,n.path)||_e(i.kind,n.kind))}function hc(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Xg(e){return e?{hash:e.hash,size:e.size}:null}function ow(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:_e(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:Xg(c),after:Xg(l)})}}function wx(e,t){return{...e,attributedTo:t.filter(i=>hc(i,e.path))}}function Yt(e,t){return{id:`scope:${D(sx,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function yx(e,t){let i=t.omitted.map(n=>Yt({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(Yt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Yt({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 Qg(e,t){return yx(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Ld(e,t){return _e(e.kind,t.kind)||_e(e.source,t.source)||fx(e.path,t.path)||_e(e.id,t.id)}function Nx(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Ld)}function bx(e){return[...new Set(e.map((t,i)=>Fi(t,`Git path ${i}`)))].sort(_e)}function sw(e){if(typeof e.contractHash!="string"||!Bd.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:fc(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:bx(e.gitChangedPaths)}}}function kx(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return ow(e,t,d=>{let f=i.some(p=>hc(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<ux){let p=wx(d,i),m=qa(p);s+m<=hn?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function cw(e,t){return Yt({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 Sx(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:cr(Number(t[1]),"Scope overflow change count"),unresolved:cr(Number(t[2]),"Scope overflow unresolved count"),unattributed:cr(Number(t[3]),"Scope overflow unattributed count")},n=fn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(cw(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function Ex(e){let t=iw("sha256");t.update(`${cx}
192
- `);let i=0;ow(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){Di(t,"change",r);let a=0;for(let o of e.declaredArtifacts)hc(o,r.path)&&(a+=1,Di(t,"change-attribution",o));Di(t,"change-end",{attributionCount:a}),a===0&&Di(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&&Di(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function lw(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=kx(e,t,r,i.gitChangedPaths),s=D(Ba,e),c=D(Ba,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=dx)break;l.push(Yt({kind:"snapshot-omission",source:y,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${y} snapshot omitted ${g.path}: ${g.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Qg("baseline",e),...Qg("current",t),...o.totalChanges===0&&a===null?[Yt({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),g=w.filter(At=>At.attributedTo.length===0),E=o.totalChanges-w.length,j=o.totalUnattributed-g.length,Q=u-y.detailedOmissionCount,J=j+Q,K=[...g.map(At=>Yt({kind:"unattributed-change",source:"implementation-scope",path:At.path,evidence:{after:At.after,before:At.before,changeKind:At.kind}},`Changed path is not covered by a declared artifact: ${At.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||J>0?[cw(y.overflowHash,{changes:E,unattributed:j,unresolved:J})]:[]],te=Nx(K),Pt=y.includeGitAdvisory?f():void 0;return{schema:Dd,contractHash:n,baselineProjectionRef:Fd(s),baselineProjectionHash:s,currentProjectionRef:Fd(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:r,changes:w,unattributed:g,unresolvedScopes:te,noCodeReason:a,...Pt?{gitAdvisory:Pt}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:b});if(qa({...y,scopeHash:b})<=hn)break;if(v){v=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>m||u>h?Ex({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):b,S=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:k}),R={...S,scopeHash:D(rw,S)};if(qa(R)>hn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return R}function qd(e){let t=Md(e.baseline),i=Md(e.current),n=sw(e);return{authority:n,baseline:t,current:i,scope:lw(t,i,n)}}var Rx=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qt(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 fn(e,t){if(typeof e!="string"||!Bd.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Zg(e,t,i){let n=Fd(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function lr(e,t){let i=Xt(e,"Native snapshot projection");if(Qt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==nw)throw new Error("Native snapshot projection schema is invalid");let n=zt({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=Md(n);if(D(Ba,i)!==D(Ba,r))throw new Error("Native snapshot projection is not canonical");let a=D(Ba,r);if(t!==void 0&&fn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Vd(e,t){let i=Xt(e,`Declared artifact ${t}`);if(Qt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Fi(i.path,`Declared artifact ${t} path`),kind:i.kind}}function ew(e,t){if(e===null)return null;let i=Xt(e,t);return Qt(i,["hash","size"],[],t),{hash:fn(i.hash,`${t} hash`),size:cr(i.size,`${t} size`)}}function tw(e,t){let i=Xt(e,`Implementation change ${t}`);if(Qt(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(Vd),r=fc(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=ew(i.before,`Implementation change ${t} before`),o=ew(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:Fi(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function Cx(e,t){let i=Xt(e,`Unresolved scope ${t}`);Qt(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"?aw(i.path,`Unresolved scope ${t} path`):Fi(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function dc(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)=>Fi(r,`${t} ${a}`)),n=[...new Set(i)].sort(_e);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function ur(e){let t=Xt(e,"Native implementation scope"),i=[...Rx].filter(w=>w!=="gitAdvisory");if(Qt(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Dd)throw new Error("Native implementation scope schema is invalid");let n=fn(t.contractHash,"Implementation scope contractHash"),r=fn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Zg(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=fn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Zg(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(Vd);if(JSON.stringify(c)!==JSON.stringify(fc(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(tw),u=[...l].sort((w,g)=>_e(w.path,g.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(g=>!d.has(`${g.kind}:${g.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(g=>hc(g,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(tw),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(Cx),h=m.filter(w=>w.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=h[0]===void 0?null:Sx(h[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let b=t.noCodeReason,N=[...p.map(w=>Yt({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+(v?.changes??0)===0&&b===null?[Yt({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(Ld))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(Ld))||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 S;if(t.gitAdvisory!==void 0){let w=Xt(t.gitAdvisory,"Implementation scope Git advisory");if(Qt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let g=dc(w.changedPaths,"Git changed paths"),E=dc(w.pathsPresentInSnapshotChanges,"Git present paths"),j=dc(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Q=[...E,...j].sort(_e),J=new Set(l.map(K=>K.path));if(JSON.stringify(Q)!==JSON.stringify(g)||(v?.changes??0)===0&&E.some(K=>!J.has(K))||j.some(K=>J.has(K)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:j}}let R={schema:Dd,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:b,...S?{gitAdvisory:S}:{}},y=fn(t.scopeHash,"Implementation scope scopeHash");if(D(rw,R)!==y)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:y}}function Px(e){let t=Xt(e,"Native implementation scope authority");if(Qt(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(Vd);if(JSON.stringify(i)!==JSON.stringify(fc(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=dc(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=sw({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 Va(e){let t=Xt(e,"Native implementation scope bundle");Qt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Px(t.authority),n=lr(t.baseline),r=lr(t.current),a=ur(t.scope),o=lw(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 uw(e){let t=ur(e.scope);return Va({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}import dw from"node:path";var Ax=/\b(Bearer|Basic)\s+[^\s"']+/giu,xx=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Tx=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,Ix=/\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,_x=/("(?:[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,jx=/(["'])((?:[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,Ox=/\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 St(e){return e.replace(Ax,"$1 [REDACTED]").replace(xx,"[REDACTED PRIVATE KEY]").replace(Tx,"$1[REDACTED]@").replace(Ix,"[REDACTED TOKEN]").replace(_x,'$1"[REDACTED]"').replace(jx,"$1$2$1$3$4[REDACTED]$4").replace(Ox,"$1$2[REDACTED]")}var hw=/^[a-f0-9]{64}$/u;var $x="comet.native.acceptance-trace.v2",Hx="comet.native.partial-allowance.v1",Dx="comet.native.verification-evidence.v2";function Zt(e,t){if(!hw.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function mw(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 Wd(e,t,i=2e3){let n=St(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function Wa(e,t){let i=dw.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})||dw.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 Fx(e,t,i){let n=Wa(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=It(n),a=n.toLowerCase(),o=i?Wa(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 Jd(e){let t=Wa(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 dr(e,t){return e<t?-1:e>t?1:0}function pc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mc(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 vw(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 fw(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 Mx(e){let t=pc(e,"Native acceptance trace");if(mc(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"||!hw.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=Wa(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=pc(o,`Native acceptance trace entry ${s}`);if(mc(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=>Jd(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(dr))||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:Wa(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Wd(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>dr(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=Zt(t.traceHash,"Native acceptance trace hash");if(D($x,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function vc(e){let t=pc(e,"Native partial allowance");if(mc(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(dr))||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:mw(t.change),scopeHash:Zt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Wd(t.reason,"Partial allowance reason"),confirmedSummary:Wd(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:pw(t.sourceRevision),confirmedAt:vw(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=Zt(t.allowanceHash,"Native partial allowance hash");if(D(Hx,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Ja(e){let t=pc(e,"Native verification evidence");if(mc(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=Zt(t.implementationScopeHash,"Native verification implementation scope hash"),n=Mx(t.acceptanceTrace),r=Zt(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:Zt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Jd(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(dr)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(dr);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=>Jd(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(dr)))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:mw(t.change),sourceRevision:pw(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Zt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:fw(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:Fx(t.reportRef,"Native verification report ref"),reportHash:Zt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:fw(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:vw(t.createdAt,"Native verification timestamp")},d=Zt(t.envelopeHash,"Native verification envelope hash");if(D(Dx,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import gw from"node:path";var ww="comet.native.check-receipt.v1",Lx="comet.native.check-receipt.v1",fr="scoped-text-safety",zd=1,ut=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Bx=/^[a-f0-9]{64}$/u,qx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Vx="comet.native.checker-policy.v1",Wx="comet.native.check-input.v1",Jx=2048,yw=D(Vx,{policy:fr,version:zd,limits:ut,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),zx=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Nw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],kw=["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"],Gx=new Set(kw);function mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vn(e,t,i){let 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 ei(e,t){if(typeof e!="string"||!Bx.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Sw(e,t){let i=pn(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function bw(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 Ux(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>Jx||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=gw.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||gw.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Kx(e){let t=mn(e,"Native check receipt checker");vn(t,["policy","version","hash","limits"],"Native check receipt checker");let i=mn(t.limits,"Native check receipt limits");if(vn(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==fr||t.version!==zd||t.hash!==yw||i.maxFiles!==ut.maxFiles||i.maxFileBytes!==ut.maxFileBytes||i.maxTotalBytes!==ut.maxTotalBytes||i.maxIssues!==ut.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:fr,version:zd,hash:yw,limits:{...ut}}}function Yx(e){let t=mn(e,"Native check receipt contract");return vn(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ei(t.expectedHash,"Native check expected contract hash"),beforeHash:ei(t.beforeHash,"Native check before contract hash"),afterHash:ei(t.afterHash,"Native check after contract hash")}}function Xx(e){let t=mn(e,"Native check receipt implementation");return vn(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ei(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:ei(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ei(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ei(t.afterSnapshotHash,"Native check after snapshot hash")}}function Qx(e){let t=mn(e,"Native check receipt counts");vn(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:pn(t.filesSelected,"Native check filesSelected"),filesScanned:pn(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:pn(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:pn(t.bytesScanned,"Native check bytesScanned"),issueCount:pn(t.issueCount,"Native check issueCount"),recordedIssueCount:pn(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>ut.maxFiles||i.bytesScanned>ut.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ut.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function Zx(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Nw.indexOf(e.kind)-Nw.indexOf(t.kind)}function eT(e){if(!Array.isArray(e)||e.length>ut.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=mn(n,`Native check issue ${r}`);if(vn(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!zx.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:Ux(a.path,`Native check issue ${r} path`),line:Sw(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(Zx);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function tT(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!Gx.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=kw.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 iT(e){return D(Wx,e)}function gc(e){let t=mn(e,"Native check receipt");if(vn(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==ww)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!qx.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Sw(t.sourceRevision,"Native check source revision"),n=Kx(t.checker),r=Yx(t.contract),a=Xx(t.implementation),o=iT({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ei(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=bw(t.startedAt,"Native check receipt startedAt"),c=bw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=Qx(t.counts),u=eT(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=tT(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>ut.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>ut.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:ww,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=ei(t.receiptHash,"Native check receipt content hash");if(D(Lx,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var Ud="comet.native.verification-receipt.v3",nT=Ud,rT="comet.native.declared-artifacts.v1",aT=/^[a-f0-9]{64}$/u,oT=/^acceptance-[a-f0-9]{64}$/u,sT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,lT=4096,uT=256,dT=1024;function hr(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 Mi(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 ti(e,t){if(typeof e!="string"||!aT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Et(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=St(e).trim();if(!i||i.length>lT||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Gd(e,t){let i=Et(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function za(e,t,i=Et,n=!1,r=uT){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 fT(e,t){if(typeof e!="string"||!oT.test(e))throw new Error(`${t} is invalid`);return e}function hT(e){let t=hr(e,"Native verification receipt bindings");if(Mi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!sT.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:ti(t.contractHash,"Native verification receipt contract hash"),scopeHash:ti(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:ti(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:ti(t.artifactHash,"Native verification receipt artifact hash")}}function pT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=cT.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function mT(e,t,i,n){let r=hr(t,`Native ${e} evidence`);if(e==="automated-check"){if(Mi(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=Gd(r.startedAt,"Native automated-check start time"),o=Gd(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=hr(r.worktree,"Native automated-check worktree");if(Mi(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=hr(r.afterFence,"Native automated-check after fence");if(Mi(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Et(r.executable,"Native automated-check executable"),args:za(r.args,"Native automated-check arguments",Et,!0),cwd:Et(r.cwd,"Native automated-check cwd"),exitCode:r.exitCode,signal:r.signal,timedOut:r.timedOut,timeoutMs:r.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Et(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:ti(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:ti(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:ti(r.outputHash,"Native automated-check output hash"),outputSummary:Et(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){Mi(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=pT(r.checkReceiptRef);if(ti(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:za(r.subjects,"Native static inspection subjects",Et,n==="required-check"),rule:Et(r.rule,"Native static inspection rule"),resultSummary:Et(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Mi(r,["steps","observations"],"Native manual-evidence evidence"),{steps:za(r.steps,"Native manual evidence steps"),observations:za(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function vT(e){let t=hr(e,"Native verification receipt");if(Mi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,n=t.role,r=t.status,a=Et(t.actor,"Native verification receipt actor"),o=za(t.acceptanceIds,"Native receipt acceptance IDs",fT,n==="required-check",dT).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:Ud,kind:i,role:n,status:r,bindings:hT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Gd(t.issuedAt,"Native verification receipt issue time"),evidence:mT(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==fr||s.actor!==`native-runtime:${fr}`))throw new Error("Native required check policy identity is invalid");return s}function wc(e){let t=hr(e,"Native verification receipt");if(Mi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Ud)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=vT(n),a=ti(t.receiptHash,"Native verification receipt hash");if(D(nT,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function Kd(e){return D(rT,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Pw=/^[a-f0-9]{64}$/u,Li=hn,mM=3*Li;function Yd(e,t){let i=Ft.relative(e,t);return i===""||!Ft.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ft.sep}`)}function wT(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ce(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ew(e){let t=await Rt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Rt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function yT(e,t){let i=Ft.resolve(e),n=Ft.resolve(t);if(!Yd(i,n))throw new Error("Native evidence path is outside its change");let r=[await Ew(i)],a=i;for(let o of Ft.relative(i,n).split(Ft.sep).filter(Boolean)){a=Ft.join(a,o);let s=await Ew(a);if(!Yd(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Rw(e){for(let t of e){let i=await Rt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!wT(t,i)||await Rt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function NT(e,t,i={}){let n=await yT(t,Ft.dirname(e));await i.afterParentChainCaptured?.();let r=await Rt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Rt.realpath(e);if(!Yd(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Rt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await Rw(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!yc(s,r)||!yc(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Li)throw new Error(`Native evidence document exceeds ${Li} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Li+1-d,b=await o.read(f,0,Math.min(f.length,v),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>Li)throw new Error(`Native evidence document exceeds ${Li} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Rt.lstat(e),Rt.realpath(e)]);if(await Rw(n),!m.isFile()||m.isSymbolicLink()||h!==a||!yc(s,p)||!yc(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 mr(e,t){if(!Pw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function Aw(e){return mr("reports",e)}async function bT(e,t,i,n,r){if(!Pw.test(i))throw new Error("Native report evidence hash is invalid");let a=await gn({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"||gT("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function pr(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function kT(e,t,i,n,r){return Ft.join(r??I(e,t),...mr(i,n).split("/"))}async function gn(e){let t=e.changeDir??I(e.paths,e.name),i=kT(e.paths,e.name,e.kind,e.hash,t);return await _(e.paths.nativeRoot,i),NT(i,t,e.hooks)}function Cw(e,t){return lr(e,t)}function ST(e,t){let i=ur(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function ET(e,t,i){let n=vc(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function RT(e,t,i){let n=Ja(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function CT(e,t,i,n=!1,r){let a=await Xd(e,t,i.implementationScopeRef,void 0,r);if(n&&await bT(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 xw(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 Ga(e,t,i,n,r){let a=pr(i,"scopes"),o=ST(await gn({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=pr(o.baselineProjectionRef,"snapshots"),c=pr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([gn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>Cw(d,s)),gn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>Cw(d,c))]);return uw({baseline:l,current:u,scope:o})}async function Xd(e,t,i,n,r){return(await Ga(e,t,i,n,r)).scope}async function xw(e,t,i,n,r){let a=pr(i,"allowances");return ET(await gn({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function Nc(e,t,i,n,r){let a=pr(i,"receipts"),o=wc(await gn({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 Ua(e,t,i,n,r){let a=pr(i,"verifications"),o=RT(await gn({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await CT(e,t,o,!1,r),o}var PT=4096;async function AT(e,t=Je.maxChanges){try{let i=await Ke({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 Tw(e,t){let i=await Ie(e,t),[n,r]=await Promise.all([i.implementation_scope?Xd(e,t,i.implementation_scope):null,Dt(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 bc(e,t,i={}){let r=(await AT(e,PT)).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 Tw(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await Tw(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Kg([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as JT}from"fs";import zT from"path";import{isDeepStrictEqual as cf}from"util";var vr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var xT=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function TT(e,t){return e<t?-1:e>t?1:0}function IT(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"||!xT.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(TT)}function Qd(e=[]){return IT(e,"Native repair failed check IDs",vr.maxFailedCheckIds,!0)}function Iw(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function _T(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Iw(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Iw(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Zd(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(_T(n,a))break;i+=1,n=a}return i}function ef(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 _w="repairStagnation",Ze={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},OT=/^[a-f0-9]{64}$/u;var $T=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),HT=["data","runId","sequence","timestamp","type"],jw=["disposition","overrideSummaryHash","signatureHash"],DT=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Ow=12;function nf(e,t){return e<t?-1:e>t?1:0}function $w(e,t,i){let n=Object.keys(e).sort(nf);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function kc(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 Ka(e,t){if(typeof e!="string"||!OT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function FT(e){if(!Array.isArray(e)||e.length>vr.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(nf)}function Hw(e){if(typeof e!="string"||e.length===0||e.length>Ze.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 tf(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Ze.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ze.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>Ze.maxTextCharacters&&(!r||e.length>Ze.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Ze.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>Ze.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>tf(s,t+1,i,`${n}[${c}]`));return}let a=kc(e,n),o=Object.keys(a);if(o.length>Ze.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ze.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ze.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");tf(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function MT(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 LT(e,t,i){let n=kc(e,`Native repair trajectory event ${t+1}`);if($w(n,HT,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(MT(n.timestamp),typeof n.type!="string"||!$T.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(Hw(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 tf(n.data,0,r,"Native trajectory event data"),kc(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function rf(e){let t=kc(e,"Native repair trajectory projection"),i=Object.keys(t).sort(nf),n=i.length===jw.length&&i.every((l,u)=>l===jw[u]);n||$w(t,DT,"Native repair trajectory projection");let r=Ka(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:Ka(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=Ka(t.contractHash,"Native repair trajectory contract hash"),s=FT(t.failedAcceptanceIds),c=Qd(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 BT(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 qT(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Ow;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Zd({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<vr.warningAtConsecutiveFailures?"continue":a<vr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function VT(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Ow;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 Dw(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ze.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Hw(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=LT(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ze.maxTotalDataNodes||c>Ze.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Ka(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Ka(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,_w)){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=rf(f[_w]);if(BT(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),qT(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");VT(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>vr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function Fw(e){return Dw(e).history}function Mw(e){let t=Dw(e).latestProjection;return t?{...t}:null}var Mt={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:[]},Ya=H("comet-native-runtime:v3:semantic-repair-budget"),WT=[{skillVersion:"2",skillHash:H("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:H("comet-native-runtime:v1")}];function Lw(e){return e.skillVersion===Mt.definition.metadata.version&&e.skillHash===Ya||WT.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var af={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Bi(e){let i={sequence:(await De(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await dg(e.changeDir,e.run.trajectoryRef,i),i}async function wn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:H(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await fg(e.changeDir,e.run.checkpointRef,t),t}function Bw(e){return H(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 Kw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],GT=new Set(Kw),Yw=new Set([...Kw,"minimum_runtime_version","revision"]),UT=new Set([...Yw,"operation"]),KT=512*1024,of=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),YT=new Set([...of,"implementationScopeHash","repairScopeHash","repairStagnation"]),Xa=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 je(e,t){return zT.join(I(e,t),"runtime","transition.json")}function XT(e){return`transition-${e}`}async function QT(e,t,i){let n=XT(t);return bi(e,n,i)}async function yn(e,t,i,n){let r=await QT(e,t,i);try{return await n()}finally{await ki(r)}}function Ec(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function lf(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 Sc(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Lt(e,t){return cf(e,t)}function sf(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=>!YT.has(u)),a=[...of].find(u=>!Object.hasOwn(i,u)),o=of.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(ef(i.summary,"Native transition journal event summary"),St(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&&(ef(i.noCodeReason,"Native transition journal event no-code reason"),St(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")?rf(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 ZT(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 sf({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return sf(e,t)}function uf(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?ZT(e.eventData,e.evidenceHash):sf(e.eventData,e.evidenceHash),r=ji(e.nextRun),a=e.previousRun===null?null:ji(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function qw(e,t,i=!1){if(e.skill!==Mt.definition.metadata.name||(i?!Lw(e):e.skillVersion!==Mt.definition.metadata.version||e.skillHash!==Ya)||e.orchestration!==Mt.definition.orchestration.mode||e.pendingRef!==Xe.pendingRef||e.trajectoryRef!==Xe.trajectoryRef||e.contextRef!==Xe.contextRef||e.artifactsRef!==Xe.artifactsRef||e.checkpointRef!==Xe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Vw(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 Ww(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 df(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(qw(a,"next Run",n||r!==null),Ww(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(qw(r,"previous Run",!0),Ww(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(!cf(Vw(r),Vw(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function eI(e,t,i){return H(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Xw(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Jw(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function ff(e,t,i,n,r=!1){let a=i.eventData,o=Jw(e),s=Jw(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&&cf(e.spec_changes,t.spec_changes),l=Bw({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=eI(e.name,a.summary,t.spec_changes),l=H(`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 hf(e,t){let i=Ec(e);if(lf(i,UT),i.schema!==$i)throw new Error(`Expected Native transition schema ${$i}`);let n=Sc(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 ${$i} minimum_runtime_version must be ${3}`);let r=Sc(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=uf(i,t),o=ct(i.previousState),s=ct(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(ff(o,s,a,i.operation),df(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:$i,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 tI(e,t){let i=Ec(e);if(lf(i,GT),i.schema!==ln)throw new Error(`Expected Native transition schema ${ln}`);let n=uf(i,t,!0),r=Fa(i.previousState),a=Fa(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return ff(r,a,n,Xw(r,a,n.eventData),!0),df(r,a,n,!0),{schema:ln,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 pf(e,t){let i=Ec(e);if(lf(i,Yw),i.schema!==Gt)throw new Error(`Expected Native transition schema ${Gt}`);if(Sc(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Gt} minimum_runtime_version must be 2`);let r=Sc(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=uf(i,t,!0),o=Hi(i.previousState),s=Hi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(ff(o,s,a,Xw(o,s,a.eventData),!0),df(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Gt,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 iI(e,t){let i=Ec(e);if(i.schema===$i)return{status:"current",journal:hf(i,t)};if(i.schema===ln)return{status:"migration-required",journal:tI(i,t)};if(i.schema===Gt)return{status:"migration-required",journal:pf(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function mf(e,t){let i=je(e,t);await _(e.nativeRoot,i);try{let n=await Z({root:e.nativeRoot,file:i,maxBytes:KT,label:`Native transition journal ${t}`});return iI(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ii(e,t){let i=await mf(e,t);if(!i)return null;if(i.status==="migration-required")throw new Xa(t);return i.journal}function zw(e,t){if(Lt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Lt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Gw(e,t){if(Lt(e,t.nextState))return"next";if(Lt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function nI(e){let{journal:t}=e;return Qw({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Qw(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Uw(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=nI({sequence:a.index+1,journal:t,type:a.event.type});if(!Lt(Qw(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function Rc(e,t,i){if(await ar(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await tc(e,t);let n=await ii(e,t);if(!n)return null;let r=I(e,t),a=Uw(await De(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([be(r),Ie(e,t)]),c=zw(o,n),l=Gw(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await cn(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Lt(await be(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await cc(e,n.nextState,n.previousState.revision);if(!Lt(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Lt(await Ie(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await ii(e,t);if(!u||!Lt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=Uw(await De(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await Bi({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let f=d.transitioned;f||(f=await Bi({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await wn({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([be(r),Ie(e,t)]);zw(p,{...n,previousRun:n.nextRun}),Gw(m,{...n,previousState:n.nextState});let h=await ii(e,t);if(!h||!Lt(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await JT.rm(je(e,t),{force:!0}),n.nextState}async function Zw(e,t,i){return xe(e,`continue transition ${t}`,()=>yn(e,t,`continue transition ${t}`,()=>Rc(e,t,i)))}import ey from"node:path";var rI="comet.native.acceptance.v1",aI=/^acceptance-[a-f0-9]{64}$/u,oI=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),sI=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,cI=/^[a-f0-9]{64}$/u,lI=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function uI(e,t){return e<t?-1:e>t?1:0}var ni=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Qa=Object.freeze({maxCriteria:1024}),ty="<!-- comet-native:acceptance-evidence:start -->",iy="<!-- comet-native:acceptance-evidence:end -->";function ny(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 ry(e,t){let i=t.toString(36),n=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function dI(e){if(!cI.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=lI.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]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function fI(e,t){let i=ny(e.text,ni.maxTextBytes),n=e.context.slice(0,ni.maxContextItems).map(r=>ny(r,ni.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 oy(e){let t=dI({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(uI),r=n.slice(0,ni.maxFailedCheckIds),a=e.criteria.slice(t,t+ni.maxItems);for(let c of a){let l=[...i,fI(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?ry(e.acceptanceHash,u):null,limits:{...ni}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ni.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?ry(e.acceptanceHash,o):null,limits:{...ni}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ni.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function wf(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 vf(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 ay(e){return e.includes("-->")||e.includes("--!>")}function*gr(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
193
- `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
194
- `,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=vf(l,t);else if(i)ay(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=vf(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!ay(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 hI(e){return[...gr(e)].map(({line:t,body:i})=>({line:t,body:i}))}function gf(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function pI(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function yf(e,t,i,n=[]){let r=gf(i),a=t.replaceAll("\\","/").trim(),o=n.map(gf);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-${D(rI,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function Nf(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 mI(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of gr(e)){r=s+1;let c=o?wf(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 sy(e,t="brief.md",i=Qa.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=mI(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of gr(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 gr(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(),Nf(a.map(c=>yf("brief-example",t,c.join(`
195
- `))),"Brief")}function cy(e,t="spec.md",i=Qa.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(yf("spec-scenario",t,[a.title,...a.body].join(`
196
- `),a.context)),a=null}};for(let{line:s,body:c}of gr(e)){let l=c?wf(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=gf(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(),Nf(n,"Specification")}function ly(e,t="spec.md",i=Qa.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(yf("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 gr(e)){let d=u?wf(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||vf(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(),Nf(n,"Specification mandatory requirements")}function vI(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||pI(i)||ey.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=ey.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(!sI.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function gI(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=>!oI.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function uy(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=gI(i,n),a=r.acceptance_id;if(typeof a!="string"||!aI.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 vI(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 dy(e){let t=hI(e);if(t.some(({line:l,body:u})=>!u&&(l===ty||l===iy)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===ty?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===iy?[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(`
197
- `).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=uy(o),c=wI(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function wI(e){let t=uy([...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 fy from"node:path";var yI="comet.native.contract.v1",NI="comet.native.acceptance-set.v1",hy=/^[a-f0-9]{64}$/u,Za={maxAcceptanceCriteria:Qa.maxCriteria};function py(e,t){let i=fy.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})||fy.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 my(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
198
- `))}function bI(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(hy))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(hy))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=py(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:my(e.markdown)},markdown:e.markdown}}function kI(e,t){return vy(e.id,t.id)}function vy(e,t){return e<t?-1:e>t?1:0}function gy(e){let t=py(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(bI).sort((d,f)=>vy(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=sy(e.briefMarkdown,t,Za.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...cy(f,d.source,Za.maxAcceptanceCriteria-a.length)),a.push(...ly(f,d.source,Za.maxAcceptanceCriteria-a.length)));if(a.sort(kI),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Za.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Za.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:my(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(NI,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(yI,u)}}var Cc={maxSpecs:64,maxFileBytes:aa,maxTotalBytes:4*1024*1024};async function wr(e){if(e.specChanges.length>Cc.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await $e({root:e.changeDir,ref:e.briefRef,maxBytes:Cc.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 $e({root:e.changeDir,ref:r.source,maxBytes:Cc.maxFileBytes});if(i+=a.size,i>Cc.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:gy({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as MI,spawn as eL}from"node:child_process";import{promisify as LI}from"node:util";import{promises as xI}from"fs";import yr from"path";var Vi={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Nr=/^[a-f0-9]{64}$/u;function Pc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ac(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 qi(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 wy(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function bf(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function SI(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||yr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=yr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function kf(e,t){return yr.join(I(e,t),"runtime","checkpoints","progress.json")}function Wi(e,t){return yr.join(I(e,t),"runtime","checkpoint-journal.json")}function Sf(e,t,i){if(!Nr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return yr.join(I(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function EI(e){if(!Nr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Ef(e,t,i){let n=await Z({root:e,file:t,maxBytes:Vi.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function RI(e,t){let i=Pc(e,`checkpoint manifest artifact ${t}`);Ac(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=SI(qi(i.path,`checkpoint artifact ${t} path`,4096)),r=It(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Nr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:bf(i.size,`checkpoint artifact ${t} size`)}}function xc(e,t){let i=Pc(e,"Native checkpoint manifest");if(Ac(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>Vi.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(RI),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=bf(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>Vi.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 Rf(e){return H(JSON.stringify(xc(e,e.change)))}function Cf(e,t){let i=Pc(e,"Native progress checkpoint");if(Ac(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=wy(i.previousRevision,"Native checkpoint previousRevision"),a=wy(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=qi(i.manifestHash,"Native checkpoint manifestHash",64);if(!Nr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=EI(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=qi(i.inputHash,"Native checkpoint inputHash",64);if(!Nr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=qi(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=bf(i.artifactCount,"Native checkpoint artifactCount");if(u>Vi.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=qi(i.summary,"Native checkpoint summary"),f=qi(i.nextAction,"Native checkpoint nextAction");if(St(d)!==d||St(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:qi(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 CI(e,t){let i=Pc(e,"Native checkpoint journal");if(Ac(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=ct(i.previousState),r=ct(i.nextState),a=Cf(i.checkpoint,t),o=xc(i.manifest,t),s=qi(i.inputHash,"Native checkpoint journal inputHash",64),c=H(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Nr.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!==Rf(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 PI(e,t,i){let n=yr.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,n)||q(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=Hu(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await Z({root:e.projectRoot,file:n,maxBytes:Vi.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 AI(e,t){let i=kf(e,t);await _(e.nativeRoot,i);try{return Cf(await Ef(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Pf(e,t,i){let n=Sf(e,t,i);await _(e.nativeRoot,n);let r=await Ef(e.nativeRoot,n,"Native checkpoint manifest"),a=xc(r,t);if(Af(e,a),Rf(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Ji(e,t){let i=Wi(e,t);await _(e.nativeRoot,i);try{let n=CI(await Ef(e.nativeRoot,i,"Native checkpoint journal"),t);return Af(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function yy(e,t,i,n){let r=xc(i,t);Af(e,r);let a=Rf(r),o=Sf(e,t,a);await _(e.nativeRoot,o);try{let s=await Pf(e,t,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await ve(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Af(e,t){for(let i of t.artifacts){let n=Hu(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Ny(e,t){let i=Cf(t,t.change),n=await Pf(e,i.change,i.manifestHash),r=H(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=kf(e,t.change);await _(e.nativeRoot,a),await ve(a,i,{containedRoot:e.nativeRoot})}async function by(e){let t;try{t=await AI(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:kf(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 Pf(e.paths,e.name,t.manifestHash);let a=H(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 PI(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:Sf(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}async function ky(e,t,i){let n=await Ji(e,t);if(!n)return null;if(await yy(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await cc(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Ny(e,n.checkpoint),await i?.afterProgressWritten?.(n),await xI.rm(Wi(e,t),{force:!0}),n}async function Sy(e,t,i){return xe(e,`continue checkpoint ${t}`,()=>yn(e,t,`continue checkpoint ${t}`,async()=>(await Rc(e,t),ky(e,t,i))))}import{constants as xf,promises as dt}from"node:fs";import Nn from"node:path";var TI=/^[a-f0-9]{64}$/u,II=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,eo=512*1024;function _I(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Tc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ce(i,n)?M(i,n):M(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function jI(e,t){let i=Nn.resolve(e),n=Nn.resolve(t);if(!q(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...Nn.relative(i,n).split(Nn.sep).filter(Boolean)]){o&&(a=Nn.join(a,o));let s=await dt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await dt.realpath(a);if(r.length>0&&!q(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 Ey(e){for(let t of e){let i=await dt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!_I(t,i)||await dt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function OI(e){if(!TI.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function $I(e){let t=II.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function HI(e,t,i){return Nn.join(I(e,t),...OI(i).split("/"))}async function DI(e,t,i){let n=await jI(i,Nn.dirname(e)),r=await dt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>eo)throw new Error(`Native check receipt exceeds ${eo} bytes`);let[a,o]=await Promise.all([dt.realpath(t),dt.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":xf.O_RDONLY|xf.O_NOFOLLOW|xf.O_NONBLOCK,c=await dt.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(),dt.lstat(e),dt.realpath(e)]);if(await Ey(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Tc(r,l)||!Tc(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=eo+1-p,k=await c.read(m,0,Math.min(m.length,N),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>eo)throw new Error(`Native check receipt exceeds ${eo} bytes`);f.push(Buffer.from(m.subarray(0,k.bytesRead)))}let[h,v,b]=await Promise.all([c.stat(),dt.lstat(e),dt.realpath(e)]);if(await Ey(n),!v.isFile()||v.isSymbolicLink()||b!==o||!q(a,b)||!Tc(l,h)||!Tc(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function Ry(e,t,i){let n=$I(i),r=I(e,t),a=HI(e,t,n);await _(e.nativeRoot,a);let o=gc(await DI(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var to=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var mL=64*1024;var vL=3600*1e3;var gL=LI(MI);var wL=["$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 BI=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Cy(e,t){let i=[];for(let n of BI){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 Py(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Ry(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 zi=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 qI(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 VI(e){let t=qI(e.bundle.baseline),i=await wd(e.paths,t,{origin:"explicit",now:e.now});return qd({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function xy(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Ga(e.paths,e.state.name,e.state.implementation_scope),i=await wr({changeDir:I(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await VI({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 Ty(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await xy(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 WI(e){let t=await $e({root:I(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:dy(t.text)}}function JI(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 zI(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:Kd(e.implementationScope.scope.declaredArtifacts)}}async function Ay(e){let t=await Nc(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Cy(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 zi([{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 Py({paths:e.paths,state:e.state,receipt:t});if(r){let a=JI({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 GI(e){let t=zI({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Ay({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof zi)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 Ay({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof zi)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 zi(i)}function Tf(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ic(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Tf(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([xy(e),Ua(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:Tf(e.state.verification_result,"stale"),envelope:null};let n=await WI({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 GI({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:Tf(e.state.verification_result,"invalid"),envelope:null}}}function KI(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function _y(e){try{return await UI.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function YI(e,t){try{return(await $e({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function XI(e,t,i){let n=lc(e,i.capability);if(!q(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=Iy.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await YI(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await $e({root:I(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 QI(e,t){return _y(je(e,t))}async function _c(e){let t=e.now??new Date,i=await Ie(e.paths,e.name),n=await Dt(e.paths,e.name),r=await We(e.paths.projectRoot),a=KI(i.name,t),o=Iy.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(m=>XI(e.paths,i.name,m))),Ic({paths:e.paths,state:i,now:t}),bc(e.paths,i.name),ar(e.paths,i.name),or(e.paths,i.name),QI(e.paths,i.name),_y(o)]);return Vg({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]})}import{promises as If}from"node:fs";import ri from"node:path";var ZI="comet.native.archive-tree.v1",e_={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function $y(e){let t={...e_,...e};for(let[i,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function jy(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function Oy(e,t,i,n){if(i.entryCount+=1,i.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>n.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${n.maxRefBytes} bytes: ${t.ref}`);let r=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=r+(e.length===0?0:1),i.manifestBytes+2>n.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${n.maxManifestBytes} bytes`);e.push(t)}async function Hy(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await Ke({root:e,directory:t,label:`Native Archive content directory ${ri.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=jy(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=ri.join(t,u.name),f=ri.relative(e,d).replaceAll("\\","/"),p=await If.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){Oy(i,{ref:f,kind:"directory"},n,r),await Hy(e,d,i,n,r,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await Z({root:e,file:d,maxBytes:r.maxFileBytes,label:`Native Archive content file ${f}`});if(n.totalBytes+=m.size,n.totalBytes>r.maxTotalBytes)throw new Error(`Native Archive content exceeds ${r.maxTotalBytes} total file bytes`);Oy(i,{ref:f,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await Ke({root:e,directory:t,label:`Native Archive content directory ${ri.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(jy(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${ri.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function Dy(e,t={}){let i=$y(t);e=ri.resolve(e);let n=await If.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await Hy(e,e,r,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(r);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return H(`${ZI}\0${o}`)}async function Ct(e,t={}){let i=$y(t);e=ri.resolve(e);let n;try{n=await If.lstat(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await Z({root:ri.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${ri.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await Dy(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Fe}from"node:fs";import ue from"node:path";var jf=16*1024*1024,t_=256*1024,i_=16*1024,io="comet.native.archive-cas.v1";function n_(e,t){let i=ue.resolve(e.nativeRoot,...t.split("/"));if(ue.relative(e.nativeRoot,i).split(ue.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function Ee(e,t){return _(e.nativeRoot,n_(e,t))}function Gi(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function br(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ze(e){let t=await Ct(e.target);if(!Gi(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${br(t)}`);return t}async function Of(e,t){let i=await $t(e,t),n=await Z({root:e.nativeRoot,file:i.journal,maxBytes:t_,label:`Native Archive transaction journal ${t}`}),r=Fs(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function jc(e,t,i){let n=Fs({...t,status:i}),r=await $t(e,n.id);return await ve(r.journal,n,{containedRoot:e.nativeRoot}),n}function Oc(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function Fy(e){return{...Oc(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ui(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function r_(e,t){return Ui(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function X(e){try{return await Fe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bt(e){let t=await Fe.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=Fy(t),n=await Z({root:e.paths.nativeRoot,file:e.file,maxBytes:jf,label:e.label}),r=await Fe.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!r_(i,Fy(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Oc(r),size:n.size}}function a_(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let r=e;if(Object.keys(r).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=r.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(r.schema!==io||r.operationId!==t.id||r.role!==i||r.hash!==n)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:io,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function qt(e,t,i,n){let r=await $t(e,t.id),a=ue.join(r.backups,".cas"),o=`.${ue.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:ue.join(a,`${i.id}.original.json`),postRecord:ue.join(a,`${i.id}.post.json`),candidate:ue.join(a,`${i.id}.candidate`),originalQuarantine:ue.join(ue.dirname(n),`${o}.original`),rollbackQuarantine:ue.join(ue.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>_(e.nativeRoot,c))),s}async function ft(e){if(!await X(e.file))return null;let t=await Z({root:e.paths.nativeRoot,file:e.file,maxBytes:i_,label:`Archive CAS ${e.operation.id} ${e.role} record`});return a_(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function $c(e){let t=await ft(e);if(t){if(!Ui(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Ot({root:e.paths.nativeRoot,directory:ue.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:io,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ve(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await ft(e);if(!n||!Ui(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function pe(e){let t=await Bt({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Ui(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function o_(e){let t=await Bt({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await $c({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await pe({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function s_(e){if(!await X(e.quarantine)||await X(e.target))return;let t=await Ri({root:e.paths.nativeRoot,directory:ue.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Fe.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([Fe.lstat(e.quarantine),Fe.lstat(e.target)]);if(!Ui(Oc(i),Oc(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Fe.unlink(e.quarantine),await t.verify()}async function qy(e){if(await X(e.quarantine)){await pe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Ri({root:e.paths.nativeRoot,directory:ue.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await pe({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await pe({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Fe.rename(e.target,e.quarantine),await t.verify(),await pe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await s_(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function bn(e){if(!await X(e.file))return;await pe(e);let t=await Ri({root:e.paths.nativeRoot,directory:ue.dirname(e.file),label:e.label});await t.verify(),await pe(e),await Fe.unlink(e.file),await t.verify()}async function My(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await Ee(e,t.target),r=await Ee(e,t.backup),a=await Ct(r);if(a!==null){if(!Gi(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ze({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ci({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:jf,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ze({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function Vy(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await qt(e.paths,e.journal,e.operation,e.target),n=await ft({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await X(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await pe({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await My(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await X(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await o_({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await pe({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await My(e.paths,e.operation,e.hooks),await qy({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:i.originalQuarantine}}async function Ly(e){let t=await qt(e.paths,e.journal,e.operation,e.target);return await X(t.candidate)?(await Bt({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Ot({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ci({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:jf,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function c_(e){let t=e.operation.stagedHash,i=await qt(e.paths,e.journal,e.operation,e.target),n=await ft({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await X(e.target))return await pe({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await X(i.candidate)&&await bn({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await X(e.target)){let c=await Ly(e),l=await Bt({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Bt({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ui(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await $c({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await bn({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await Ly(e),a=await Bt({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Ot({root:e.paths.nativeRoot,directory:ue.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Ri({root:e.paths.nativeRoot,directory:ue.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await pe({paths:e.paths,file:r,operation:e.operation,record:{schema:io,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Fe.link(r,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Bt({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ui(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await $c({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await bn({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function l_(e,t,i,n){let r=await Ee(e,i.target),a=await Ee(e,i.staged);if(await ze({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await qt(e,t,i,r);(!await ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await X(r))&&await Vy({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await Ct(r);if(o!==null&&!Gi(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${br(o)}`)}await c_({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await ze({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function u_(e,t,i,n){let r=await Ee(e,i.target);await Vy({paths:e,journal:t,operation:i,target:r,hooks:n}),await ze({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function d_(e,t){let i=await Ee(e,t.source),n=await Ee(e,t.target),[r,a]=await Promise.all([Ct(i),Ct(n)]);if(!(r===null&&Gi(a,t.expectedSourceHash,"directory"))){if(!Gi(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${br(r)}, target=${br(a)}`);await Fe.mkdir(ue.dirname(n),{recursive:!0}),await Fe.rename(i,n),await ze({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function f_(e,t,i,n){return i.type==="write"?l_(e,t,i,n):i.type==="remove"?u_(e,t,i,n):d_(e,i)}function h_(e){let t=0,i=!1,n=[];for(let r of e.events){if(r.type!=="operation-started"&&r.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||r.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(r.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(a.id),t+=1,i=!1}return n}async function p_(e,t,i,n){let r=await Ee(e,i.target);if(i.type==="write"){let a=await Ee(e,i.staged);await ze({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await qt(e,t,i,r),s=await ft({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await pe({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ze({target:await Ee(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await ft({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await X(o.originalQuarantine))await pe({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ze({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ze({target:await Ee(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await qt(e,t,i,r),o=await ft({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await X(a.originalQuarantine))await pe({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}n||(await ze({target:await Ee(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ze({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function Wy(e,t,i){let n=t.status==="prepared"?await jc(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await Ai(e,n.id),a=h_({journal:n,events:r}),o=new Set(a),s=r.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,a.length))await p_(e,n,l,s);let c=o.size;for(let l of n.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await rt(e,n.id,"operation-started",l.id),await f_(e,n,l,i),await rt(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await Of(e,n.id),n}async function m_(e){try{return await pe(e),!0}catch{return!1}}async function v_(e){await pe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Ri({root:e.paths.nativeRoot,directory:ue.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await pe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Fe.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await pe({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function _f(e){if(e.operation.type!=="write")return;let t=await qt(e.paths,e.journal,e.operation,e.target);if(!await X(t.candidate))return;let i=await Bt({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await bn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:io,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function g_(e,t,i,n){let r=await Ee(e,i.target),a=await qt(e,t,i,r),o=i.expectedTargetHash,s=o===null?null:await ft({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await ft({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await X(a.candidate)&&await X(r)){let l=await Bt({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Bt({paths:e,file:r,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Ui(l.identity,u.identity)&&(c=await $c({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await X(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await pe({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await X(r)&&!(s!==null&&await m_({paths:e,file:r,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Ct(r);if(Gi(u,o)){await _f({paths:e,journal:t,operation:i,target:r});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await qy({paths:e,operation:i,phase:"rollback",target:r,quarantine:a.rollbackQuarantine,record:c,hooks:n})}if(o===null){if(await X(r))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await X(r)){if(!s||!await X(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await v_({paths:e,operation:i,target:r,quarantine:a.originalQuarantine,record:s,hooks:n})}s&&await X(a.originalQuarantine)&&await bn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await X(a.rollbackQuarantine)&&await bn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await _f({paths:e,journal:t,operation:i,target:r}),await ze({target:r,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function w_(e,t){let i=await Ee(e,t.source),n=await Ee(e,t.target),[r,a]=await Promise.all([Ct(i),Ct(n)]);if(!(Gi(r,t.expectedSourceHash,"directory")&&a===null)){if(r!==null||!Gi(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${br(r)}, target=${br(a)}`);await Fe.mkdir(ue.dirname(i),{recursive:!0}),await Fe.rename(n,i)}}async function Jy(e,t,i){let n=await Ai(e,t.id);if(n.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await jc(e,t,"rolling-back");await rt(e,r.id,"rollback-started");let a=new Set(n.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...r.operations].reverse())a.has(o.id)&&(o.type==="move"?await w_(e,o):await g_(e,r,o,i));return await rt(e,r.id,"rollback-completed"),r=await jc(e,r,"rolled-back"),r}async function By(e,t,i){let n=await Ee(e,i.target);if(i.type==="write"){let r=await qt(e,t,i,n),a=await ft({paths:e,file:r.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await pe({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ze({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function y_(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await Ee(e,i.target),r=await qt(e,t,i,n);if(await X(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await By(e,t,i),i.expectedTargetHash!==null){let a=await ft({paths:e,file:r.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await X(r.originalQuarantine)&&await bn({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await _f({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await By(e,t,i)}async function Hc(e,t,i){return i==="commit"&&await y_(e,t),await rt(e,t.id,i),i==="commit"?jc(e,t,"committed"):t}import{promises as N_}from"fs";import b_ from"path";var $f="comet.selection.v2",k_=16*1024;function Dc(e){return b_.join(e,".comet","current-change.json")}function S_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zy(e){return e===null||typeof e=="string"}function E_(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(!S_(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&&!zy(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:$f,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==$f)throw new Error(`current change selection schema must be ${$f}`);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(!zy(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Hf(e){let t;try{let n=Dc(e),{bytes:r}=await rn(n,k_,{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",...E_(t)}}async function Gy(e){await N_.rm(Dc(e),{force:!0})}async function Uy(e,t,i){let n=await Hf(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await Gy(e),!0)}var gB=16*1024;async function Fc(e){let t=await Hf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(oc(t.selection.change),t.selection)}function Ky(e){return Dc(e.projectRoot)}async function Yy(e,t){return await Bn(e.projectRoot),Uy(e.projectRoot,"native",t)}var VB=16*1024*1024,Mc=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"},no=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"};function Xy(e,t){let i=t.operations.find(n=>n.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return kr.resolve(e.nativeRoot,...i.target.split("/"))}async function Qy(e,t,i){let n=await Ai(e,t.id);if(n.some(h=>h.type==="archive-finalized"))return;let r=n.some(h=>h.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!r){let h=t.operations.find(b=>b.id==="archive-change");if(!h||h.type!=="move"||!h.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await Ct(Xy(e,t));if(v?.kind!=="directory"||v.hash!==h.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Xy(e,t),o=kr.join(a,Se),s=await $g(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await be(a);if(!c||c.runId!==s.run_id||c.currentStep!=="archive"&&!(c.currentStep===null&&c.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let l=c;if(c.currentStep==="archive"){let h=th(Mt,c,new Set,af,void 0);if(!h.action)throw new Error(h.reason??"Native archive produced no action");l=ih(Mt,h.state,{actionId:h.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},af,void 0)}let u=H(`archive:${t.id}:${s.name}`),d=await De(a,l.trajectoryRef),f=d.filter(h=>h.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(f.length>1||f.some(h=>h.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let p=f.find(h=>h.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:u,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(p&&t.schema==="comet.native.transaction.v2"&&(!R_(p.data,m)||p.runId!==l.runId||p.timestamp!==t.createdAt||p!==d.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!r&&(s.archived||c.currentStep===null||f.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(r||(t.schema==="comet.native.transaction.v2"?(await Hc(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Gn(e,t,"archive-finalization-started")),!s.archived){let h={...s,archived:!0};await Og(o,h)}p||(p=await Bi({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await wn({changeDir:a,run:l,trajectoryOffset:p.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await cn(a,l),await Yy(e,s.name),t.schema==="comet.native.transaction.v2"?await Hc(e,t,"archive-finalized"):await Gn(e,t,"archive-finalized")}async function C_(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Ai(e,t.id)).some(o=>o.type==="operation-started")){let o=await _c({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new no(o,"Native Archive facts changed before the first transaction operation")}let a=await Wy(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await Ie(e,t.change),c=await Ic({paths:e,state:s,now:new Date(t.createdAt)});if(s.phase!=="archive"||s.archived||s.verification_result!=="pass"||!["complete","partial"].includes(c.freshness)||c.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${c.findingCodes.join(", ")||c.freshness}`)}});return await Qy(e,a,i),Hc(e,a,"commit")}let n=await _v(e,t);return await Qy(e,n,i),Gn(e,n,"commit")}function P_(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(kr.resolve(t.projectRoot)!==kr.resolve(e.projectRoot)||kr.resolve(t.nativeRoot)!==kr.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Zy(e){return xe(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await bi(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await Ye(e.paths,e.transactionId),n=i.schema==="comet.native.transaction.v2"?await Of(e.paths,e.transactionId):i;return P_(e.paths,n),n.status==="committed"||n.status==="rolled-back"?n:e.strategy==="continue"?C_(e.paths,n):n.schema==="comet.native.transaction.v2"?Jy(e.paths,n):Ls(e.paths,n)}finally{await ki(t)}},{allowedTransactionId:e.transactionId})}import{promises as M_}from"fs";import A_ from"path";function Df(e,t){return A_.resolve(e,...t.split(/[\\/]/u))}async function eN(e,t){let i=[],n=I(e,t.name),r=Df(n,Xe.stateRef),a;try{a=await be(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=Df(n,a.trajectoryRef),s=await tr(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 De(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=Df(n,a.checkpointRef);try{let u=await er(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}var x_=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function T_(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 tN(e){let i=(e.findings??[]).filter(u=>!ir(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||x_.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:T_(e.state)}}import ro from"path";var iN=8,I_={"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 __(e){let t=I_[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"}:ir(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 j_(e,t,i){if(!i.path)return null;let n;if(ro.isAbsolute(i.path)?n=ro.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=ro.resolve(I(e,t.name),...i.path.split(/[\\/]/u)):n=ro.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!q(e.projectRoot,n))return null;let r=ro.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function O_(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 nN(e){return e.findings.map(t=>{let i=__(t.code);return{code:t.code,message:t.message,severity:i.severity,path:j_(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:O_(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 rN(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,iN),truncated:t.length>iN}}import aN from"path";var oN=240,sN=8,Lc=50;function cN(e){let t=Array.from(e);return t.length<=oN?e:`${t.slice(0,oN-1).join("")}…`}function $_(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function H_(e){let t=[...new Set(e.map($_))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,sN),reasonCount:e.length,codesTruncated:t.length>sN};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Lc),reasonsTruncated:e.length>Lc}}}async function lN(e){let t=null;try{let s=await Ji(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Wi(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:Wi(e.paths,e.state.name)}}let i=await by({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=H_(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Vi.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:cN(i.checkpoint.summary),nextAction:cN(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:aN.relative(e.paths.projectRoot,aN.join(I(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:Vi.maxArtifacts}}async function D_(e,t){let i=I(e,t.name),n=await be(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 er(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 De(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function F_(e,t){let i=await D_(e,t);return{committed:i,latest:Mw(i),history:Fw(i)}}async function uN(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await F_(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 L_=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Sr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function B_(e){return(await Fc(e))?.change??null}function q_(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 V_(e,t){let i=I(e,t.name),n=[...(await Id(i,t.brief)).findings,...(await Lg(e,t)).findings,...await eN(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await Zn(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 Gs(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 wr({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 ii(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 _d(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 Ff(e,t,i){let n=await B_(e)===t,r;try{let w=await lt(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 lN({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await uN(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 wr({changeDir:I(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),g=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let E=await Ua(e,r.name,r.verification_evidence);for(let j of E.acceptanceTrace.entries)g.set(j.acceptanceId,j.status==="failed"?"failed":j.status==="missing"?"missing":"satisfied")}c=oy({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:g,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 bc(e,r.name,{tolerateInvalidSiblings:!0});l.push(...w.findingCodes.map(g=>({code:g,message:`Native change overlap is visible in the current root: ${g}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let w=await Dt(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let g=await ja({paths:e,identity:w});g.state==="drifted"&&g.code&&u.push({code:g.code,message:g.message??"Native workspace binding is no longer valid"})}else{let g=await _a({paths:e,identity:w});u.push(...g.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${g.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 Ty({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.findingCodes.map(g=>({code:g,message:`Native Verify implementation scope is not current: ${g}`})))}let p=null,m=[];if(r.phase==="archive")try{p=await _c({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 V_(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,g,E)=>E.findIndex(j=>j.code===w.code&&j.path===w.path)===g),v=nN({paths:e,state:r,findings:h}),b=v.filter(w=>!ir(w.code)),N=r.phase==="archive"&&p?.ready===!0&&b.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)),S=v.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=v.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:S||R?null:q_(r,N,k,i?.clarificationMode),archiveReady:N,inspection:a.inspection,findingSummary:rN(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:tN({state:r,findings:v,archiveReady:N,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:v.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Lc,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:v.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}async function W_(e){let t;try{t=await Ri({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await M_.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>Sr.maxChanges))throw new Error(`Native status exceeds ${Sr.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function dN(e,t){let i=t.toString(36),n=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function J_(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=L_.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let n=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==n)throw new Error("Native status cursor integrity check failed");return i}async function z_(e,t){let i=await W_(e),n=D("comet.native.status-names.v1",i),r=J_({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+Sr.maxItems).map(c=>Ff(e,c,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let c of a){let l=[...o,c],u=r+l.length,d={schema:"comet.native.status-page.v1",total:i.length,offset:r,items:l,nextCursor:u<i.length?dN(n,u):null,limits:{...Sr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Sr.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(c)}let s=r+o.length;return{schema:"comet.native.status-page.v1",total:i.length,offset:r,items:o,nextCursor:s<i.length?dN(n,s):null,limits:{...Sr}}}async function Mf(e,t){return(await z_(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as dj,randomUUID as fj}from"node:crypto";import{constants as Wf,promises as U}from"node:fs";import re from"node:path";var Vc=po(ra(),1);import{randomUUID as G_}from"crypto";import{promises as vN}from"fs";import Bf from"path";import{isDeepStrictEqual as qf}from"util";var kn=/^[a-f0-9]{64}$/u,U_=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),K_=new Set(["sourceHash","targetHash","nextJournal"]),Y_=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),fN=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),X_=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Bc(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function hN(e){return JSON.stringify(e,null,2)+`
199
- `}function Vf(e){return e.schema===we?sc(e):un(e)}function Lf(e,t){return{...e,schema:we,minimum_runtime_version:2,revision:t}}function Q_(e){return{...e,schema:Gt,minimum_runtime_version:2,revision:1,previousState:Lf(e.previousState,1),nextState:Lf(e.nextState,2)}}function qc(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:ge,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function Z_(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?H(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:$i,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:qc(e.previousState),nextState:{...qc(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Mt.definition.metadata.version,skillHash:Ya}:e.nextRun}}function pN(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Er(e,t){return JSON.stringify(sc(e))===JSON.stringify(sc(t))}function mN(e,t){return JSON.stringify(un(e))===JSON.stringify(un(t))}function ai(e,t){return qf(e,t)}function ej(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let r=e;if(Bc(r,Y_,"Schema migration transition supersede plan"),typeof r.sourceHash!="string"||!kn.test(r.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof r.transitionId!="string"||r.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof r.evidenceHash!="string"||!kn.test(r.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=ji(r.previousRun),o=ji(r.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!ai(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!r.eventData||typeof r.eventData!="object"||Array.isArray(r.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=r.eventData,u=Object.keys(l);if(u.length!==fN.size||u.some(f=>!fN.has(f))||l.fromSchema!==we||l.toSchema!==ge||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==r.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=H(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:r.transitionId,migrationId:n,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(r.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:r.sourceHash,transitionId:r.transitionId,previousRun:a,nextRun:o,evidenceHash:r.evidenceHash,eventData:l}}function ao(e,t){return Bf.join(I(e,t),"runtime","schema-migration.json")}function tj(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Bc(e,U_,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let n=i.fromSchema===st&&i.toSchema===we,r=i.fromSchema===we&&i.toSchema===ge;if(!n&&!r)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!kn.test(i.sourceHash)||typeof i.targetHash!="string"||!kn.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=n?Hi(i.nextState):ct(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(H((0,Vc.stringify)(Vf(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Bc(i.transition,K_,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!kn.test(l.sourceHash)||typeof l.targetHash!="string"||!kn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=n?pf(l.nextJournal,t):hf(l.nextJournal,t);if(H(JSON.stringify(l.nextJournal,null,2)+`
200
- `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(n&&a.schema===we?Er(a,u.previousState)||Er(a,u.nextState):a.schema===ge&&(mN(a,u.previousState)||mN(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(n&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!r||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==ge)throw new Error("Schema migration transition supersede target schema is invalid");s=ej(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!r||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Bc(i.runRetreat,X_,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=ji(l.previousRun),d=ji(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!kn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==ge||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function oo(e,t){let i=ao(e,t);await _(e.nativeRoot,i);try{let n=await js({root:e.nativeRoot,file:i,maxBytes:524288,label:"Native schema migration journal"});return tj(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ij(e,t,i){let n=await Zn(e,t),r=n?await Gs(e,n):await Us(e,{now:new Date(i),origin:"legacy-migration"});if(!r.complete){let a=vd(r),o=r.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=r.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new rr(t,r.omittedCount,o,a.samplePaths,a.sampleTruncated)}n===null&&await yd(e,t,r)}async function gN(e){try{return await Nt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function nj(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function wN(e,t){let i=t.transitionSupersede,n=I(e,t.change),r=await De(n,i.nextRun.trajectoryRef),a=r.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!qf(o.event,nj(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:r.length,sequence:o?.event.sequence??null}}async function rj(e,t,i){if(!t.transitionSupersede)return;let n=je(e,t.change),r=await gN(n);if(r===t.transitionSupersede.sourceHash)return;if(r!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${r}`);let a=await be(I(e,t.change)),o=await wN(e,t),s=await er(I(e,t.change),t.transitionSupersede.nextRun.checkpointRef);if(!i||!a||!ai(a,t.transitionSupersede.nextRun)||o.sequence===null||!s||s.runId!==t.transitionSupersede.nextRun.runId||s.stateVersion!==t.transitionSupersede.nextRun.iteration||s.trajectoryOffset!==o.sequence||s.contextHash!==null||s.artifactsHash!==H(t.transitionSupersede.evidenceHash)||s.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function aj(e,t,i){let n=t.transitionSupersede;if(!n)return;let r=I(e,t.change),a=await be(r);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ai(a,n.nextRun)){if(!ai(a,n.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await cn(r,n.nextRun),await i?.afterRunStateWritten?.(t)}if(!ai(await be(r),n.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await wN(e,t);if(o.sequence===null){let l=await Bi({changeDir:r,run:n.nextRun,type:"state_migrated",data:{...n.eventData,migrationId:t.id,evidenceHash:n.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await wn({changeDir:r,run:n.nextRun,trajectoryOffset:o.sequence,evidenceHash:n.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=je(e,t.change),c=await gN(s);if(c!==null){if(c!==n.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await vN.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function oj(e,t,i){if(!t.runRetreat)return;let n=I(e,t.change),r=await be(n);if(!r)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ai(r,t.runRetreat.nextRun)){if(!ai(r,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await cn(n,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await De(n,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Bi({changeDir:n,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await wn({changeDir:n,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function sj(e,t,i){let n=await oo(e,t);if(!n)return null;if(await or(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=Bf.join(I(e,t),Se),a=await Nt(r);if(await rj(e,n,a===n.targetHash),await ij(e,t,n.createdAt),a!==n.targetHash){if(a!==n.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${n.sourceHash}, actual ${a}`);await Ve(r,(0,Vc.stringify)(Vf(n.nextState))),await i?.afterStateWritten?.(n)}if(n.transition){let o=je(e,t),s=await Nt(o);if(s!==n.transition.targetHash){if(s!==n.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${n.transition.sourceHash}, actual ${s}`);await ve(o,n.transition.nextJournal),await i?.afterTransitionWritten?.(n)}}return await aj(e,n,i),await oj(e,n,i),await vN.rm(ao(e,t),{force:!0}),n.nextState}async function cj(e){let t=I(e.paths,e.state.name),i=await be(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let n={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},r=H(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:n,evidenceHash:r,eventData:{fromSchema:we,toSchema:ge,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function lj(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let r=Er(i,t.previousState),a=Er(i,t.nextState);if(!r&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=I(e.paths,i.name),s=await be(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&ai(s,t.previousRun),l=ai(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await De(o,t.nextRun.trajectoryRef)).map((b,N)=>({event:b,index:N})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!qf(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...qc(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=H(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await Nt(je(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:h,evidenceHash:v,eventData:{fromSchema:we,toSchema:ge,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function uj(e){let t,i,n,r;if(e.state.schema===st){if(t=Lf(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==ln)throw new Error("Native v1 change has a transition from another schema generation");let s=Q_(e.pendingTransition.journal);if(pN(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(pN(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=je(e.paths,e.name);i={sourceHash:await Nt(c),targetHash:H(hN(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Gt)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await lj({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,n=l.plan}else{let l=Z_(s);if(Er(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Er(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=je(e.paths,e.name);i={sourceHash:await Nt(u),targetHash:H(hN(l)),nextJournal:l}}}else t=qc(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(r=await cj({paths:e.paths,state:e.state,migrationId:e.id}));let a=Bf.join(I(e.paths,e.name),Se),o=(0,Vc.stringify)(Vf(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===st?we:ge,sourceHash:await Nt(a),targetHash:H(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...n?{transitionSupersede:n}:{},...r?{runRetreat:r}:{}}}async function yN(e){return xe(e.paths,`migrate schema for ${e.name}`,()=>yn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await sj(e.paths,e.name,e.hooks);if(i?.schema===ge)return i;let n=await lt(e.paths,e.name);if(n.status==="current"&&n.state)return n.state;if(n.status!=="migration-required"||!n.state)throw new Error(n.message??`Native change ${e.name} cannot be migrated`);if(await or(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=n.state;if(r.schema!==st&&r.schema!==we)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await mf(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await uj({paths:e.paths,name:e.name,state:r,pendingTransition:a,now:e.now??new Date,id:e.id?.()??G_()}),s=ao(e.paths,e.name);await _(e.paths.nativeRoot,s),await ve(s,o),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var oi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),hj=512*1024,Sn=/^([a-f0-9]{64})\.json$/u,pj=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,mj=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Wc=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function zf(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Vt(e,t){return zf(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function EN(e,t){return zf(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Rr(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Me(e,t){return e<t?-1:e>t?1:0}function vj(e,t){let i=re.relative(e.projectRoot,t);if(i.length===0||re.isAbsolute(i)||i===".."||i.startsWith(`..${re.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(re.sep).join("/")}function RN(e,t){return re.join(I(e,t),"runtime","evidence")}function Jc(e,t){return vj(e,RN(e,t))}async function zc(e,t){let i=re.resolve(e),n=re.resolve(t);if(!q(i,n))throw new Error("Native evidence retention path escapes its managed change");let r=re.relative(i,n).split(re.sep).filter(Boolean),a=[],o=i;for(let s of["",...r]){s&&(o=re.join(o,s));let c=await U.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await U.realpath(o);if(a.length>0&&!q(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Rr(c)})}return a}async function ht(e){for(let t of e){let i=await U.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!zf(t,i)||await U.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function CN(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:mr(e,t)}function NN(e){return e!==null&&mj.test(e)?[e]:[]}function gj(e,t,i,n){if(e==="snapshots")return{canonical:lr(i,t),dependencies:[]};if(e==="scopes"){let a=ur(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=vc(i);if(a.change!==n||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[mr("scopes",a.scopeHash)]}}if(e==="verifications"){let a=Ja(i);if(a.change!==n||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(NN));return{canonical:a,dependencies:[a.implementationScopeRef,Aw(a.reportHash),...NN(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||dj("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=wc(i);if(a.bindings.change!==n||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let r=gc(i);if(r.change!==n||r.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:r,dependencies:[]}}async function Ki(e){let t=await U.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?hj:Li;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let n=await U.realpath(e.file);if(!q(e.directoryChain[0].realPath,n))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let r=process.platform==="win32"?"r":Wf.O_RDONLY|Wf.O_NOFOLLOW|Wf.O_NONBLOCK,a=await U.open(e.file,r).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),U.lstat(e.file),U.realpath(e.file)]);if(await ht(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==n||!Vt(Rr(t),o)||!Vt(Rr(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let N=i+1-d,k=await a.read(u,0,Math.min(u.length,N),null);if(k.bytesRead===0)break;if(d+=k.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,k.bytesRead)))}let[f,p,m]=await Promise.all([a.stat(),U.lstat(e.file),U.realpath(e.file)]);if(await ht(e.directoryChain),!p.isFile()||p.isSymbolicLink()||m!==n||!Vt(Rr(o),f)||!Vt(Rr(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(h)}catch(N){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:N})}let b=gj(e.kind,e.hash,v,e.name);if(h!==JSON.stringify(b.canonical,null,2)+`
201
- `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Rr(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(Me)}}finally{await a.close()}}async function bN(e){try{return await U.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function wj(e){let t=I(e.paths,e.name),i=RN(e.paths,e.name);await _(e.paths.nativeRoot,i);let n;try{let o=await zc(t,i);n=await U.readdir(i,{withFileTypes:!0}),await ht(o)}catch(o){if(o.code==="ENOENT")return{findings:[],pending:!1};throw o}let r=[];for(let o of Wc){if(!n.some(d=>d.name===o))continue;let s=re.join(i,o),c=await zc(t,s),l=(await U.readdir(s,{withFileTypes:!0})).sort((d,f)=>Me(d.name,f.name)),u=new Map;for(let d of l){let f=pj.exec(d.name);if(!f)continue;let p=u.get(f[1])??[];p.push(d),u.set(f[1],p)}for(let[d,f]of[...u.entries()].sort(([p],[m])=>Me(p,m))){if(f.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${o}/${d}`);let p=f[0];if(!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${o}/${p.name}`);let m=re.join(s,d),h=Sn.exec(d)?.[1];if(!h)throw new Error(`Native evidence cleanup quarantine name is invalid: ${p.name}`);let v=CN(o,h),b=re.join(s,p.name),N=await Ki({changeRoot:t,file:b,ref:v,kind:o,hash:h,name:e.name,directoryChain:c}),k=await bN(m),S=k?null:await Ki({changeRoot:t,file:m,ref:v,kind:o,hash:h,name:e.name,directoryChain:c});r.push({ref:v,original:m,quarantine:b,document:N,action:k?"restore-original":"finish-linked-recovery",originalDocument:S})}}if(r.length===0)return{findings:[],pending:!1};let a=r.map(o=>o.ref).sort(Me);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Cr(`Native evidence cleanup has ${a.length} safely recoverable quarantined document(s) for ${e.name}: ${Gc(a)}`),path:Jc(e.paths,e.name)}]};for(let o of r.sort((s,c)=>Me(s.ref,c.ref))){if(await ht(o.document.directoryChain),o.action==="finish-linked-recovery"){let u=await Ki({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Sn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),d=await Ki({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Sn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!o.originalDocument||!Vt(o.originalDocument.identity,u.identity)||!Vt(o.document.identity,d.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${o.ref}`);await U.rm(o.quarantine),await ht(o.document.directoryChain);continue}if(!await bN(o.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${o.ref}`);let s=await U.lstat(o.quarantine);if(!s.isFile()||s.isSymbolicLink()||!Vt(o.document.identity,s))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${o.ref}`);await U.link(o.quarantine,o.original),await e.hooks.afterRecoveryLink?.({ref:o.ref,original:o.original,quarantine:o.quarantine});let c=await Ki({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Sn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),l=await Ki({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Sn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!EN(o.document.identity,c.identity)||!Vt(c.identity,l.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${o.ref}`);await U.rm(o.quarantine),await ht(o.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Cr(`Recovered ${a.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Gc(a)}`),path:Jc(e.paths,e.name)}]}}async function yj(e,t){let i=I(e,t),n=re.join(i,"runtime","evidence");await _(e.nativeRoot,n);let r;try{let c=await zc(i,n);r=await U.readdir(n,{withFileTypes:!0}),await ht(c)}catch(c){if(c.code==="ENOENT")return[];throw c}let a=r.filter(c=>!Wc.includes(c.name)||!c.isDirectory()||c.isSymbolicLink()).map(c=>c.name).sort(Me);if(a.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Gc(a)}`);let o=[],s=0;for(let c of Wc){if(!r.some(f=>f.name===c))continue;let l=re.join(n,c),u=await zc(i,l),d=(await U.readdir(l,{withFileTypes:!0})).sort((f,p)=>Me(f.name,p.name));await ht(u);for(let f of d){if(o.length>=oi.maxDocuments)throw new Error(`Native evidence store exceeds ${oi.maxDocuments} documents`);let p=Sn.exec(f.name);if(!p||!f.isFile()||f.isSymbolicLink())throw new Error(`Native evidence kind ${c} has an unknown or special entry: ${f.name}`);let m=CN(c,p[1]),h=re.join(l,f.name);await _(e.nativeRoot,h);let v=await Ki({changeRoot:i,file:h,ref:m,kind:c,hash:p[1],name:t,directoryChain:u});if(s+=v.size,s>oi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${oi.maxScannedBytes} scanned bytes`);o.push(v)}await ht(u)}return o}function kN(e,t){let i=new Set,n=[...e].sort(Me).reverse();for(;n.length>0;){let r=n.pop();if(i.has(r))continue;let a=t.get(r);if(!a)throw new Error(`Native evidence dependency is missing: ${r}`);i.add(r);for(let o of[...a.dependencies].sort(Me).reverse())i.has(o)||n.push(o)}return i}function Nj(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let n=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Me),r=[];for(;n.length>0;){let a=n.shift(),o=t.get(a);r.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(n.push(s),n.sort(Me))}}if(r.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return r}function bj(e,t,i){let n=new Map(e.map(c=>[c.ref,c]));if(n.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!n.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let r=kN(t,n),a=new Set(r);for(let c of e)i-c.mtimeMs<oi.minimumAgeMs&&a.add(c.ref);for(let c of Wc){let l=e.filter(u=>u.kind===c&&!r.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Me(u.ref,d.ref)).slice(0,oi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=kN(a,n),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=oi.minimumAgeMs).sort((c,l)=>Me(c.ref,l.ref));return{candidates:Nj(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Gc(e){let t=e.slice(0,oi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Cr(e){let t=oi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Jf(e,t,i,n){let r=t.candidates.map(a=>a.ref).sort(Me);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Cr(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Gc(r)}`),path:n}}async function SN(e,t){try{await U.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await U.rename(e,t)}catch{}}async function kj(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await ht(e.directoryChain);let i=await Ki({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Sn.exec(re.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),n=await U.lstat(e.file),r=await U.realpath(e.file);if(!n.isFile()||n.isSymbolicLink()||!Vt(e.identity,n)||!Vt(e.identity,i.identity)||!q(e.directoryChain[0].realPath,r))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=re.join(re.dirname(e.file),`.${re.basename(e.file)}.${fj()}.gc`);await U.rename(e.file,a);try{let[o,s]=await Promise.all([U.lstat(a),U.realpath(a)]);if(await ht(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!EN(e.identity,o)||!q(e.directoryChain[0].realPath,s))throw await SN(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await U.rm(a),await ht(e.directoryChain)}catch(o){throw await SN(a,e.file),o}}async function Sj(e){if((await We(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await U.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())return!0;try{let r=await Ye(e,n.name);if(r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}}return!1}async function Ej(e,t){if(t)return[t];let i;try{i=await U.readdir(e.changesDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort(Me)}async function Rj(e,t){let i=await lt(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[n,r,a]=await Promise.all([ii(e,t),oo(e,t),Ji(e,t)]);return n!==null||r!==null||a!==null}async function Cj(e){if(await Rj(e.paths,e.name))return[];let t=await lt(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await wj({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let n=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&n.push(c);let r=await yj(e.paths,e.name),a=bj(r,n,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Jc(e.paths,e.name);if(!e.repair)return[...i.findings,Jf(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await kj(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Jf(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Cr(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Jf(e.name,a,!0,o)]}async function PN(e){if(e.deferAll||await Sj(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async r=>{let a=[];for(let o of await Ej(e.paths,e.name))try{a.push(...await Cj({paths:e.paths,name:o,repair:r,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Cr(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Jc(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let n=await i(!1);if(n.some(r=>r.severity==="error")||!n.some(r=>r.code==="evidence-retention-candidates"||r.code==="evidence-retention-recovery-required"))return n;try{return await xe(e.paths,"prune Native evidence",()=>i(!0))}catch(r){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Cr(`Native evidence cleanup was deferred until the project mutation lock is available: ${r.message}`)}]}}import{createHash as Pj,randomUUID as EV}from"crypto";import{promises as lo}from"fs";import ee from"path";var Uf=64*1024*1024,Aj=256*1024,IN=16*1024*1024;async function Le(e){try{return await lo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xj(e){let t;try{t=await lo.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((n,r)=>n.name.localeCompare(r.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let n=await Dt(e,i.name);if(n){await Ia({paths:e,name:i.name,revision:n.capturedRevision,...n.schema==="comet.native.workspace.v3"?{binding:{isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch},...n.finish?{finish:n.finish}:{}}:{}});continue}let r;try{r=await lt(e,i.name)}catch{continue}r.status!=="current"||!r.state||!("revision"in r.state)||await Ia({paths:e,name:i.name,revision:r.state.revision})}}async function co(e,t){let i=[];async function n(r){let a=await Ke({root:e,directory:r,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ee.join(r,s.name);if(t.excludedFiles?.has(ee.resolve(c))){await a.verify();continue}let l=await lo.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ee.relative(e,c).split(ee.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await Z({root:e,file:c,maxBytes:Uf,label:`Native root file ${ee.relative(e,c)}`});i.push({ref:ee.relative(e,c).split(ee.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await n(e),i.sort((r,a)=>r.ref.localeCompare(a.ref))}async function Tj(e,t,i,n){await Ot({root:n,directory:t,label:"Native root move staging directory"});async function r(a,o){let s=await Ke({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ee.join(a,l.name);if(ee.resolve(u)===ee.resolve(i)){await s.verify();continue}let d=await lo.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ee.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Ot({root:n,directory:f,label:"Native root move staging directory"}),await r(u,f);else if(l.isFile()&&d.isFile())await Ci({sourceRoot:e,source:u,targetRoot:n,target:f,maxBytes:Uf,label:`Native root move file ${ee.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await r(e,t)}async function Pr(e,t,i,n){let r=await co(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ee.resolve(i)]):void 0}),a=await co(t,{rejectSymlinks:!0,excludedFiles:n?new Set([ee.resolve(n)]):void 0});if(JSON.stringify(r)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function Ij(e,t){return ee.join(e.artifactRoot,`.comet-native-move-${t}`)}function _j(e,t){return ee.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function jj(e){return`${e}.removing`}function AN(e,t){return ee.join(ee.dirname(e),`.${ee.basename(e)}.${t}.rollback-removing`)}function _N(e,t,i){return ee.join(Ms(e,t).directory,`root-move-cleanup-${i}.json`)}function Oj(e){return JSON.stringify(e,null,2)+`
202
- `}function $j(e){return Pj("sha256").update(e).digest("hex")}function Hj(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,n=Object.keys(i).sort(),r=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ee.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function Dj(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let n=e;if(JSON.stringify(Object.keys(n).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||n.schema!=="comet.native.root-move-cleanup.v1"||n.transactionId!==t||n.kind!==i||!Array.isArray(n.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let r=n.entries.map(Hj);for(let a=0;a<r.length;a+=1){if(a>0&&r[a-1].ref.localeCompare(r[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ee.posix.dirname(r[a].ref);if(o!=="."&&!r.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:r}}async function Fj(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=Oj(t);if(Buffer.byteLength(i,"utf8")>IN)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await Ve(_N(e.paths,e.id,e.kind),i,{containedRoot:e.paths.nativeRoot}),$j(i)}async function Mj(e){let t=await Z({root:e.paths.nativeRoot,file:_N(e.paths,e.id,e.cleanup.kind),maxBytes:IN,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return Dj(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Gf(e){let t=await co(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(n=>[n.ref,n]));for(let n of t){let r=i.get(n.ref);if(!r||JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${n.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function xN(e){return e.ref.split("/").length}async function Lj(e){let i=[...await Gf({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((r,a)=>xN(a)-xN(r)||(r.type===a.type?a.ref.localeCompare(r.ref):r.type==="file"?-1:1)),n=0;for(let r of i){let a=ee.join(e.quarantine,...r.ref.split("/"));r.type==="file"?await Os({root:e.projectRoot,file:a,maxBytes:Uf,expectedHash:r.hash,expectedSize:r.size,label:`Native root-move cleanup file ${r.ref}`}):await ed({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${r.ref}`}),n+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,r.ref,n)}await Gf({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await ed({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function jN(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function Bj(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function qj(e,t,i,n){for(let a of[e,t])try{let o=await Ye(a,n);if(o.kind!=="root-move")throw new Error(`Transaction ${n} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let r=ee.join(i,"runtime","transactions",n,"transaction.json");try{let a=await Z({root:i,file:r,maxBytes:Aj,label:`Staged Native root-move journal ${n}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${n}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${n}`,{cause:a})}}async function TN(e){let t=jN(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await qn(e.projectRoot,t),t}async function so(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=jN(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await qn(e.projectRoot,i),i}async function Uc(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let n=i.cleanup;if(n&&n.kind!==e.kind)throw new Error(`Native root move has unfinished ${n.kind} cleanup; cannot start ${e.kind}`);let r=await Le(e.target),a=await Le(e.quarantine);if(r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!n){if(!r&&!a)return t;if(!r&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await Fj({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await co(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await so({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let o=await Mj({paths:e.stablePaths,id:e.id,cleanup:n});if(r=await Le(e.target),a=await Le(e.quarantine),r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(r){if(n.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Nv({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(n.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return so({projectRoot:e.projectRoot,config:t,id:e.id})}return await Gf({quarantine:e.quarantine,manifest:o,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await so({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await so({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await Lj({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),so({projectRoot:e.projectRoot,config:t,id:e.id})}async function Vj(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Le(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=jj(e.staging);t=await Uc({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await co(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ee.resolve(e.lockFile)])}),await Tj(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Pr(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await TN({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Le(e.destinationPaths.nativeRoot)){if(await Le(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Pr(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Le(e.staging))throw new Error("Native move staging tree is missing");await Pr(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await lo.rename(e.staging,e.destinationPaths.nativeRoot)}t=await TN({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Le(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=_j(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Le(e.sourcePaths.nativeRoot)&&await Pr(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Uc({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:n,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await xj(e.destinationPaths);let r=await Ye(e.destinationPaths,e.pending.id);await Gn(e.destinationPaths,r,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await qn(e.projectRoot,o),o}async function ON(e){let t=await We(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let n=await _t(e.projectRoot,i.fromArtifactRoot),r=await _t(e.projectRoot,i.toArtifactRoot),a=Ij(r,i.id),o=await Le(n.nativeRoot)?n:r,s=await bi(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await qj(n,r,a,i.id)}catch(m){if(i.stage!=="copying"||!await Le(n.nativeRoot))throw m;let h=Bj({id:i.id,paths:n,now:new Date});await Tv(n,h),c={journal:h,paths:n}}if(e.strategy==="continue"){let m=await Vj({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:n,destinationPaths:r,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:r.nativeRoot,config:m}}if(!await Le(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=AN(r.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Le(r.nativeRoot)&&await Pr(n.nativeRoot,r.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Uc({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:n,target:r.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=AN(a,i.id);!t.native.pending_root_move?.cleanup&&await Le(a)&&await Pr(n.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Uc({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:n,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await Ye(n,i.id);await Ls(n,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await qn(e.projectRoot,p),{activeNativeRoot:n.nativeRoot,config:p}}finally{await ki(s)}}var uo=4096,Jj=4096,zj=1024;async function En(e,t,i){try{let n=await Ke({root:e.nativeRoot,directory:t,label:"Native doctor directory",maxEntries:i});return await n.verify(),n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}}async function Kc(e,t){let i=new Map(e.map(n=>[ye.resolve(n.file),{...n,file:ye.resolve(n.file)}]));for(let{paths:n,file:r}of i.values()){let a;try{a=await wa(r)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:r}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Zu(n,r,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:r});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:r}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:r}),!1)}}return!0}async function Gj(e,t){let i=Ky(e),n;try{await _(e.projectRoot,i);let r=await Fc(e);if(!r)return[];n=r}catch(r){return r.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${r.message}`,path:i}]}if(n.schema!=="comet.selection.v2"||n.workflow!=="native"||typeof n.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await Ie(e,n.change),[]}catch(r){if(r.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${r.message}`,path:i}]}return t?(await Wj.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${n.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${n.change}`,path:i}]}async function Uj(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await _(e.nativeRoot,i)}catch(n){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${n.message}`,path:i})}return t}async function Kj(e,t){let i=[],n=[];for(let r of await En(e,e.transactionsDir,Jj)){if(!r.isDirectory()||r.isSymbolicLink())continue;let a;try{a=await Ye(e,r.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${r.name} is invalid: ${o.message}`,path:ye.join(e.transactionsDir,r.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){n.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Is([e],`doctor archive recovery ${a.id}`,async()=>await Kc([{paths:e,file:ye.join(e.locksDir,"root-move.lock")},{paths:e,file:ye.join(e.locksDir,"archive.lock")}],i)?(await Zy({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){n.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){n.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else n.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:n}}async function Yj(e,t,i){let n=[];for(let r of await En(e,e.locksDir,zj)){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".lock"))continue;let a=ye.join(e.locksDir,r.name);try{let o=await wa(a);if(o.status==="active")n.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")n.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await Zu(e,a,o);s.status==="removed"?n.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&n.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else n.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){n.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return n}async function Xj(e,t,i=5){let n=[],r=t?await Mf(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Mf(e,{maxVerifyFailures:i});if(t&&r.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of r){if(a.migrationRequired)continue;if(a.phase==="invalid"){n.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:ye.join(e.changesDir,a.name,Se)});continue}let o=await Ff(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||n.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:ye.join(e.projectRoot,s.path)}:{}})}return n}async function Qj(e,t){let i=[],n=t.name?[t.name]:(await En(e,e.changesDir,uo)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{let a=await tr(e,r);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${r} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await pg(e,r);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${r} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${r}: ${a.message}`,path:ye.join(e.changesDir,r,"runtime","trajectory.jsonl")})}return i}async function Zj(e,t){let i=[],n=t.name?[t.name]:(await En(e,e.changesDir,uo)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{if(!await Rd(e,r))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${r} uses legacy external-probe or hash-only metadata`,path:nr(e,r),repair:"migrate"});continue}let a=await Ie(e,r);await Rg({paths:e,name:r,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${r} with process-free root identities`,path:nr(e,r)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${r}: ${a.message}`,path:nr(e,r)})}return i}async function eO(e,t){let i=[],n=t.name?[t.name]:(await En(e,e.changesDir,uo)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=ao(e,r);try{let o=await oo(e,r),s=await lt(e,r);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${r} requires a newer runtime`,path:ye.join(e.changesDir,r,Se)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${r}`:`Native change ${r} requires migration to the current schema`,path:o?a:ye.join(e.changesDir,r,Se),repair:"migrate"});continue}await yN({paths:e,name:r}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${r} to the current schema`,path:ye.join(e.changesDir,r,Se)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${r}: ${o.message}`,path:a})}}return i}async function tO(e,t){let i=[],n=t.name?[t.name]:(await En(e,e.changesDir,uo)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a;try{a=await ii(e,r)}catch(o){if(o instanceof Xa)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:je(e,r)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Is([e],`doctor transition recovery ${r}`,async()=>await Kc([{paths:e,file:ye.join(e.locksDir,"root-move.lock")},{paths:e,file:ye.join(e.locksDir,`transition-${r}.lock`)}],i)?(await Zw(e,r),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${r}`,path:je(e,r)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:je(e,r)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${r}`,path:je(e,r),repair:"continue"})}}return i}async function iO(e,t){let i=[],n=t.name?[t.name]:(await En(e,e.changesDir,uo)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=Wi(e,r),o;try{o=await Ji(e,r)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${r}`,path:a});continue}try{if(!await Is([e],`doctor checkpoint recovery ${r}`,async()=>await Kc([{paths:e,file:ye.join(e.locksDir,"root-move.lock")},{paths:e,file:ye.join(e.locksDir,`transition-${r}.lock`)}],i)?(await Sy(e,r),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${r}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function $N(e){let t=e.repair??!1,i=[],n=e.paths,r;try{r=await We(n.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:n.configFile}]}}let a=!!r?.native.pending_root_move;if(r?.native.pending_root_move){let c=r.native.pending_root_move,[l,u]=await Promise.all([_t(n.projectRoot,c.fromArtifactRoot),_t(n.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Kc([{paths:l,file:ye.join(l.locksDir,"root-move.lock")},{paths:u,file:ye.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await ON({projectRoot:n.projectRoot,strategy:e.recoveryStrategy});n=await _t(n.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await Uj(n);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await Kj(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),i.push(...await eO(n,{name:e.name,repair:t})),i.push(...await Zj(n,{name:e.name,repair:t})),i.push(...await Qj(n,{name:e.name,repair:t})),i.push(...await tO(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await iO(n,{name:e.name,repair:t})),i.push(...await PN({paths:n,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0})),i.push(...await Yj(n,t,s.unfinished)),i.push(...await Gj(n,t)),i.push(...await Xj(n,e.name,r?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import nO from"path";var d2=10*1024*1024,si=class extends Error{};function Yc(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new si(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Xc(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new si(`${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 si(`${t} requires a value`);return e.splice(n,2),r}function HN(e){if(e.length>0)throw new si(`Unexpected argument: ${e[0]}`)}async function DN(e){return e?nO.resolve(e):Uu(process.cwd())}async function FN(e){let t=await We(e);return _t(e,t?.native.artifact_root??"docs")}function MN(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
203
- `}}function LN(e,t){if(t instanceof si)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Mc)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 no)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof $a)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 rc)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 rr)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 zi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof to)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 BN(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}})+`
204
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function qN(e,t){let i=Yc(e,"--repair"),n=Xc(e,"--strategy");if(n!==void 0&&n!=="continue"&&n!=="rollback")throw new si("--strategy must be continue or rollback");let r=e[0]?.startsWith("--")?void 0:e.shift();HN(e);let a=await FN(t),o=await $N({paths:a,...r?{name:r}:{},repair:i,...n?{recoveryStrategy:n}:{}});return o.healthy?MN("doctor",o):{command:"doctor",exitCode:65,data:o,error:{code:"invalid-data",message:"Native project needs attention"}}}function rO(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}})+`
205
- `}}async function VN(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{Yc(r,"--json"),s=Xc(r,"--project-root");let u=[...r,...a],d=await DN(s);c=await t(u,d)}catch(u){c=LN(e,u)}let l=o?rO(c):BN(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
237
+
238
+ ## Previous iterations
239
+
240
+ ${a}
241
+
242
+ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summary: ${e.history_overflow.dropped_entries}.
243
+
244
+ `:""}## Conclusion
245
+
246
+ ${Ar(e.verification.summary)}
247
+ `}function aH(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function du(e){let t;try{t=await tH.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=aH(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function fu(e){await ue(e.file,nH(e.state))}var Ik=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oH="comet-state.yaml",sH="state.json";function jt(e,t){if(!Ik.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=_r.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function bt(e,t){return _r.join(jt(e,t),oH)}function cn(e,t){return _r.join(rt(e,t),sH)}async function Tr(e,t){try{let i=await fs.readFile(bt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function cH(e){return Ae(e).currentBranch}async function ka(e,t){return Ue(bt(e,t))}async function lH(e){let t=await zr({file:bt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=_r.join(jt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await fs.rm(i,{force:!0})}return t}async function uH(e){let t=jt(e.paths,e.state.name),i=_r.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await fs.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Ik.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=_r.join(t,...s.split("/")),l=await fs.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=_r.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await fs.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function dH(e){let t=jt(e.paths,e.state.name),i=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Jc({briefMarkdown:i.text,specs:r})}async function jk(e){let t=await uH(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await dH({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Vw(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Tp({changeDir:jt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c)})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Ip({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function $k(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Ln(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ir(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await lH({paths:e.paths,previous:t,next:r});return await Cr(cn(e.paths,t.name),sn({portableState:n,projectRoot:e.paths.projectRoot,branch:cH(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function hu(e){if(e.state.verification===null)return"not-applicable";let t=_r.join(jt(e.paths,e.state.name),"verification.md");return await du({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await fu({file:t,state:e.state}),"rebuilt")}async function Ok(e){let t=await ka(e.paths,e.name),i=cn(e.paths,e.name);try{let r=await uu(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var qG=16*1024;async function pu(e){let t=await Pp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(xl(t.selection.change),t.selection)}function Hk(e){return nu(e.projectRoot)}async function hs(e,t){return await $n(e.projectRoot),Sk(e.projectRoot,"native",t)}var gU=16*1024*1024,mu=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"},ps=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"};function Mk(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Sa.resolve(e.nativeRoot,...i.target.split("/"))}async function Fk(e,t,i){let r=await lr(e,t.id);if(r.some(m=>m.type==="archive-finalized"))return;let n=r.some(m=>m.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let m=t.operations.find(y=>y.id==="archive-change");if(!m||m.type!=="move"||!m.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let N=await Qt(Mk(e,t));if(N?.kind!=="directory"||N.hash!==m.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Mk(e,t),o=Sa.join(a,Re),s=await wN(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await Ie(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let m=dm(pi,l,new Set,ep,void 0);if(!m.action)throw new Error(m.reason??"Native archive produced no action");u=fm(pi,m.state,{actionId:m.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},ep,void 0)}let d=F(`archive:${t.id}:${s.name}`),f=await Xe(c,u.trajectoryRef),p=f.filter(m=>m.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(m=>m.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=p.find(m=>m.type==="state_transitioned"),h={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!fH(v.data,h)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||p.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await ru(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await zn(e,t,"archive-finalization-started")),!s.archived){let m={...s,archived:!0};await gN(o,m)}v||(v=await Nr({changeDir:c,run:u,type:"state_transitioned",data:h,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await nn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Xr(c,u),await hs(e,s.name),t.schema==="comet.native.transaction.v2"?await ru(e,t,"archive-finalized"):await zn(e,t,"archive-finalized")}async function Dp(e,t){let i=rt(e,t);try{let r=await Dk.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await Dk.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function hH(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await lr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Zl({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new ps(c,"Native Archive facts changed before the first transaction operation")}let o=await yk(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await $e(e,t.change),u=await Ql({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await Fk(e,o,i);let s=await ru(e,o,"commit");return{journal:s,runtimeCleanupWarning:await Dp(e,s.change)}}let r=await hy(e,t);await Fk(e,r,i);let n=await zn(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await Dp(e,n.change):null}}function pH(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Sa.resolve(t.projectRoot)!==Sa.resolve(e.projectRoot)||Sa.resolve(t.nativeRoot)!==Sa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Lk(e){return he(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await er(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await mt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Sp(e.paths,e.transactionId):i;return pH(e.paths,r),r.status==="committed"?(r.change&&await Dp(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await hH(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?Nk(e.paths,r):ll(e.paths,r)}finally{await tr(t)}},{allowedTransactionId:e.transactionId})}import{promises as AH}from"fs";async function Bk(e,t){let i=[],r=H(e,t.name),n=Qi(r,vt.stateRef),a;try{a=await Ie(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Qi(r,a.trajectoryRef),s=await Zn(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 Xe(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=Qi(r,a.checkpointRef);try{let u=await Qn(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}var mH=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function vH(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function gH(e){return e?e.map(vH).join(" "):null}function wH(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function $t(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function yH(e){return e.map(t=>$t(t,[],null))}function NH(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[$t("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push($t("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push($t("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),$t("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push($t("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push($t("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),$t("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Je(e,t){let i=t.commandArgs===void 0?wH(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?gH(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??yH(t.requiredInputs??[])}}function vu(e){let i=(e.findings??[]).filter(d=>!ea(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||mH.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Je(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Je(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[$t("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Je(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Je(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Je(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"<summary>")]});if(n)return Je(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Je(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Je(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Je(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[$t("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Je(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Je(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=NH(e.state);return Je(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import ms from"path";var qk=8,bH={"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 kH(e){let t=bH[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"}:ea(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 SH(e,t,i){if(!i.path)return null;let r;if(ms.isAbsolute(i.path)?r=ms.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=ms.resolve(re(e,t.name),...i.path.split(/[\\/]/u)):r=ms.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=ms.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function EH(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 Mp(e){return e.findings.map(t=>{let i=kH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:SH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:EH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Fp(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,qk),truncated:t.length>qk}}var Vk=240,Wk=8,gu=50;function zk(e){let t=Array.from(e);return t.length<=Vk?e:`${t.slice(0,Vk-1).join("")}…`}function PH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function RH(e){let t=[...new Set(e.map(PH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Wk),reasonCount:e.length,codesTruncated:t.length>Wk};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,gu),reasonsTruncated:e.length>gu}}}async function Jk(e){let t=null;try{let s=await Er(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Sr(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:Sr(e.paths,e.state.name)}}let i=await Yb({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=RH(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:kr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:zk(i.checkpoint.summary),nextAction:zk(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:kr.maxArtifacts}}async function xH(e,t){let i=H(e,t.name),r=await Ie(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Qn(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 Xe(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function CH(e,t){let i=await xH(e,t);return{committed:i,latest:Rb(i),history:Pb(i)}}async function Gk(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await CH(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var _H=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ea=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Lp(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function TH(e){return(await pu(e))?.change??null}function IH(e,t,i=!1,r){return vu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function jH(e,t){let i=re(e,t.name),r=[...(await xh(i,t.brief)).findings,...(await SN(e,t)).findings,...await Bk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Xn(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await vl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await ga({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ti(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Ch(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Bp(e,t,i){let r=await TH(e)===t,n=await No(e,t),a=await aN(e,t),o;try{let g=await ui(e,t);if(g.status==="migration-required"&&g.state)return{name:t,phase:g.state.phase,revision:"revision"in g.state?g.state.revision:null,approval:g.state.approval,verificationResult:g.state.verification_result,specChanges:g.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,migrationRequired:!0,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message};if(g.status!=="current"||!g.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${t} is incompatible`};o=g.state}catch(g){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:g.message}}if(n.status!=="available"){let g={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Mp({paths:e,state:o,findings:[g]}),D=vu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:D.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Fp(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:D,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await Jk({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Gk(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let g=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:g,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let g=await ga({changeDir:re(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let De=await ma(e,o.name,o.verification_evidence);for(let ce of De.acceptanceTrace.entries)P.set(ce.acceptanceId,ce.status==="failed"?"failed":ce.status==="missing"?"missing":"satisfied")}let D=Dw({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),O=D.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",D.nextCursor,"--project-root",e.projectRoot]:null;u={...D,...O?{nextPageCommand:Lp(O),nextPageArgs:O}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Bl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await wt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let P=await ia({paths:e,identity:g});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Fo({paths:e,identity:g});f.push(...P.findingCodes.map(D=>({code:D,message:`Native workspace advisory changed: ${D} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let g=await ak({paths:e,state:o});v=g.freshness!=="fresh",p.push(...g.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Zl({paths:e,name:o.name}),m.push(...h.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 N=[...await jH(e,o),...s.findings,...d,...f,...p,...l,...m].filter((g,P,D)=>D.findIndex(O=>O.code===g.code&&O.path===g.path)===P),y=Mp({paths:e,state:o,findings:N}),E=y.filter(g=>!ea(g.code)),S=o.phase==="archive"&&h?.ready===!0&&E.length===0,k=v||o.phase==="archive"&&(h?.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)),b=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",w=y.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:b||R?null:IH(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:Fp(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:vu({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:gu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...w?{error:w.message}:{}}}async function $H(e){let t;try{t=await Jt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await AH.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ea.maxChanges))throw new Error(`Native status exceeds ${Ea.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function wu(e,t){let i=t.toString(36),r=M("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function OH(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=_H.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=M("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function HH(e,t){let i=await $H(e),r=M("comet.native.status-names.v1",i),n=OH({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ea.maxItems).map(u=>Bp(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,p={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?wu(r,f):null,nextPageCommand:f<i.length?Lp(["comet","native","status","--cursor",wu(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",wu(r,f)]:null,limits:{...Ea}};if(Buffer.byteLength(JSON.stringify(p),"utf8")>Ea.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?wu(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?Lp(l):null,nextPageArgs:l,limits:{...Ea}}}async function qp(e,t){return(await HH(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as tD,randomUUID as iD}from"node:crypto";import{constants as Gp,promises as X}from"node:fs";import se from"node:path";var bu=hn(Lr(),1);import{randomUUID as DH}from"crypto";import{promises as Qk}from"fs";import Wp from"path";import{isDeepStrictEqual as zp}from"util";var ln=/^[a-f0-9]{64}$/u,MH=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),FH=new Set(["sourceHash","targetHash","nextJournal"]),LH=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),Uk=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),BH=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function yu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Kk(e){return JSON.stringify(e,null,2)+`
248
+ `}function Jp(e){return e.schema===we?Cl(e):Qr(e)}function Vp(e,t){return{...e,schema:we,minimum_runtime_version:2,revision:t}}function qH(e){return{...e,schema:Si,minimum_runtime_version:2,revision:1,previousState:Vp(e.previousState,1),nextState:Vp(e.nextState,2)}}function Nu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:ge,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function VH(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?F(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:rr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Nu(e.previousState),nextState:{...Nu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:pi.definition.metadata.version,skillHash:ns}:e.nextRun}}function Yk(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Pa(e,t){return JSON.stringify(Cl(e))===JSON.stringify(Cl(t))}function Xk(e,t){return JSON.stringify(Qr(e))===JSON.stringify(Qr(t))}function $i(e,t){return zp(e,t)}function WH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(yu(n,LH,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!ln.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!ln.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=hr(n.previousRun),o=hr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!$i(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==Uk.size||u.some(f=>!Uk.has(f))||l.fromSchema!==we||l.toSchema!==ge||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function vs(e,t){return Wp.join(H(e,t),"schema-migration.json")}function zH(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");yu(e,MH,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===Ke&&i.toSchema===we,n=i.fromSchema===we&&i.toSchema===ge;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!ln.test(i.sourceHash)||typeof i.targetHash!="string"||!ln.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?ai(i.nextState):st(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(F((0,bu.stringify)(Jp(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");yu(i.transition,FH,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!ln.test(l.sourceHash)||typeof l.targetHash!="string"||!ln.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?cp(l.nextJournal,t):sp(l.nextJournal,t);if(F(JSON.stringify(l.nextJournal,null,2)+`
249
+ `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===we?Pa(a,u.previousState)||Pa(a,u.nextState):a.schema===ge&&(Xk(a,u.previousState)||Xk(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==ge)throw new Error("Schema migration transition supersede target schema is invalid");s=WH(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");yu(i.runRetreat,BH,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=hr(l.previousRun),d=hr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!ln.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==ge||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function gs(e,t){let i=vs(e,t),r=j(e,i);await T(r,i);try{let n=await il({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return zH(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function JH(e,t,i){let r=await Xn(e,t),n=r?await vl(e,r):await gl(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=hh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ra(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await vh(e,t,n)}async function Zk(e){try{return await Gt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function GH(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function eS(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await Xe(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!zp(o.event,GH(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function UH(e,t,i){if(!t.transitionSupersede)return;let r=ze(e,t.change),n=await Zk(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await Ie(a),s=await eS(e,t),c=await Qn(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!$i(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==F(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function KH(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await Ie(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!$i(a,r.nextRun)){if(!$i(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Xr(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!$i(await Ie(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await eS(e,t);if(o.sequence===null){let l=await Nr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await nn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=ze(e,t.change),c=await Zk(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await Qk.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function YH(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await Ie(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!$i(n,t.runRetreat.nextRun)){if(!$i(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Xr(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await Xe(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Nr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await nn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function XH(e,t,i){let r=await gs(e,t);if(!r)return null;if(await aa(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Wp.join(re(e,t),Re),a=await Gt(n);if(await UH(e,r,a===r.targetHash),await JH(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await ue(n,(0,bu.stringify)(Jp(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=ze(e,t),s=await Gt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await te(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await KH(e,r,i),await YH(e,r,i),await Qk.rm(vs(e,t),{force:!0}),r.nextState}async function QH(e){let t=H(e.paths,e.state.name),i=await Ie(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:we,toSchema:ge,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function ZH(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Pa(i,t.previousState),a=Pa(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await Ie(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&$i(s,t.previousRun),l=$i(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await Xe(o,t.nextRun.trajectoryRef)).map((N,y)=>({event:N,index:y})).filter(({event:N})=>N.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let N={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!zp(f.event,N)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Nu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,m=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await Gt(ze(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:h,evidenceHash:m,eventData:{fromSchema:we,toSchema:ge,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function eD(e){let t,i,r,n;if(e.state.schema===Ke){if(t=Vp(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Jr)throw new Error("Native v1 change has a transition from another schema generation");let s=qH(e.pendingTransition.journal);if(Yk(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(Yk(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=ze(e.paths,e.name);i={sourceHash:await Gt(c),targetHash:F(Kk(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Si)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await ZH({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=VH(s);if(Pa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Pa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=ze(e.paths,e.name);i={sourceHash:await Gt(u),targetHash:F(Kk(l)),nextJournal:l}}}else t=Nu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await QH({paths:e.paths,state:e.state,migrationId:e.id}));let a=Wp.join(re(e.paths,e.name),Re),o=(0,bu.stringify)(Jp(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Ke?we:ge,sourceHash:await Gt(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function tS(e){return he(e.paths,`migrate schema for ${e.name}`,()=>an(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await XH(e.paths,e.name,e.hooks);if(i?.schema===ge)return i;let r=await ui(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await aa(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==Ke&&n.schema!==we)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await lp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await eD({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??DH()}),s=vs(e.paths,e.name),c=j(e.paths,s);await T(c,s),await te(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Oi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),rD=512*1024,un=/^([a-f0-9]{64})\.json$/u,nD=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,aD=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,ku=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Kp(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yi(e,t){return Kp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function oS(e,t){return Kp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ra(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ze(e,t){return e<t?-1:e>t?1:0}function oD(e,t){let i=se.relative(e.projectRoot,t);if(i.length===0||se.isAbsolute(i)||i===".."||i.startsWith(`..${se.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(se.sep).join("/")}function sS(e,t){return se.join(H(e,t),"evidence")}function Su(e,t){return oD(e,sS(e,t))}async function Eu(e,t){let i=se.resolve(e),r=se.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=se.relative(i,r).split(se.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=se.join(o,s));let c=await X.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await X.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ra(c)})}return a}async function Ot(e){for(let t of e){let i=await X.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Kp(t,i)||await X.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function cS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:pa(e,t)}function iS(e){return e!==null&&aD.test(e)?[e]:[]}function sD(e,t,i,r){if(e==="snapshots")return{canonical:ca(i,t),dependencies:[]};if(e==="scopes"){let a=la(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Hl(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[pa("scopes",a.scopeHash)]}}if(e==="verifications"){let a=Zo(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(iS));return{canonical:a,dependencies:[a.implementationScopeRef,mb(a.reportHash),...iS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||tD("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Ml(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=Dl(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Ir(e){let t=await X.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?rD:yr;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await X.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Gp.O_RDONLY|Gp.O_NOFOLLOW|Gp.O_NONBLOCK,a=await X.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!yi(Ra(t),o)||!yi(Ra(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,E=await a.read(u,0,Math.min(u.length,y),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,p,v]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!p.isFile()||p.isSymbolicLink()||v!==r||!yi(Ra(o),f)||!yi(Ra(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),m;try{m=JSON.parse(h)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let N=sD(e.kind,e.hash,m,e.name);if(h!==JSON.stringify(N.canonical,null,2)+`
250
+ `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ra(f),directoryChain:e.directoryChain,dependencies:[...new Set(N.dependencies)].sort(Ze)}}finally{await a.close()}}async function rS(e){try{return await X.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function cD(e){let t=H(e.paths,e.name),i=t,r=sS(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Eu(t,r);n=await X.readdir(r,{withFileTypes:!0}),await Ot(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of ku){if(!n.some(f=>f.name===s))continue;let c=se.join(r,s),l=await Eu(t,c),u=(await X.readdir(c,{withFileTypes:!0})).sort((f,p)=>Ze(f.name,p.name)),d=new Map;for(let f of u){let p=nD.exec(f.name);if(!p)continue;let v=d.get(p[1])??[];v.push(f),d.set(p[1],v)}for(let[f,p]of[...d.entries()].sort(([v],[h])=>Ze(v,h))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=p[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let h=se.join(c,f),m=un.exec(f)?.[1];if(!m)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let N=cS(s,m),y=se.join(c,v.name),E=await Ir({changeRoot:i,file:y,ref:N,kind:s,hash:m,name:e.name,directoryChain:l}),S=await rS(h),k=S?null:await Ir({changeRoot:i,file:h,ref:N,kind:s,hash:m,name:e.name,directoryChain:l});a.push({ref:N,original:h,quarantine:y,document:E,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Ze);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:xa(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Pu(o)}`),path:Su(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Ze(c.ref,l.ref))){if(await Ot(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Ir({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Ir({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!yi(s.originalDocument.identity,d.identity)||!yi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain);continue}if(!await rS(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await X.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!yi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await X.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Ir({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Ir({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:un.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!oS(s.document.identity,l.identity)||!yi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:xa(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Pu(o)}`),path:Su(e.paths,e.name)}]}}async function lD(e,t){let i=H(e,t),r=i,n=se.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Eu(i,n);a=await X.readdir(n,{withFileTypes:!0}),await Ot(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!ku.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Ze);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Pu(o)}`);let s=[],c=0;for(let l of ku){if(!a.some(p=>p.name===l))continue;let u=se.join(n,l),d=await Eu(r,u),f=(await X.readdir(u,{withFileTypes:!0})).sort((p,v)=>Ze(p.name,v.name));await Ot(d);for(let p of f){if(s.length>=Oi.maxDocuments)throw new Error(`Native evidence store exceeds ${Oi.maxDocuments} documents`);let v=un.exec(p.name);if(!v||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let h=cS(l,v[1]),m=se.join(u,p.name);await T(j(e,m),m);let N=await Ir({changeRoot:r,file:m,ref:h,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=N.size,c>Oi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Oi.maxScannedBytes} scanned bytes`);s.push(N)}await Ot(d)}return s}function nS(e,t){let i=new Set,r=[...e].sort(Ze).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Ze).reverse())i.has(o)||r.push(o)}return i}function uD(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ze),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Ze))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function dD(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=nS(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Oi.minimumAgeMs&&a.add(c.ref);for(let c of ku){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ze(u.ref,d.ref)).slice(0,Oi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=nS(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Oi.minimumAgeMs).sort((c,l)=>Ze(c.ref,l.ref));return{candidates:uD(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Pu(e){let t=e.slice(0,Oi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function xa(e){let t=Oi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Up(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Ze);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:xa(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Pu(n)}`),path:r}}async function aS(e,t){try{await X.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await X.rename(e,t)}catch{}}async function fD(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ot(e.directoryChain);let i=await Ir({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:un.exec(se.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await X.lstat(e.file),n=await X.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!yi(e.identity,r)||!yi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=se.join(se.dirname(e.file),`.${se.basename(e.file)}.${iD()}.gc`);await X.rename(e.file,a);try{let[o,s]=await Promise.all([X.lstat(a),X.realpath(a)]);if(await Ot(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!oS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await aS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await X.rm(a),await Ot(e.directoryChain)}catch(o){throw await aS(a,e.file),o}}async function hD(e){if((await Ne(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await X.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await mt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function pD(e,t){if(t)return[t];let i;try{i=await X.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Ze)}async function mD(e,t){let i=await ui(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Ti(e,t),gs(e,t),Er(e,t)]);return r!==null||n!==null||a!==null}async function vD(e){if(await mD(e.paths,e.name))return[];let t=await ui(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await cD({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await lD(e.paths,e.name),a=dD(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Su(e.paths,e.name);if(!e.repair)return[...i.findings,Up(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await fD(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Up(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:xa(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Up(e.name,a,!0,o)]}async function lS(e){if(e.deferAll||await hD(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await pD(e.paths,e.name))try{a.push(...await vD({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:xa(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Su(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await he(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:xa(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as gD,randomUUID as YK}from"crypto";import{promises as Ns}from"fs";import ne from"path";var Xp=64*1024*1024,wD=256*1024,hS=16*1024*1024;async function et(e){try{return await Ns.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function yD(e){let t;try{t=await Ns.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await wt(e,i.name);if(r){await Pl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function ys(e,t){let i=[];async function r(n){let a=await pt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(n,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await Ns.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ie({root:e,file:c,maxBytes:Xp,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function ND(e,t,i,r){await oi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await pt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await Ns.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await oi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await sr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Xp,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Ca(e,t,i,r){let n=await ys(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await ys(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ne.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function bD(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function kD(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function SD(e){return`${e}.removing`}function uS(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function pS(e,t,i){return ne.join(cl(e,t).directory,`root-move-cleanup-${i}.json`)}function ED(e){return JSON.stringify(e,null,2)+`
251
+ `}function PD(e){return gD("sha256").update(e).digest("hex")}function RD(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function xD(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(RD);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function CD(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=ED(t);if(Buffer.byteLength(i,"utf8")>hS)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await ue(pS(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),PD(i)}async function AD(e){let t=await ie({root:e.paths.runtimeDir,file:pS(e.paths,e.id,e.cleanup.kind),maxBytes:hS,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return xD(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Yp(e){let t=await ys(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function dS(e){return e.ref.split("/").length}async function _D(e){let i=[...await Yp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>dS(a)-dS(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ne.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await rl({root:e.projectRoot,file:a,maxBytes:Xp,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Xf({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Yp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Xf({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function mS(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function TD(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function ID(e,t,i,r){for(let a of[e,t])try{let o=await mt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ne.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ie({root:i,file:n,maxBytes:wD,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function fS(e){let t=mS(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Zi(e.projectRoot,t),t}async function ws(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=mS(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Zi(e.projectRoot,i),i}async function Ru(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await et(e.target),a=await et(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await CD({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await ys(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await AD({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await et(e.target),a=await et(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await ty({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return ws({projectRoot:e.projectRoot,config:t,id:e.id})}return await Yp({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await ws({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await _D({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),ws({projectRoot:e.projectRoot,config:t,id:e.id})}async function jD(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await et(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=SD(e.staging);t=await Ru({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await ys(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await ND(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ca(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await fS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await et(e.destinationPaths.nativeRoot)){if(await et(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ca(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await et(e.staging))throw new Error("Native move staging tree is missing");await Ca(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ns.rename(e.staging,e.destinationPaths.nativeRoot)}t=await fS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await et(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=kD(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await et(e.sourcePaths.nativeRoot)&&await Ca(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Ru({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await yD(e.destinationPaths);let n=await mt(e.destinationPaths,e.pending.id);await zn(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Zi(e.projectRoot,o),o}async function vS(e){let t=await Ne(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await Be(e.projectRoot,i.fromArtifactRoot),n=await Be(e.projectRoot,i.toArtifactRoot),a=bD(n,i.id),o=await et(r.nativeRoot)?r:n,s=await er(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await ID(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await et(r.nativeRoot))throw v;let h=TD({id:i.id,paths:r,now:new Date});await dy(r,h),c={journal:h,paths:r}}if(e.strategy==="continue"){let v=await jD({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await et(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=uS(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await et(n.nativeRoot)&&await Ca(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Ru({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=uS(a,i.id);!t.native.pending_root_move?.cleanup&&await et(a)&&await Ca(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Ru({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await mt(r,i.id);await ll(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Zi(e.projectRoot,p),{activeNativeRoot:r.nativeRoot,config:p}}finally{await tr(s)}}var Aa=4096,$D=4096,OD=1024;async function jr(e,t,i){try{let r=await pt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Cu(e,t){let i=new Map(e.map(r=>[xe.resolve(r.file),{...r,file:xe.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await bo(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Ff(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function HD(e,t){let i=Hk(e),r;try{await T(e.projectRoot,i);let n=await pu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await Tr(e,r.change)?[]:(await $e(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await xu.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function DD(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function MD(e,t){let i=[],r=[];for(let n of await jr(e,e.transactionsDir,$D)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await mt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:xe.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await On([e],`doctor archive recovery ${a.id}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,"archive.lock")}],i)?(await Lk({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function FD(e,t,i){let r=[];for(let n of await jr(e,e.locksDir,OD)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=xe.join(e.locksDir,n.name);try{let o=await bo(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await Ff(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function LD(e,t,i=5){let r=[],n=t?await qp(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await qp(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:xe.join(e.changesDir,a.name,Re)});continue}let o=await Bp(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:xe.join(e.projectRoot,s.path)}:{}})}return r}async function BD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await Zn(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Yy(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:xe.join(H(e,n),"trajectory.jsonl")})}return i}async function qD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await No(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=Vr(e,n),s=rt(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await On([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Jt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await xu.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Jt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await xu.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await xu.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function VD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await kh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:ta(e,n),repair:"migrate"});continue}let a=await $e(e,n);await sN({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:ta(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:ta(e,n)})}return i}async function WD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=vs(e,n);try{let o=await gs(e,n),s=await ui(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:xe.join(e.changesDir,n,Re)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:xe.join(e.changesDir,n,Re),repair:"migrate"});continue}await tS({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:xe.join(e.changesDir,n,Re)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function zD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Ti(e,n)}catch(o){if(o instanceof as)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:ze(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await On([e],`doctor transition recovery ${n}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Lb(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:ze(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:ze(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:ze(e,n),repair:"continue"})}}return i}async function JD(e,t){let i=[],r=t.name?[t.name]:(await jr(e,e.changesDir,Aa)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Sr(e,n),o;try{o=await Er(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await On([e],`doctor checkpoint recovery ${n}`,async()=>await Cu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Qb(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function bs(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Ne(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([Be(r.projectRoot,c.fromArtifactRoot),Be(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Cu([{paths:l,file:xe.join(l.locksDir,"root-move.lock")},{paths:u,file:xe.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await vS({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await Be(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await DD(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await MD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await qD(r,{name:e.name,repair:t})),i.push(...await WD(r,{name:e.name,repair:t})),i.push(...await VD(r,{name:e.name,repair:t})),i.push(...await BD(r,{name:e.name,repair:t})),i.push(...await zD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await JD(r,{name:e.name,repair:t})),i.push(...await lS({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await FD(r,t,s.unfinished)),i.push(...await HD(r,t)),e.projectOnly||i.push(...await LD(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as GD}from"node:crypto";import{promises as He}from"node:fs";import dt from"node:path";var Qp=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function gS(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function wS(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=dt.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function Au(e){try{return await He.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function yS(e,t){let i=dt.normalize(dt.resolve(e)),r=dt.normalize(dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function UD(e,t){let i;try{i=await He.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=dt.join(e.archiveDir,n.name);try{let o=await Ue(dt.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function KD(e,t){let i=await el(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function dn(e,t){await He.mkdir(e.transactionsDir,{recursive:!0}),await te(nr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function YD(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Rn(e.paths.projectRoot);i.some(a=>yS(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Ne(a);if(!o)continue;let s=await Be(a,o.native.artifact_root);r.some(c=>yS(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await He.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Ue(dt.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await _l(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function XD(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function QD(e){let t=dt.join(e.paths.specsDir,e.change.capability),i=dt.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await He.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await He.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([He.realpath(e.paths.specsDir),He.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await He.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await He.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await He.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=dt.join(jt(e.paths,e.state.name),e.change.source);await ue(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await He.mkdir(t,{recursive:!0}),await ue(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function NS(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function ZD(e,t){let i=jt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Q({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function eM(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(NS(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Zp(e){return he(e.paths,`archive portable change ${e.name}`,async()=>{let t=XD(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await KD(e.paths,e.name),r=jt(e.paths,e.name),n=await Au(r),a=n?null:await UD(e.paths,e.name),o;if(n)o=await ka(e.paths,e.name);else if(i)o=await Ue(dt.join(wS(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await jk({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await $k({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=wS(e.paths,i?.archive_ref??gS(o)),c=await Au(s);if(i&&eM(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await hs(e.paths,o.name),await He.rm(rt(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)NS(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await YD({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new Qp(l);i={schema:Zc,id:GD(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:gS(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await ZD(e.paths,o),created_at:new Date().toISOString()},await dn(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await dn(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await QD({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await dn(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await dn(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await zr({file:bt(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await dn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await Au(r)?r:s;if(await fu({file:dt.join(l,"verification.md"),state:o}),await du({file:dt.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await dn(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await He.mkdir(e.paths.archiveDir,{recursive:!0}),await Au(s))throw new Error(`Native Archive target already exists: ${s}`);await He.rename(r,s),i={...i,status:"moved"},await dn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await hs(e.paths,o.name),await He.rm(rt(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await He.rm(nr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function _u(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?["comet","native","next",e.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as tM}from"node:crypto";import{promises as _a}from"node:fs";import xS from"node:path";var CS=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function iM(e){try{return await _a.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function em(e,t){let i=re(e,t),r=[nr(e,{kind:"migration",change:t}),Vr(e,t),...CS.map(n=>xS.join(i,n))];return(await Promise.all(r.map(iM))).some(Boolean)}async function rM(e,t){let i=await el(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function bS(e,t){await _a.mkdir(e.transactionsDir,{recursive:!0}),await te(nr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function kS(e,t){await Promise.all([_a.rm(rt(e,t),{recursive:!0,force:!0}),_a.rm(Vr(e,t),{recursive:!0,force:!0}),...CS.map(i=>_a.rm(xS.join(re(e,t),i),{force:!0}))])}async function SS(e,t){await Cr(cn(e,t.name),sn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ES(e,t){try{let i=await wt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function PS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=Ae(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function nM(e){let t=re(e.paths,e.state.name),i=await Q({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Jc({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function RS(e,t){let i=await _l(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function ks(e){return he(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await rM(e.paths,e.name),i=await Tr(e.paths,e.name)?await Ue(bt(e.paths,e.name)):null;if(!t&&i)return await kS(e.paths,e.name),await SS(e.paths,i),i;let r=null,n=null;for(t||(r=await RS(e.paths,e.name),n=await ES(e.paths,e.name),PS(e.paths,n),t={schema:Qc,id:tM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await bS(e.paths,t));;){let a=Jw(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await RS(e.paths,e.name),n??=await ES(e.paths,e.name),PS(e.paths,n),i=zw({state:r,acceptance:await nM({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Xc(bt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await kS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ue(bt(e.paths,e.name)),await SS(e.paths,i)),t={...t,status:a.nextStatus},await bS(e.paths,t)}return await _a.rm(nr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ue(bt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as AS}from"node:fs";import _S from"node:path";function aM(e,t){let i=Ae(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function oM(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function sM(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Ln(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ir(t),completed_at:i});return nt({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:oM(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function cM(e){try{let t=await uu(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function TS(e){return he(e.paths,`recover portable change ${e.name}`,async()=>{let t=await ka(e.paths,e.name);if(t.status==="done")return await hu({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=aM(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=cn(e.paths,e.name),n=await cM(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Cr(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await hu({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=jp({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await zr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await AS.rm(_S.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=sn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Cr(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=sM(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await zr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=sn({portableState:t,projectRoot:e.paths.projectRoot,branch:Ae(e.paths.projectRoot).currentBranch});return await AS.mkdir(_S.dirname(cn(e.paths,t.name)),{recursive:!0}),await Cr(r,d,{containedRoot:e.paths.runtimeDir}),await hu({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as IS}from"node:fs";function lM(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function uM(e,t){let i=Ae(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function Ta(e){let t=await Ok(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=uM(e.paths,t.state),n=await us({paths:e.paths,state:t.state}),a=_u(t.state,n),o=r.bindingState==="mismatch"?{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...a.runnerAction,kind:"none"}}:a;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:lM(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{children:n.children,readyChildren:n.readyChildren}:{},continuation:o,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function jS(e){let t;try{t=await IS.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await IS.readFile(`${jt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import rm from"path";var Tu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var $S=["--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."],im=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:$S,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, parent child readiness, or 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; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
252
+ comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, 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]
253
+ 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 tm(e,t){return`${e}:
254
+ ${t.map(i=>` ${i}`).join(`
255
+ `)}`}function dM(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return im[i]||t.length>1&&im[t[0]]?.subcommands?i:t[0]}function fM(e=[]){let t=dM(e),i=im[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",tm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...$S];return n&&n.length>0&&r.push("",tm("Options",n)),r.push("",`Output:
256
+ ${i.output}`),i.examples&&r.push("",tm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
257
+ `)}
258
+ `}}var hM=fM().usage;var W4=10*1024*1024,Ht=class extends Error{};function Iu(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Ht(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function ju(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ht(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new Ht(`${t} requires a value`);return e.splice(r,2),n}function HS(e){if(e.length>0)throw new Ht(`Unexpected argument: ${e[0]}`)}function OS(e,t){let i=rm.normalize(e),r=rm.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function pM(e){let t=rm.resolve(e),i=Ae(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ae(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!OS(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||OS(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function DS(e){return e?pM(e):$f(process.cwd())}async function MS(e){let t=await Ne(e);return Be(e,t?.native.artifact_root??"docs")}function Hi(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
259
+ `}}function FS(e,t){if(t instanceof Ht)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof mu)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 ps)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Bo)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 qo)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 Tu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ra)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 Pr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof cs)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function LS(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}})+`
260
+ `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Ss(e,t){let i=await us({paths:e,state:t});return _u(t,i)}async function mM(e){let t;try{t=await VS.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function vM(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function BS(e,t){let i;try{i=await VS.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${vM(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:Ou.join(e.archiveDir,n.name)}:null}function gM(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function $u(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function qS(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:Ou.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function wM(e,t){let i=[],r=[];for(let n of await Xw(e)){let a=Ur(n);if(t&&a.change!==t)continue;let o=Ou.join(e.transactionsDir,n);try{let s=await Ro(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function nm(e,t){let i=Iu(e,"--repair"),r=ju(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Ht("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();HS(e);let a=await MS(t),o=await wM(a,n);if(n&&o.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let d=await Tr(a,n)?await Ta({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await Zp({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ss(a,v.state)})}let p=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:p.schema,stateVersion:p.state_version},state:p,continuation:await Ss(a,p)})}return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await Tr(a,n)){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([BS(a,n),em(a,n)]);if(u){let p=await Ta({paths:a,name:n,details:!0});return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[u],continuation:p.continuation})}if(d&&!i){let p=await Ta({paths:a,name:n,details:!0});return $u({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[qS(a,n)],continuation:p.continuation})}if(i){if(d){let v=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Ss(a,v)})}let p=await TS({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:p,continuation:await Ss(a,p.state)})}let f=await Ta({paths:a,name:n,details:!0});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await ks({paths:a,name:n});return Hi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ss(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await jS(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");if(i){let k=await bs({paths:a,repair:!0,projectOnly:!0}),b=[];for(let g of c.transactions)g.kind==="archive"?await Zp({paths:a,name:g.change}):await ks({paths:a,name:g.change}),b.push({kind:g.kind,change:g.change,transactionId:g.journal.id});let R=await nm([],t),w=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...w,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await mM(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),p=u.filter(k=>!d.has(k)),[v,h,m,N,y]=await Promise.all([Promise.all(s.map(k=>Ta({paths:a,name:k}))),Promise.all(s.map(k=>BS(a,k))),Promise.all(s.map(k=>em(a,k))),Promise.all(p.map(k=>bs({paths:a,name:k}))),bs({paths:a,projectOnly:!0})]),E=gM([...h.filter(k=>k!==null),...s.flatMap((k,b)=>m[b]&&!f.has(k)?[qS(a,k)]:[]),...c.findings,...p.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:Ou.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...N.flatMap(({findings:k})=>k),...y.findings]),S={healthy:E.every(k=>k.severity==="info"),workflow:p.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:p,findings:E};return S.healthy?Hi("doctor",S):$u(S)}let l=await bs({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Hi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}function yM(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}})+`
261
+ `}}async function WS(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{Iu(n,"--json"),s=ju(n,"--project-root");let u=[...n,...a],d=await DS(s);c=await t(u,d)}catch(u){c=FS(e,u)}let l=o?yM(c):LS(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
206
262
  `)?"":`
207
- `)),l.exitCode}process.exitCode=await VN("doctor",qN);
263
+ `)),l.exitCode}process.exitCode=await WS("doctor",nm);