@rpamis/comet 0.4.0-beta.13 → 0.4.0-beta.15

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 (361) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +13 -1
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/SKILL.md +6 -5
  5. package/assets/skills/comet/reference/subagent-dispatch.md +2 -4
  6. package/assets/skills/comet/rules/comet-phase-guard.en.md +4 -3
  7. package/assets/skills/comet/rules/comet-phase-guard.md +4 -3
  8. package/assets/skills/comet/rules/comet-workflow-guard.en.md +1 -1
  9. package/assets/skills/comet/rules/comet-workflow-guard.md +1 -1
  10. package/assets/skills/comet/scripts/comet-archive.mjs +85 -85
  11. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
  12. package/assets/skills/comet/scripts/comet-guard.mjs +111 -111
  13. package/assets/skills/comet/scripts/comet-handoff.mjs +85 -85
  14. package/assets/skills/comet/scripts/comet-hook-guard.mjs +91 -89
  15. package/assets/skills/comet/scripts/comet-hook-router.mjs +124 -116
  16. package/assets/skills/comet/scripts/comet-resume-probe.mjs +77 -77
  17. package/assets/skills/comet/scripts/comet-runtime.mjs +188 -185
  18. package/assets/skills/comet/scripts/comet-state.mjs +108 -107
  19. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +95 -95
  20. package/assets/skills/comet-any/SKILL.md +1 -1
  21. package/assets/skills/comet-any/reference/authoring-subagents.md +3 -11
  22. package/assets/skills/comet-any/reference/subagents/pause-points-author.md +1 -4
  23. package/assets/skills/comet-any/reference/subagents/reference-author.md +1 -4
  24. package/assets/skills/comet-any/reference/subagents/script-author.md +1 -4
  25. package/assets/skills/comet-any/reference/subagents/skill-core-author.md +1 -4
  26. package/assets/skills/comet-any/reference/subagents/skill-reviewer.md +1 -4
  27. package/assets/skills/comet-any/reference/subagents/workflow-entry-author.md +1 -4
  28. package/assets/skills/comet-build/SKILL.md +2 -2
  29. package/assets/skills/comet-native/SKILL.md +85 -11
  30. package/assets/skills/comet-native/reference/artifacts.md +3 -1
  31. package/assets/skills/comet-native/reference/commands.md +15 -6
  32. package/assets/skills/comet-native/reference/recovery.md +12 -1
  33. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +124 -118
  34. package/assets/skills/comet-native/scripts/comet-native-check.mjs +116 -110
  35. package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +110 -110
  36. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +121 -121
  37. package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +83 -83
  38. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +88 -82
  39. package/assets/skills/comet-native/scripts/comet-native-init.mjs +85 -85
  40. package/assets/skills/comet-native/scripts/comet-native-new.mjs +114 -114
  41. package/assets/skills/comet-native/scripts/comet-native-next.mjs +122 -122
  42. package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +124 -116
  43. package/assets/skills/comet-native/scripts/comet-native-root.mjs +110 -110
  44. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +154 -152
  45. package/assets/skills/comet-native/scripts/comet-native-select.mjs +110 -110
  46. package/assets/skills/comet-native/scripts/comet-native-show.mjs +80 -80
  47. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +112 -112
  48. package/assets/skills/comet-native/scripts/comet-native-status.mjs +107 -107
  49. package/assets/skills-zh/comet/SKILL.md +3 -3
  50. package/assets/skills-zh/comet/reference/subagent-dispatch.md +2 -4
  51. package/assets/skills-zh/comet-any/SKILL.md +1 -1
  52. package/assets/skills-zh/comet-any/reference/authoring-subagents.md +3 -14
  53. package/assets/skills-zh/comet-any/reference/subagents/pause-points-author.md +1 -4
  54. package/assets/skills-zh/comet-any/reference/subagents/reference-author.md +1 -4
  55. package/assets/skills-zh/comet-any/reference/subagents/script-author.md +1 -4
  56. package/assets/skills-zh/comet-any/reference/subagents/skill-core-author.md +1 -4
  57. package/assets/skills-zh/comet-any/reference/subagents/skill-reviewer.md +1 -4
  58. package/assets/skills-zh/comet-any/reference/subagents/workflow-entry-author.md +1 -4
  59. package/assets/skills-zh/comet-build/SKILL.md +2 -2
  60. package/assets/skills-zh/comet-native/SKILL.md +86 -12
  61. package/assets/skills-zh/comet-native/reference/artifacts.md +3 -1
  62. package/assets/skills-zh/comet-native/reference/commands.md +17 -8
  63. package/assets/skills-zh/comet-native/reference/recovery.md +14 -3
  64. package/bin/fast-runtime-router.js +1 -0
  65. package/dist/app/cli/index.js +1 -0
  66. package/dist/app/cli/index.js.map +1 -1
  67. package/dist/app/commands/doctor.d.ts.map +1 -1
  68. package/dist/app/commands/doctor.js +138 -37
  69. package/dist/app/commands/doctor.js.map +1 -1
  70. package/dist/app/commands/i18n.d.ts +1 -1
  71. package/dist/app/commands/i18n.d.ts.map +1 -1
  72. package/dist/app/commands/i18n.js +90 -0
  73. package/dist/app/commands/i18n.js.map +1 -1
  74. package/dist/app/commands/init.d.ts.map +1 -1
  75. package/dist/app/commands/init.js +45 -12
  76. package/dist/app/commands/init.js.map +1 -1
  77. package/dist/app/commands/project-scope-selection.d.ts +2 -1
  78. package/dist/app/commands/project-scope-selection.d.ts.map +1 -1
  79. package/dist/app/commands/project-scope-selection.js +5 -7
  80. package/dist/app/commands/project-scope-selection.js.map +1 -1
  81. package/dist/app/commands/uninstall.d.ts +6 -0
  82. package/dist/app/commands/uninstall.d.ts.map +1 -1
  83. package/dist/app/commands/uninstall.js +197 -110
  84. package/dist/app/commands/uninstall.js.map +1 -1
  85. package/dist/app/commands/update.d.ts.map +1 -1
  86. package/dist/app/commands/update.js +81 -10
  87. package/dist/app/commands/update.js.map +1 -1
  88. package/dist/app/commands/workflow.d.ts +1 -0
  89. package/dist/app/commands/workflow.d.ts.map +1 -1
  90. package/dist/app/commands/workflow.js +9 -2
  91. package/dist/app/commands/workflow.js.map +1 -1
  92. package/dist/domains/comet-classic/classic-hook-guard.d.ts +5 -1
  93. package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
  94. package/dist/domains/comet-classic/classic-hook-guard.js +104 -20
  95. package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
  96. package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
  97. package/dist/domains/comet-classic/classic-layout-initialization.js +8 -4
  98. package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
  99. package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
  100. package/dist/domains/comet-classic/classic-layout.js +1 -0
  101. package/dist/domains/comet-classic/classic-layout.js.map +1 -1
  102. package/dist/domains/comet-classic/classic-plan-readiness.d.ts +12 -0
  103. package/dist/domains/comet-classic/classic-plan-readiness.d.ts.map +1 -0
  104. package/dist/domains/comet-classic/classic-plan-readiness.js +26 -0
  105. package/dist/domains/comet-classic/classic-plan-readiness.js.map +1 -0
  106. package/dist/domains/comet-classic/classic-project-config.d.ts +1 -0
  107. package/dist/domains/comet-classic/classic-project-config.d.ts.map +1 -1
  108. package/dist/domains/comet-classic/classic-project-config.js +13 -7
  109. package/dist/domains/comet-classic/classic-project-config.js.map +1 -1
  110. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  111. package/dist/domains/comet-classic/classic-state-command.js +58 -7
  112. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  113. package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
  114. package/dist/domains/comet-entry/hook-adapter.js +15 -2
  115. package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
  116. package/dist/domains/comet-entry/hook-project-root.d.ts +3 -0
  117. package/dist/domains/comet-entry/hook-project-root.d.ts.map +1 -0
  118. package/dist/domains/comet-entry/hook-project-root.js +62 -0
  119. package/dist/domains/comet-entry/hook-project-root.js.map +1 -0
  120. package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -1
  121. package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
  122. package/dist/domains/comet-entry/hook-router-entry.js +6 -4
  123. package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
  124. package/dist/domains/comet-entry/hook-router.d.ts +2 -0
  125. package/dist/domains/comet-entry/hook-router.d.ts.map +1 -1
  126. package/dist/domains/comet-entry/hook-router.js +45 -9
  127. package/dist/domains/comet-entry/hook-router.js.map +1 -1
  128. package/dist/domains/comet-entry/hook-types.d.ts +1 -0
  129. package/dist/domains/comet-entry/hook-types.d.ts.map +1 -1
  130. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  131. package/dist/domains/comet-entry/init-workflow.js +2 -3
  132. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  133. package/dist/domains/comet-entry/project-activation.d.ts +12 -0
  134. package/dist/domains/comet-entry/project-activation.d.ts.map +1 -0
  135. package/dist/domains/comet-entry/project-activation.js +109 -0
  136. package/dist/domains/comet-entry/project-activation.js.map +1 -0
  137. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  138. package/dist/domains/comet-entry/resume-probe.js +47 -26
  139. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  140. package/dist/domains/comet-entry/types.d.ts +1 -1
  141. package/dist/domains/comet-entry/types.d.ts.map +1 -1
  142. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  143. package/dist/domains/comet-native/native-archive-command.js +43 -1
  144. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  145. package/dist/domains/comet-native/native-archive-inspection.d.ts.map +1 -1
  146. package/dist/domains/comet-native/native-archive-inspection.js +11 -0
  147. package/dist/domains/comet-native/native-archive-inspection.js.map +1 -1
  148. package/dist/domains/comet-native/native-archive-preflight.d.ts +10 -0
  149. package/dist/domains/comet-native/native-archive-preflight.d.ts.map +1 -1
  150. package/dist/domains/comet-native/native-archive-preflight.js +44 -0
  151. package/dist/domains/comet-native/native-archive-preflight.js.map +1 -1
  152. package/dist/domains/comet-native/native-change.d.ts +18 -1
  153. package/dist/domains/comet-native/native-change.d.ts.map +1 -1
  154. package/dist/domains/comet-native/native-change.js +72 -3
  155. package/dist/domains/comet-native/native-change.js.map +1 -1
  156. package/dist/domains/comet-native/native-check.d.ts.map +1 -1
  157. package/dist/domains/comet-native/native-check.js +13 -1
  158. package/dist/domains/comet-native/native-check.js.map +1 -1
  159. package/dist/domains/comet-native/native-cli-shared.d.ts +2 -2
  160. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  161. package/dist/domains/comet-native/native-cli-shared.js +24 -3
  162. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  163. package/dist/domains/comet-native/native-conflict-inspection.d.ts +3 -1
  164. package/dist/domains/comet-native/native-conflict-inspection.d.ts.map +1 -1
  165. package/dist/domains/comet-native/native-conflict-inspection.js +20 -10
  166. package/dist/domains/comet-native/native-conflict-inspection.js.map +1 -1
  167. package/dist/domains/comet-native/native-continuation.d.ts.map +1 -1
  168. package/dist/domains/comet-native/native-continuation.js +16 -0
  169. package/dist/domains/comet-native/native-continuation.js.map +1 -1
  170. package/dist/domains/comet-native/native-diagnostics.d.ts +2 -0
  171. package/dist/domains/comet-native/native-diagnostics.d.ts.map +1 -1
  172. package/dist/domains/comet-native/native-diagnostics.js +43 -32
  173. package/dist/domains/comet-native/native-diagnostics.js.map +1 -1
  174. package/dist/domains/comet-native/native-evidence-storage.d.ts +6 -0
  175. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  176. package/dist/domains/comet-native/native-evidence-storage.js +24 -0
  177. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  178. package/dist/domains/comet-native/native-findings.d.ts.map +1 -1
  179. package/dist/domains/comet-native/native-findings.js +36 -0
  180. package/dist/domains/comet-native/native-findings.js.map +1 -1
  181. package/dist/domains/comet-native/native-hook-guard.js +2 -2
  182. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  183. package/dist/domains/comet-native/native-new-command.d.ts.map +1 -1
  184. package/dist/domains/comet-native/native-new-command.js +22 -7
  185. package/dist/domains/comet-native/native-new-command.js.map +1 -1
  186. package/dist/domains/comet-native/native-receipt-command.d.ts.map +1 -1
  187. package/dist/domains/comet-native/native-receipt-command.js +14 -1
  188. package/dist/domains/comet-native/native-receipt-command.js.map +1 -1
  189. package/dist/domains/comet-native/native-receipt-errors.d.ts +23 -0
  190. package/dist/domains/comet-native/native-receipt-errors.d.ts.map +1 -0
  191. package/dist/domains/comet-native/native-receipt-errors.js +9 -0
  192. package/dist/domains/comet-native/native-receipt-errors.js.map +1 -0
  193. package/dist/domains/comet-native/native-receipt-refresh.d.ts +3 -0
  194. package/dist/domains/comet-native/native-receipt-refresh.d.ts.map +1 -1
  195. package/dist/domains/comet-native/native-receipt-refresh.js +13 -2
  196. package/dist/domains/comet-native/native-receipt-refresh.js.map +1 -1
  197. package/dist/domains/comet-native/native-root-move.d.ts.map +1 -1
  198. package/dist/domains/comet-native/native-root-move.js +54 -1
  199. package/dist/domains/comet-native/native-root-move.js.map +1 -1
  200. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  201. package/dist/domains/comet-native/native-snapshot.js +71 -14
  202. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  203. package/dist/domains/comet-native/native-transitions.d.ts.map +1 -1
  204. package/dist/domains/comet-native/native-transitions.js +74 -42
  205. package/dist/domains/comet-native/native-transitions.js.map +1 -1
  206. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts +37 -4
  207. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  208. package/dist/domains/comet-native/native-verification-receipt-runtime.js +192 -4
  209. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  210. package/dist/domains/comet-native/native-verification-runtime.d.ts +27 -1
  211. package/dist/domains/comet-native/native-verification-runtime.d.ts.map +1 -1
  212. package/dist/domains/comet-native/native-verification-runtime.js +29 -6
  213. package/dist/domains/comet-native/native-verification-runtime.js.map +1 -1
  214. package/dist/domains/comet-native/native-workspace.d.ts +39 -3
  215. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  216. package/dist/domains/comet-native/native-workspace.js +200 -8
  217. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  218. package/dist/domains/dashboard/collector.d.ts +26 -1
  219. package/dist/domains/dashboard/collector.d.ts.map +1 -1
  220. package/dist/domains/dashboard/collector.js +381 -1
  221. package/dist/domains/dashboard/collector.js.map +1 -1
  222. package/dist/domains/dashboard/native-adapter.d.ts +15 -0
  223. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  224. package/dist/domains/dashboard/native-adapter.js +1 -1
  225. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  226. package/dist/domains/dashboard/native-collector.d.ts +26 -1
  227. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  228. package/dist/domains/dashboard/native-collector.js +284 -5
  229. package/dist/domains/dashboard/native-collector.js.map +1 -1
  230. package/dist/domains/dashboard/server.d.ts.map +1 -1
  231. package/dist/domains/dashboard/server.js +92 -3
  232. package/dist/domains/dashboard/server.js.map +1 -1
  233. package/dist/domains/dashboard/types.d.ts +41 -1
  234. package/dist/domains/dashboard/types.d.ts.map +1 -1
  235. package/dist/domains/dashboard/verify-parser.d.ts +1 -0
  236. package/dist/domains/dashboard/verify-parser.d.ts.map +1 -1
  237. package/dist/domains/dashboard/verify-parser.js +8 -4
  238. package/dist/domains/dashboard/verify-parser.js.map +1 -1
  239. package/dist/domains/dashboard/web/assets/{arc-mNt_SS1l.js → arc-ClrSujVb.js} +1 -1
  240. package/dist/domains/dashboard/web/assets/{architectureDiagram-3BPJPVTR-Bc5akVD6.js → architectureDiagram-3BPJPVTR-B4A_t84A.js} +1 -1
  241. package/dist/domains/dashboard/web/assets/{blockDiagram-GPEHLZMM-C43zhVBe.js → blockDiagram-GPEHLZMM-D72u2953.js} +1 -1
  242. package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-dToETarK.js → c4Diagram-AAUBKEIU-Ca5zba3N.js} +1 -1
  243. package/dist/domains/dashboard/web/assets/channel-B_u-_i2t.js +1 -0
  244. package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-C0oO137R.js → chunk-2J33WTMH-CCVPBm0J.js} +1 -1
  245. package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-CGms1fgI.js → chunk-4BX2VUAB-JYluRsP-.js} +1 -1
  246. package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-Bugl8v6f.js → chunk-55IACEB6-DfYm7pN7.js} +1 -1
  247. package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-8ATNMlBG.js → chunk-727SXJPM-CwghIMO9.js} +1 -1
  248. package/dist/domains/dashboard/web/assets/{chunk-AQP2D5EJ-BNYjSSqU.js → chunk-AQP2D5EJ-BA_zgMXZ.js} +1 -1
  249. package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-_nJAqSbe.js → chunk-FMBD7UC4-BAJLB5V6.js} +1 -1
  250. package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-lyxYm5NX.js → chunk-ND2GUHAM-Bj6HWRwi.js} +1 -1
  251. package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-PUMVeWpd.js → chunk-QZHKN3VN-B1kXfg5N.js} +1 -1
  252. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-BpA7BPgX.js +1 -0
  253. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-BpA7BPgX.js +1 -0
  254. package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-DzMqjexn.js → cose-bilkent-S5V4N54A-BBrkuiAU.js} +1 -1
  255. package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-B67ET0eq.js → cynefin-VYW2F7L2-DlFhgQHt.js} +1 -1
  256. package/dist/domains/dashboard/web/assets/{dagre-BM42HDAG-CQPMvRLK.js → dagre-BM42HDAG-B0Bk5oiP.js} +1 -1
  257. package/dist/domains/dashboard/web/assets/{demo-BuVau32v.js → demo-DZYPLZpF.js} +2 -2
  258. package/dist/domains/dashboard/web/assets/{diagram-2AECGRRQ-BRpLrFHM.js → diagram-2AECGRRQ-tvTUiBA2.js} +1 -1
  259. package/dist/domains/dashboard/web/assets/{diagram-5GNKFQAL-CPGWuGrE.js → diagram-5GNKFQAL-BZfcK29q.js} +1 -1
  260. package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-D2wpX2iO.js → diagram-KO2AKTUF-BQahyP-C.js} +1 -1
  261. package/dist/domains/dashboard/web/assets/{diagram-LMA3HP47-D54mAbDu.js → diagram-LMA3HP47-D5bJnW2C.js} +1 -1
  262. package/dist/domains/dashboard/web/assets/{diagram-OG6HWLK6-ZGQDpSs_.js → diagram-OG6HWLK6-DTwWdzWJ.js} +1 -1
  263. package/dist/domains/dashboard/web/assets/{erDiagram-TEJ5UH35-C3qDo7sd.js → erDiagram-TEJ5UH35-BbvrdCp9.js} +1 -1
  264. package/dist/domains/dashboard/web/assets/{flowDiagram-I6XJVG4X-B7hStPd9.js → flowDiagram-I6XJVG4X-DgbR7Tcc.js} +1 -1
  265. package/dist/domains/dashboard/web/assets/{ganttDiagram-6RSMTGT7-IqcLFbTK.js → ganttDiagram-6RSMTGT7-wWMOA7F4.js} +1 -1
  266. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-YrMZpzUu.js → gitGraphDiagram-PVQCEYII-DCxvMAUJ.js} +1 -1
  267. package/dist/domains/dashboard/web/assets/index-Bk1o-4VO.css +1 -0
  268. package/dist/domains/dashboard/web/assets/{index-icxk8_BP.js → index-Blit0P5Z.js} +1 -1
  269. package/dist/domains/dashboard/web/assets/index-g8vyW0R_.js +257 -0
  270. package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-CcIgGK_7.js → infoDiagram-5YYISTIA-9qXEkzDe.js} +1 -1
  271. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-1x3rNjGP.js → ishikawaDiagram-YF4QCWOH-Dkf5othW.js} +1 -1
  272. package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-B2XiqMNP.js → journeyDiagram-JHISSGLW-C2_IkO4s.js} +1 -1
  273. package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-x46cGuo3.js → kanban-definition-UN3LZRKU-BxWgu4DL.js} +1 -1
  274. package/dist/domains/dashboard/web/assets/{linear-DFLqGZWl.js → linear-Dkr6p-Ro.js} +1 -1
  275. package/dist/domains/dashboard/web/assets/{mermaid.core-g3J6BACc.js → mermaid.core-DZUcsoG4.js} +4 -4
  276. package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-CTdeKmcX.js → mindmap-definition-RKZ34NQL-C9xyxGfa.js} +1 -1
  277. package/dist/domains/dashboard/web/assets/{pieDiagram-4H26LBE5-C_obwjIf.js → pieDiagram-4H26LBE5-Dn67tdOF.js} +1 -1
  278. package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-B6Gnfz9M.js → quadrantDiagram-W4KKPZXB-Cy6iOcxc.js} +1 -1
  279. package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-nX4PObnB.js → requirementDiagram-4Y6WPE33-B_gZONhx.js} +1 -1
  280. package/dist/domains/dashboard/web/assets/{sankeyDiagram-5OEKKPKP-QjDwwHgl.js → sankeyDiagram-5OEKKPKP-C3u-4dOk.js} +1 -1
  281. package/dist/domains/dashboard/web/assets/{sequenceDiagram-3UESZ5HK-BEEe0j6B.js → sequenceDiagram-3UESZ5HK-Xd3ByTVF.js} +1 -1
  282. package/dist/domains/dashboard/web/assets/{stateDiagram-AJRCARHV-CXfAaBgM.js → stateDiagram-AJRCARHV-CJGHL7Up.js} +1 -1
  283. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-rKvBgr6I.js +1 -0
  284. package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-BOzX2EnD.js → timeline-definition-PNZ67QCA-DvONX2YQ.js} +1 -1
  285. package/dist/domains/dashboard/web/assets/{vennDiagram-CIIHVFJN-C40vhXRq.js → vennDiagram-CIIHVFJN-B-L4qWy4.js} +1 -1
  286. package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-B1rm89JH.js → wardleyDiagram-YWT4CUSO-cf39WX2o.js} +1 -1
  287. package/dist/domains/dashboard/web/assets/{xychartDiagram-2RQKCTM6-BlMr59qK.js → xychartDiagram-2RQKCTM6-Dk1vcm3u.js} +1 -1
  288. package/dist/domains/dashboard/web/index.html +16 -16
  289. package/dist/domains/integrations/openspec.d.ts.map +1 -1
  290. package/dist/domains/integrations/openspec.js +5 -2
  291. package/dist/domains/integrations/openspec.js.map +1 -1
  292. package/dist/domains/skill/hook-lifecycle.d.ts +9 -0
  293. package/dist/domains/skill/hook-lifecycle.d.ts.map +1 -0
  294. package/dist/domains/skill/hook-lifecycle.js +48 -0
  295. package/dist/domains/skill/hook-lifecycle.js.map +1 -0
  296. package/dist/domains/skill/platform-inspect.d.ts +2 -0
  297. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  298. package/dist/domains/skill/platform-inspect.js +170 -32
  299. package/dist/domains/skill/platform-inspect.js.map +1 -1
  300. package/dist/domains/skill/platform-install.d.ts +21 -1
  301. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  302. package/dist/domains/skill/platform-install.js +174 -31
  303. package/dist/domains/skill/platform-install.js.map +1 -1
  304. package/dist/domains/skill/project-hook-projection.d.ts +14 -0
  305. package/dist/domains/skill/project-hook-projection.d.ts.map +1 -0
  306. package/dist/domains/skill/project-hook-projection.js +41 -0
  307. package/dist/domains/skill/project-hook-projection.js.map +1 -0
  308. package/dist/domains/skill/project-instructions.d.ts +3 -0
  309. package/dist/domains/skill/project-instructions.d.ts.map +1 -1
  310. package/dist/domains/skill/project-instructions.js +8 -0
  311. package/dist/domains/skill/project-instructions.js.map +1 -1
  312. package/dist/domains/skill/uninstall.d.ts +6 -2
  313. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  314. package/dist/domains/skill/uninstall.js +192 -29
  315. package/dist/domains/skill/uninstall.js.map +1 -1
  316. package/dist/domains/workflow-contract/contained-atomic-write.d.ts +3 -0
  317. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  318. package/dist/domains/workflow-contract/contained-atomic-write.js +15 -2
  319. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  320. package/dist/domains/workflow-contract/global-config.d.ts +10 -0
  321. package/dist/domains/workflow-contract/global-config.d.ts.map +1 -0
  322. package/dist/domains/workflow-contract/global-config.js +117 -0
  323. package/dist/domains/workflow-contract/global-config.js.map +1 -0
  324. package/dist/domains/workflow-contract/hook-target-scope.d.ts +6 -0
  325. package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -0
  326. package/dist/domains/workflow-contract/hook-target-scope.js +51 -0
  327. package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -0
  328. package/dist/domains/workflow-contract/index.d.ts +2 -1
  329. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  330. package/dist/domains/workflow-contract/index.js +2 -1
  331. package/dist/domains/workflow-contract/index.js.map +1 -1
  332. package/dist/domains/workflow-contract/project-config-reader.d.ts +2 -0
  333. package/dist/domains/workflow-contract/project-config-reader.d.ts.map +1 -1
  334. package/dist/domains/workflow-contract/project-config-reader.js.map +1 -1
  335. package/dist/domains/workflow-contract/project-config-writer.d.ts.map +1 -1
  336. package/dist/domains/workflow-contract/project-config-writer.js +3 -2
  337. package/dist/domains/workflow-contract/project-config-writer.js.map +1 -1
  338. package/dist/domains/workflow-contract/project-config.d.ts +1 -0
  339. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  340. package/dist/domains/workflow-contract/project-config.js +9 -4
  341. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  342. package/dist/domains/workflow-contract/types.d.ts +3 -0
  343. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  344. package/dist/platform/install/platforms.d.ts +2 -0
  345. package/dist/platform/install/platforms.d.ts.map +1 -1
  346. package/dist/platform/install/platforms.js +1 -0
  347. package/dist/platform/install/platforms.js.map +1 -1
  348. package/dist/platform/paths/git-worktree.d.ts +4 -1
  349. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  350. package/dist/platform/paths/git-worktree.js +34 -1
  351. package/dist/platform/paths/git-worktree.js.map +1 -1
  352. package/eval/local/tests/scaffold/test_utils.py +74 -0
  353. package/eval/pyproject.toml +4 -4
  354. package/eval/scaffold/shell/docker.sh +5 -0
  355. package/package.json +1 -1
  356. package/dist/domains/dashboard/web/assets/channel-b2wWDG4F.js +0 -1
  357. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-B9SWZywo.js +0 -1
  358. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-B9SWZywo.js +0 -1
  359. package/dist/domains/dashboard/web/assets/index-DhtBssCt.js +0 -257
  360. package/dist/domains/dashboard/web/assets/index-pr3axVDI.css +0 -1
  361. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-CD3nS4cC.js +0 -1
@@ -1,181 +1,181 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var mg=Object.create;var Ru=Object.defineProperty;var vg=Object.getOwnPropertyDescriptor;var gg=Object.getOwnPropertyNames;var wg=Object.getPrototypeOf,yg=Object.prototype.hasOwnProperty;var Rr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Ng=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of gg(t))!yg.call(e,r)&&r!==i&&Ru(e,r,{get:()=>t[r],enumerable:!(n=vg(t,r))||n.enumerable});return e};var Pu=(e,t,i)=>(i=e!=null?mg(wg(e)):{},Ng(t||!e||!e.__esModule?Ru(i,"default",{value:e,enumerable:!0}):i,e));var M=R(re=>{"use strict";var $o=Symbol.for("yaml.alias"),Au=Symbol.for("yaml.document"),Pr=Symbol.for("yaml.map"),xu=Symbol.for("yaml.pair"),Ho=Symbol.for("yaml.scalar"),Ar=Symbol.for("yaml.seq"),at=Symbol.for("yaml.node.type"),bg=e=>!!e&&typeof e=="object"&&e[at]===$o,Sg=e=>!!e&&typeof e=="object"&&e[at]===Au,kg=e=>!!e&&typeof e=="object"&&e[at]===Pr,Eg=e=>!!e&&typeof e=="object"&&e[at]===xu,Tu=e=>!!e&&typeof e=="object"&&e[at]===Ho,Cg=e=>!!e&&typeof e=="object"&&e[at]===Ar;function Iu(e){if(e&&typeof e=="object")switch(e[at]){case Pr:case Ar:return!0}return!1}function Rg(e){if(e&&typeof e=="object")switch(e[at]){case $o:case Pr:case Ho:case Ar:return!0}return!1}var Pg=e=>(Tu(e)||Iu(e))&&!!e.anchor;re.ALIAS=$o;re.DOC=Au;re.MAP=Pr;re.NODE_TYPE=at;re.PAIR=xu;re.SCALAR=Ho;re.SEQ=Ar;re.hasAnchor=Pg;re.isAlias=bg;re.isCollection=Iu;re.isDocument=Sg;re.isMap=kg;re.isNode=Rg;re.isPair=Eg;re.isScalar=Tu;re.isSeq=Cg});var en=R(Do=>{"use strict";var ie=M(),he=Symbol("break visit"),_u=Symbol("skip children"),Ke=Symbol("remove node");function xr(e,t){let i=ju(t);ie.isDocument(e)?wi(null,e.contents,i,Object.freeze([e]))===Ke&&(e.contents=null):wi(null,e,i,Object.freeze([]))}xr.BREAK=he;xr.SKIP=_u;xr.REMOVE=Ke;function wi(e,t,i,n){let r=Ou(e,t,i,n);if(ie.isNode(r)||ie.isPair(r))return $u(e,n,r),wi(e,r,i,n);if(typeof r!="symbol"){if(ie.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=wi(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Ke&&(t.items.splice(a,1),a-=1)}}}else if(ie.isPair(t)){n=Object.freeze(n.concat(t));let a=wi("key",t.key,i,n);if(a===he)return he;a===Ke&&(t.key=null);let o=wi("value",t.value,i,n);if(o===he)return he;o===Ke&&(t.value=null)}}return r}async function Tr(e,t){let i=ju(t);ie.isDocument(e)?await yi(null,e.contents,i,Object.freeze([e]))===Ke&&(e.contents=null):await yi(null,e,i,Object.freeze([]))}Tr.BREAK=he;Tr.SKIP=_u;Tr.REMOVE=Ke;async function yi(e,t,i,n){let r=await Ou(e,t,i,n);if(ie.isNode(r)||ie.isPair(r))return $u(e,n,r),yi(e,r,i,n);if(typeof r!="symbol"){if(ie.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await yi(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Ke&&(t.items.splice(a,1),a-=1)}}}else if(ie.isPair(t)){n=Object.freeze(n.concat(t));let a=await yi("key",t.key,i,n);if(a===he)return he;a===Ke&&(t.key=null);let o=await yi("value",t.value,i,n);if(o===he)return he;o===Ke&&(t.value=null)}}return r}function ju(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 Ou(e,t,i,n){if(typeof i=="function")return i(e,t,n);if(ie.isMap(t))return i.Map?.(e,t,n);if(ie.isSeq(t))return i.Seq?.(e,t,n);if(ie.isPair(t))return i.Pair?.(e,t,n);if(ie.isScalar(t))return i.Scalar?.(e,t,n);if(ie.isAlias(t))return i.Alias?.(e,t,n)}function $u(e,t,i){let n=t[t.length-1];if(ie.isCollection(n))n.items[e]=i;else if(ie.isPair(n))e==="key"?n.key=i:n.value=i;else if(ie.isDocument(n))n.contents=i;else{let r=ie.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Do.visit=xr;Do.visitAsync=Tr});var Fo=R(Du=>{"use strict";var Hu=M(),Ag=en(),xg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Tg=e=>e.replace(/[!,[\]{}]/g,t=>xg[t]),tn=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+Tg(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&&Hu.isNode(t.contents)){let a={};Ag.visit(t.contents,(o,s)=>{Hu.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
- `)}};tn.defaultYaml={explicit:!1,version:"1.2"};tn.defaultTags={"!!":"tag:yaml.org,2002:"};Du.Directives=tn});var Ir=R(nn=>{"use strict";var Fu=M(),Ig=en();function _g(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 Lu(e){let t=new Set;return Ig.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function Mu(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function jg(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=Lu(e));let o=Mu(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Fu.isScalar(o.node)||Fu.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}}nn.anchorIsValid=_g;nn.anchorNames=Lu;nn.createNodeAnchors=jg;nn.findNewAnchor=Mu});var Lo=R(Bu=>{"use strict";function rn(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=rn(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=rn(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=rn(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=rn(e,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return e.call(t,i,n)}Bu.applyReviver=rn});var Nt=R(Vu=>{"use strict";var Og=M();function qu(e,t,i){if(Array.isArray(e))return e.map((n,r)=>qu(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!Og.hasAnchor(e))return e.toJSON(t,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=a=>{n.res=a,delete i.onCreate};let r=e.toJSON(t,i);return i.onCreate&&i.onCreate(r),r}return typeof e=="bigint"&&!i?.keep?Number(e):e}Vu.toJS=qu});var _r=R(Wu=>{"use strict";var $g=Lo(),zu=M(),Hg=Nt(),Mo=class{constructor(t){Object.defineProperty(this,zu.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(!zu.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=Hg.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?$g.applyReviver(a,{"":s},"",s):s}};Wu.NodeBase=Mo});var an=R(Ju=>{"use strict";var Dg=Ir(),Fg=en(),Ni=M(),Lg=_r(),Mg=Nt(),Bo=class extends Lg.NodeBase{constructor(t){super(Ni.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=[],Fg.visit(t,{Node:(a,o)=>{(Ni.isAlias(o)||Ni.hasAnchor(o))&&n.push(o)}}),i&&(i.aliasResolveCache=n));let r;for(let a of n){if(a===this)break;a.anchor===this.source&&(r=a)}return r}toJSON(t,i){if(!i)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:a}=i,o=this.resolve(r,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(Mg.toJS(o,null,i),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=jr(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(Dg.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 jr(e,t,i){if(Ni.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(Ni.isCollection(t)){let n=0;for(let r of t.items){let a=jr(e,r,i);a>n&&(n=a)}return n}else if(Ni.isPair(t)){let n=jr(e,t.key,i),r=jr(e,t.value,i);return Math.max(n,r)}return 1}Ju.Alias=Bo});var Z=R(qo=>{"use strict";var Bg=M(),qg=_r(),Vg=Nt(),zg=e=>!e||typeof e!="function"&&typeof e!="object",bt=class extends qg.NodeBase{constructor(t){super(Bg.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Vg.toJS(this.value,t,i)}toString(){return String(this.value)}};bt.BLOCK_FOLDED="BLOCK_FOLDED";bt.BLOCK_LITERAL="BLOCK_LITERAL";bt.PLAIN="PLAIN";bt.QUOTE_DOUBLE="QUOTE_DOUBLE";bt.QUOTE_SINGLE="QUOTE_SINGLE";qo.Scalar=bt;qo.isScalarValue=zg});var on=R(Gu=>{"use strict";var Wg=an(),Jt=M(),Uu=Z(),Jg="tag:yaml.org,2002:";function Ug(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 Gg(e,t,i){if(Jt.isDocument(e)&&(e=e.contents),Jt.isNode(e))return e;if(Jt.isPair(e)){let d=i.schema[Jt.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 Wg.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Jg+t.slice(2));let l=Ug(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Uu.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Jt.MAP]:Symbol.iterator in Object(e)?o[Jt.SEQ]:o[Jt.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 Uu.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Gu.createNode=Gg});var $r=R(Or=>{"use strict";var Kg=on(),Ye=M(),Yg=_r();function Vo(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 Kg.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Ku=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,zo=class extends Yg.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=>Ye.isNode(n)||Ye.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Ku(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(Ye.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vo(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(Ye.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&&Ye.isScalar(a)?a.value:a:Ye.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Ye.isPair(i))return!1;let n=i.value;return n==null||t&&Ye.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 Ye.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(Ye.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,Vo(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};Or.Collection=zo;Or.collectionFromPath=Vo;Or.isEmptyPath=Ku});var sn=R(Hr=>{"use strict";var Xg=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Wo(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Qg=(e,t,i)=>e.endsWith(`
6
- `)?Wo(i,t):i.includes(`
4
+ var Ag=Object.create;var Hu=Object.defineProperty;var xg=Object.getOwnPropertyDescriptor;var Tg=Object.getOwnPropertyNames;var Ig=Object.getPrototypeOf,_g=Object.prototype.hasOwnProperty;var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var jg=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Tg(t))!_g.call(e,r)&&r!==i&&Hu(e,r,{get:()=>t[r],enumerable:!(n=xg(t,r))||n.enumerable});return e};var Go=(e,t,i)=>(i=e!=null?Ag(Ig(e)):{},jg(t||!e||!e.__esModule?Hu(i,"default",{value:e,enumerable:!0}):i,e));var M=R(ae=>{"use strict";var Uo=Symbol.for("yaml.alias"),Fu=Symbol.for("yaml.document"),Or=Symbol.for("yaml.map"),Du=Symbol.for("yaml.pair"),Ko=Symbol.for("yaml.scalar"),$r=Symbol.for("yaml.seq"),ot=Symbol.for("yaml.node.type"),Og=e=>!!e&&typeof e=="object"&&e[ot]===Uo,$g=e=>!!e&&typeof e=="object"&&e[ot]===Fu,Hg=e=>!!e&&typeof e=="object"&&e[ot]===Or,Fg=e=>!!e&&typeof e=="object"&&e[ot]===Du,Lu=e=>!!e&&typeof e=="object"&&e[ot]===Ko,Dg=e=>!!e&&typeof e=="object"&&e[ot]===$r;function Mu(e){if(e&&typeof e=="object")switch(e[ot]){case Or:case $r:return!0}return!1}function Lg(e){if(e&&typeof e=="object")switch(e[ot]){case Uo:case Or:case Ko:case $r:return!0}return!1}var Mg=e=>(Lu(e)||Mu(e))&&!!e.anchor;ae.ALIAS=Uo;ae.DOC=Fu;ae.MAP=Or;ae.NODE_TYPE=ot;ae.PAIR=Du;ae.SCALAR=Ko;ae.SEQ=$r;ae.hasAnchor=Mg;ae.isAlias=Og;ae.isCollection=Mu;ae.isDocument=$g;ae.isMap=Hg;ae.isNode=Lg;ae.isPair=Fg;ae.isScalar=Lu;ae.isSeq=Dg});var an=R(Yo=>{"use strict";var re=M(),ve=Symbol("break visit"),Bu=Symbol("skip children"),Xe=Symbol("remove node");function Hr(e,t){let i=qu(t);re.isDocument(e)?bi(null,e.contents,i,Object.freeze([e]))===Xe&&(e.contents=null):bi(null,e,i,Object.freeze([]))}Hr.BREAK=ve;Hr.SKIP=Bu;Hr.REMOVE=Xe;function bi(e,t,i,n){let r=Vu(e,t,i,n);if(re.isNode(r)||re.isPair(r))return Wu(e,n,r),bi(e,r,i,n);if(typeof r!="symbol"){if(re.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=bi(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===ve)return ve;o===Xe&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){n=Object.freeze(n.concat(t));let a=bi("key",t.key,i,n);if(a===ve)return ve;a===Xe&&(t.key=null);let o=bi("value",t.value,i,n);if(o===ve)return ve;o===Xe&&(t.value=null)}}return r}async function Fr(e,t){let i=qu(t);re.isDocument(e)?await ki(null,e.contents,i,Object.freeze([e]))===Xe&&(e.contents=null):await ki(null,e,i,Object.freeze([]))}Fr.BREAK=ve;Fr.SKIP=Bu;Fr.REMOVE=Xe;async function ki(e,t,i,n){let r=await Vu(e,t,i,n);if(re.isNode(r)||re.isPair(r))return Wu(e,n,r),ki(e,r,i,n);if(typeof r!="symbol"){if(re.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await ki(a,t.items[a],i,n);if(typeof o=="number")a=o-1;else{if(o===ve)return ve;o===Xe&&(t.items.splice(a,1),a-=1)}}}else if(re.isPair(t)){n=Object.freeze(n.concat(t));let a=await ki("key",t.key,i,n);if(a===ve)return ve;a===Xe&&(t.key=null);let o=await ki("value",t.value,i,n);if(o===ve)return ve;o===Xe&&(t.value=null)}}return r}function qu(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 Vu(e,t,i,n){if(typeof i=="function")return i(e,t,n);if(re.isMap(t))return i.Map?.(e,t,n);if(re.isSeq(t))return i.Seq?.(e,t,n);if(re.isPair(t))return i.Pair?.(e,t,n);if(re.isScalar(t))return i.Scalar?.(e,t,n);if(re.isAlias(t))return i.Alias?.(e,t,n)}function Wu(e,t,i){let n=t[t.length-1];if(re.isCollection(n))n.items[e]=i;else if(re.isPair(n))e==="key"?n.key=i:n.value=i;else if(re.isDocument(n))n.contents=i;else{let r=re.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Yo.visit=Hr;Yo.visitAsync=Fr});var Xo=R(Ju=>{"use strict";var zu=M(),Bg=an(),qg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Vg=e=>e.replace(/[!,[\]{}]/g,t=>qg[t]),on=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+Vg(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&&zu.isNode(t.contents)){let a={};Bg.visit(t.contents,(o,s)=>{zu.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
+ `)}};on.defaultYaml={explicit:!1,version:"1.2"};on.defaultTags={"!!":"tag:yaml.org,2002:"};Ju.Directives=on});var Dr=R(sn=>{"use strict";var Gu=M(),Wg=an();function zg(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 Uu(e){let t=new Set;return Wg.visit(e,{Value(i,n){n.anchor&&t.add(n.anchor)}}),t}function Ku(e,t){for(let i=1;;++i){let n=`${e}${i}`;if(!t.has(n))return n}}function Jg(e,t){let i=[],n=new Map,r=null;return{onAnchor:a=>{i.push(a),r??(r=Uu(e));let o=Ku(t,r);return r.add(o),o},setAnchors:()=>{for(let a of i){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Gu.isScalar(o.node)||Gu.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}}sn.anchorIsValid=zg;sn.anchorNames=Uu;sn.createNodeAnchors=Jg;sn.findNewAnchor=Ku});var Qo=R(Yu=>{"use strict";function cn(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=cn(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=cn(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=cn(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=cn(e,n,r,a);o===void 0?delete n[r]:o!==a&&(n[r]=o)}return e.call(t,i,n)}Yu.applyReviver=cn});var bt=R(Qu=>{"use strict";var Gg=M();function Xu(e,t,i){if(Array.isArray(e))return e.map((n,r)=>Xu(n,String(r),i));if(e&&typeof e.toJSON=="function"){if(!i||!Gg.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}Qu.toJS=Xu});var Lr=R(ed=>{"use strict";var Ug=Qo(),Zu=M(),Kg=bt(),Zo=class{constructor(t){Object.defineProperty(this,Zu.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(!Zu.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=Kg.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof a=="function"?Ug.applyReviver(a,{"":s},"",s):s}};ed.NodeBase=Zo});var ln=R(td=>{"use strict";var Yg=Dr(),Xg=an(),Si=M(),Qg=Lr(),Zg=bt(),es=class extends Qg.NodeBase{constructor(t){super(Si.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=[],Xg.visit(t,{Node:(a,o)=>{(Si.isAlias(o)||Si.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||(Zg.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=Mr(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(Yg.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 Mr(e,t,i){if(Si.isAlias(t)){let n=t.resolve(e),r=i&&n&&i.get(n);return r?r.count*r.aliasCount:0}else if(Si.isCollection(t)){let n=0;for(let r of t.items){let a=Mr(e,r,i);a>n&&(n=a)}return n}else if(Si.isPair(t)){let n=Mr(e,t.key,i),r=Mr(e,t.value,i);return Math.max(n,r)}return 1}td.Alias=es});var te=R(ts=>{"use strict";var ew=M(),tw=Lr(),iw=bt(),nw=e=>!e||typeof e!="function"&&typeof e!="object",kt=class extends tw.NodeBase{constructor(t){super(ew.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:iw.toJS(this.value,t,i)}toString(){return String(this.value)}};kt.BLOCK_FOLDED="BLOCK_FOLDED";kt.BLOCK_LITERAL="BLOCK_LITERAL";kt.PLAIN="PLAIN";kt.QUOTE_DOUBLE="QUOTE_DOUBLE";kt.QUOTE_SINGLE="QUOTE_SINGLE";ts.Scalar=kt;ts.isScalarValue=nw});var un=R(nd=>{"use strict";var rw=ln(),Ut=M(),id=te(),aw="tag:yaml.org,2002:";function ow(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 sw(e,t,i){if(Ut.isDocument(e)&&(e=e.contents),Ut.isNode(e))return e;if(Ut.isPair(e)){let d=i.schema[Ut.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 rw.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=aw+t.slice(2));let l=ow(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new id.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Ut.MAP]:Symbol.iterator in Object(e)?o[Ut.SEQ]:o[Ut.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 id.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}nd.createNode=sw});var qr=R(Br=>{"use strict";var cw=un(),Qe=M(),lw=Lr();function is(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 cw.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 rd=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ns=class extends lw.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(n=>Qe.isNode(n)||Qe.isPair(n)?n.clone(t):n),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(rd(t))this.add(i);else{let[n,...r]=t,a=this.get(n,!0);if(Qe.isCollection(a))a.addIn(r,i);else if(a===void 0&&this.schema)this.set(n,is(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(t){let[i,...n]=t;if(n.length===0)return this.delete(i);let r=this.get(i,!0);if(Qe.isCollection(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}getIn(t,i){let[n,...r]=t,a=this.get(n,!0);return r.length===0?!i&&Qe.isScalar(a)?a.value:a:Qe.isCollection(a)?a.getIn(r,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!Qe.isPair(i))return!1;let n=i.value;return n==null||t&&Qe.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[i,...n]=t;if(n.length===0)return this.has(i);let r=this.get(i,!0);return Qe.isCollection(r)?r.hasIn(n):!1}setIn(t,i){let[n,...r]=t;if(r.length===0)this.set(n,i);else{let a=this.get(n,!0);if(Qe.isCollection(a))a.setIn(r,i);else if(a===void 0&&this.schema)this.set(n,is(this.schema,r,i));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}};Br.Collection=ns;Br.collectionFromPath=is;Br.isEmptyPath=rd});var dn=R(Vr=>{"use strict";var uw=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function rs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var dw=(e,t,i)=>e.endsWith(`
6
+ `)?rs(i,t):i.includes(`
7
7
  `)?`
8
- `+Wo(i,t):(e.endsWith(" ")?"":" ")+i;Hr.indentComment=Wo;Hr.lineComment=Qg;Hr.stringifyComment=Xg});var Xu=R(cn=>{"use strict";var Zg="flow",Jo="block",Dr="quoted";function ew(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,N=-1;i===Jo&&(h=Yu(e,h,t.length),h!==-1&&(d=h+c));for(let S;S=e[h+=1];){if(i===Dr&&S==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}N=h}if(S===`
9
- `)i===Jo&&(h=Yu(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
8
+ `+rs(i,t):(e.endsWith(" ")?"":" ")+i;Vr.indentComment=rs;Vr.lineComment=dw;Vr.stringifyComment=uw});var od=R(fn=>{"use strict";var fw="flow",as="block",Wr="quoted";function hw(e,t,i="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!r||r<0)return e;r<a&&(a=0);let c=Math.max(1+a,1+r-t.length);if(e.length<=c)return e;let l=[],u={},d=r-t.length;typeof n=="number"&&(n>r-Math.max(2,a)?l.push(0):d=r-n);let f,p,m=!1,h=-1,g=-1,S=-1;i===as&&(h=ad(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(i===Wr&&k==="\\"){switch(g=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(k===`
9
+ `)i===as&&(h=ad(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
10
10
  `&&p!==" "){let b=e[h+1];b&&b!==" "&&b!==`
11
- `&&b!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Dr){for(;p===" "||p===" ";)p=S,S=e[h+=1],m=!0;let b=h>N+1?h-2:v-1;if(u[b])return e;l.push(b),u[b]=!0,d=b+c,f=void 0}else m=!0}p=S}if(m&&s&&s(),l.length===0)return e;o&&o();let k=e.slice(0,l[0]);for(let S=0;S<l.length;++S){let b=l[S],C=l[S+1]||e.length;b===0?k=`
12
- ${t}${e.slice(0,C)}`:(i===Dr&&u[b]&&(k+=`${e[b]}\\`),k+=`
13
- ${t}${e.slice(b+1,C)}`)}return k}function Yu(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}cn.FOLD_BLOCK=Jo;cn.FOLD_FLOW=Zg;cn.FOLD_QUOTED=Dr;cn.foldFlowLines=ew});var un=R(Qu=>{"use strict";var Oe=Z(),St=Xu(),Lr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Mr=e=>/^(%|---|\.\.\.)/m.test(e);function tw(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 ln(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Mr(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
+ `&&b!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Wr){for(;p===" "||p===" ";)p=k,k=e[h+=1],m=!0;let b=h>S+1?h-2:g-1;if(u[b])return e;l.push(b),u[b]=!0,d=b+c,f=void 0}else m=!0}p=k}if(m&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let b=l[k],C=l[k+1]||e.length;b===0?N=`
12
+ ${t}${e.slice(0,C)}`:(i===Wr&&u[b]&&(N+=`${e[b]}\\`),N+=`
13
+ ${t}${e.slice(b+1,C)}`)}return N}function ad(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}fn.FOLD_BLOCK=as;fn.FOLD_FLOW=fw;fn.FOLD_QUOTED=Wr;fn.foldFlowLines=hw});var pn=R(sd=>{"use strict";var $e=te(),St=od(),Jr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Gr=e=>/^(%|---|\.\.\.)/m.test(e);function pw(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 hn(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:n}=t,r=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Gr(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(n||i[c+2]==='"'||i.length<r)c+=1;else{for(o+=i.slice(s,c)+`
16
16
 
17
17
  `;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,n?o:St.foldFlowLines(o,a,St.FOLD_QUOTED,Lr(t,!1))}function Uo(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return ln(e,t);let i=t.indent||(Mr(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?n:St.foldFlowLines(n,i,St.FOLD_FLOW,Lr(t,!1))}function bi(e,t){let{singleQuote:i}=t.options,n;if(i===!1)n=ln;else{let r=e.includes('"'),a=e.includes("'");r&&!a?n=Uo:a&&!r?n=ln:n=i?Uo:ln}return n(e,t)}var Go;try{Go=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,n?o:St.foldFlowLines(o,a,St.FOLD_QUOTED,Jr(t,!1))}function os(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return hn(e,t);let i=t.indent||(Gr(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?n:St.foldFlowLines(n,i,St.FOLD_FLOW,Jr(t,!1))}function Ei(e,t){let{singleQuote:i}=t.options,n;if(i===!1)n=hn;else{let r=e.includes('"'),a=e.includes("'");r&&!a?n=os:a&&!r?n=hn:n=i?os:hn}return n(e,t)}var ss;try{ss=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Go=/\n+(?!\n|$)/g}function Fr({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 bi(i,n);let l=n.indent||(n.forceBlockIndent||Mr(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Oe.Scalar.BLOCK_FOLDED?!1:t===Oe.Scalar.BLOCK_LITERAL?!0:!tw(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{ss=/\n+(?!\n|$)/g}function zr({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 Ei(i,n);let l=n.indent||(n.forceBlockIndent||Gr(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===$e.Scalar.BLOCK_FOLDED?!1:t===$e.Scalar.BLOCK_LITERAL?!0:!pw(i,c,l.length);if(!i)return u?`|
24
24
  `:`>
25
25
  `;let d,f;for(f=i.length;f>0;--f){let C=i[f-1];if(C!==`
26
26
  `&&C!==" "&&C!==" ")break}let p=i.substring(f),m=p.indexOf(`
27
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(Go,`$&${l}`));let h=!1,v,N=-1;for(v=0;v<i.length;++v){let C=i[v];if(C===" ")h=!0;else if(C===`
29
- `)N=v;else break}let k=i.substring(0,N<v?N+1:v);k&&(i=i.substring(k.length),k=k.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+d;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let C=i.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),y=!1,w=Lr(n,!0);o!=="folded"&&t!==Oe.Scalar.BLOCK_FOLDED&&(w.onOverflow=()=>{y=!0});let g=St.foldFlowLines(`${k}${C}${p}`,l,St.FOLD_BLOCK,w);if(!y)return`>${b}
31
- ${l}${g}`}return i=i.replace(/\n+/g,`$&${l}`),`|${b}
32
- ${l}${k}${i}${p}`}function iw(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 bi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?bi(a,t):Fr(e,t,i,n);if(!s&&!u&&r!==Oe.Scalar.PLAIN&&a.includes(`
35
- `))return Fr(e,t,i,n);if(Mr(a)){if(c==="")return t.forceBlockIndent=!0,Fr(e,t,i,n);if(s&&c===l)return bi(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 bi(a,t)}return s?d:St.foldFlowLines(d,c,St.FOLD_FLOW,Lr(t,!1))}function nw(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!==Oe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Oe.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Oe.Scalar.BLOCK_FOLDED:case Oe.Scalar.BLOCK_LITERAL:return r||a?bi(o.value,t):Fr(o,t,i,n);case Oe.Scalar.QUOTE_DOUBLE:return ln(o.value,t);case Oe.Scalar.QUOTE_SINGLE:return Uo(o.value,t);case Oe.Scalar.PLAIN:return iw(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}Qu.stringifyString=nw});var dn=R(Ko=>{"use strict";var rw=Ir(),kt=M(),aw=sn(),ow=un();function sw(e,t){let i=Object.assign({blockQuote:!0,commentString:aw.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 cw(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(kt.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 lw(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(kt.isScalar(e)||kt.isCollection(e))&&e.anchor;a&&rw.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 uw(e,t,i,n){if(kt.isPair(e))return e.toString(t,i,n);if(kt.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=kt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=cw(t.doc.schema.tags,a));let o=lw(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):kt.isScalar(a)?ow.stringifyString(a,t,i,n):a.toString(t,i,n);return o?kt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Ko.createStringifyContext=sw;Ko.stringify=uw});var id=R(td=>{"use strict";var ot=M(),Zu=Z(),ed=dn(),fn=sn();function dw({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=ot.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ot.isCollection(e)||!ot.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||ot.isCollection(e)||(ot.isScalar(e)?e.type===Zu.Scalar.BLOCK_FOLDED||e.type===Zu.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=ed.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+=fn.lineComment(v,i.indent,l(f)):h&&r&&r(),v;m&&(f=null),p?(f&&(v+=fn.lineComment(v,i.indent,l(f))),v=`? ${v}
38
- ${s}:`):(v=`${v}:`,f&&(v+=fn.lineComment(v,i.indent,l(f))));let N,k,S;ot.isNode(t)?(N=!!t.spaceBefore,k=t.commentBefore,S=t.comment):(N=!1,k=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&ot.isScalar(t)&&(i.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&ot.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let b=!1,C=ed.stringify(t,i,()=>b=!0,()=>h=!0),y=" ";if(f||N||k){if(y=N?`
39
- `:"",k){let w=l(k);y+=`
40
- ${fn.indentComment(w,i.indent)}`}C===""&&!i.inFlow?y===`
41
- `&&S&&(y=`
28
+ `&&(p=p.slice(0,-1)),p=p.replace(ss,`$&${l}`));let h=!1,g,S=-1;for(g=0;g<i.length;++g){let C=i[g];if(C===" ")h=!0;else if(C===`
29
+ `)S=g;else break}let N=i.substring(0,S<g?S+1:g);N&&(i=i.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+d;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let C=i.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),y=!1,w=Jr(n,!0);o!=="folded"&&t!==$e.Scalar.BLOCK_FOLDED&&(w.onOverflow=()=>{y=!0});let v=St.foldFlowLines(`${N}${C}${p}`,l,St.FOLD_BLOCK,w);if(!y)return`>${b}
31
+ ${l}${v}`}return i=i.replace(/\n+/g,`$&${l}`),`|${b}
32
+ ${l}${N}${i}${p}`}function mw(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 Ei(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?Ei(a,t):zr(e,t,i,n);if(!s&&!u&&r!==$e.Scalar.PLAIN&&a.includes(`
35
+ `))return zr(e,t,i,n);if(Gr(a)){if(c==="")return t.forceBlockIndent=!0,zr(e,t,i,n);if(s&&c===l)return Ei(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 Ei(a,t)}return s?d:St.foldFlowLines(d,c,St.FOLD_FLOW,Jr(t,!1))}function vw(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!==$e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=$e.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case $e.Scalar.BLOCK_FOLDED:case $e.Scalar.BLOCK_LITERAL:return r||a?Ei(o.value,t):zr(o,t,i,n);case $e.Scalar.QUOTE_DOUBLE:return hn(o.value,t);case $e.Scalar.QUOTE_SINGLE:return os(o.value,t);case $e.Scalar.PLAIN:return mw(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}sd.stringifyString=vw});var mn=R(cs=>{"use strict";var gw=Dr(),Et=M(),ww=dn(),yw=pn();function Nw(e,t){let i=Object.assign({blockQuote:!0,commentString:ww.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 bw(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(Et.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 kw(e,t,{anchors:i,doc:n}){if(!n.directives)return"";let r=[],a=(Et.isScalar(e)||Et.isCollection(e))&&e.anchor;a&&gw.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 Sw(e,t,i,n){if(Et.isPair(e))return e.toString(t,i,n);if(Et.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=Et.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=bw(t.doc.schema.tags,a));let o=kw(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):Et.isScalar(a)?yw.stringifyString(a,t,i,n):a.toString(t,i,n);return o?Et.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}cs.createStringifyContext=Nw;cs.stringify=Sw});var dd=R(ud=>{"use strict";var st=M(),cd=te(),ld=mn(),vn=dn();function Ew({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=st.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(st.isCollection(e)||!st.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||st.isCollection(e)||(st.isScalar(e)?e.type===cd.Scalar.BLOCK_FOLDED||e.type===cd.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=ld.stringify(e,i,()=>m=!0,()=>h=!0);if(!p&&!i.inFlow&&g.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return m&&n&&n(),g===""?"?":p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=vn.lineComment(g,i.indent,l(f)):h&&r&&r(),g;m&&(f=null),p?(f&&(g+=vn.lineComment(g,i.indent,l(f))),g=`? ${g}
38
+ ${s}:`):(g=`${g}:`,f&&(g+=vn.lineComment(g,i.indent,l(f))));let S,N,k;st.isNode(t)?(S=!!t.spaceBefore,N=t.commentBefore,k=t.comment):(S=!1,N=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&st.isScalar(t)&&(i.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&st.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let b=!1,C=ld.stringify(t,i,()=>b=!0,()=>h=!0),y=" ";if(f||S||N){if(y=S?`
39
+ `:"",N){let w=l(N);y+=`
40
+ ${vn.indentComment(w,i.indent)}`}C===""&&!i.inFlow?y===`
41
+ `&&k&&(y=`
42
42
 
43
43
  `):y+=`
44
- ${i.indent}`}else if(!p&&ot.isCollection(t)){let w=C[0],g=C.indexOf(`
45
- `),E=g!==-1,_=i.inFlow??t.flow??t.items.length===0;if(E||!_){let K=!1;if(E&&(w==="&"||w==="!")){let q=C.indexOf(" ");w==="&"&&q!==-1&&q<g&&C[q+1]==="!"&&(q=C.indexOf(" ",q+1)),(q===-1||g<q)&&(K=!0)}K||(y=`
44
+ ${i.indent}`}else if(!p&&st.isCollection(t)){let w=C[0],v=C.indexOf(`
45
+ `),E=v!==-1,I=i.inFlow??t.flow??t.items.length===0;if(E||!I){let U=!1;if(E&&(w==="&"||w==="!")){let q=C.indexOf(" ");w==="&"&&q!==-1&&q<v&&C[q+1]==="!"&&(q=C.indexOf(" ",q+1)),(q===-1||v<q)&&(U=!0)}U||(y=`
46
46
  ${i.indent}`)}}else(C===""||C[0]===`
47
- `)&&(y="");return v+=y+C,i.inFlow?b&&n&&n():S&&!b?v+=fn.lineComment(v,i.indent,l(S)):h&&r&&r(),v}td.stringifyPair=dw});var Xo=R(Yo=>{"use strict";var nd=Rr("process");function fw(e,...t){e==="debug"&&console.log(...t)}function hw(e,t){(e==="debug"||e==="warn")&&(typeof nd.emitWarning=="function"?nd.emitWarning(t):console.warn(t))}Yo.debug=fw;Yo.warn=hw});var Wr=R(zr=>{"use strict";var Vr=M(),rd=Z(),Br="<<",qr={identify:e=>e===Br||typeof e=="symbol"&&e.description===Br,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new rd.Scalar(Symbol(Br)),{addToJSMap:ad}),stringify:()=>Br},pw=(e,t)=>(qr.identify(t)||Vr.isScalar(t)&&(!t.type||t.type===rd.Scalar.PLAIN)&&qr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===qr.tag&&i.default);function ad(e,t,i){let n=od(e,i);if(Vr.isSeq(n))for(let r of n.items)Qo(e,t,r);else if(Array.isArray(n))for(let r of n)Qo(e,t,r);else Qo(e,t,n)}function Qo(e,t,i){let n=od(e,i);if(!Vr.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 od(e,t){return e&&Vr.isAlias(t)?t.resolve(e.doc,e):t}zr.addMergeToJSMap=ad;zr.isMergeKey=pw;zr.merge=qr});var es=R(ld=>{"use strict";var mw=Xo(),sd=Wr(),vw=dn(),cd=M(),Zo=Nt();function gw(e,t,{key:i,value:n}){if(cd.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(sd.isMergeKey(e,i))sd.addMergeToJSMap(e,t,n);else{let r=Zo.toJS(i,"",e);if(t instanceof Map)t.set(r,Zo.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=ww(i,r,e),o=Zo.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 ww(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(cd.isNode(e)&&i?.doc){let n=vw.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)+'..."'),mw.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)}ld.addPairToJSMap=gw});var Et=R(ts=>{"use strict";var ud=on(),yw=id(),Nw=es(),Jr=M();function bw(e,t,i){let n=ud.createNode(e,void 0,i),r=ud.createNode(t,void 0,i);return new Ur(n,r)}var Ur=class e{constructor(t,i=null){Object.defineProperty(this,Jr.NODE_TYPE,{value:Jr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return Jr.isNode(i)&&(i=i.clone(t)),Jr.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return Nw.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?yw.stringifyPair(this,t,i,n):JSON.stringify(this)}};ts.Pair=Ur;ts.createPair=bw});var is=R(fd=>{"use strict";var Ut=M(),dd=dn(),Gr=sn();function Sw(e,t,i){return(t.inFlow??e.flow?Ew:kw)(e,t,i)}function kw({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(Ut.isNode(h))!d&&h.spaceBefore&&f.push(""),Kr(i,f,h.commentBefore,d),h.comment&&(v=h.comment);else if(Ut.isPair(h)){let k=Ut.isNode(h.key)?h.key:null;k&&(!d&&k.spaceBefore&&f.push(""),Kr(i,f,k.commentBefore,d))}d=!1;let N=dd.stringify(h,u,()=>v=null,()=>d=!0);v&&(N+=Gr.lineComment(N,a,l(v))),d&&v&&(d=!1),f.push(n+N)}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?`
47
+ `)&&(y="");return g+=y+C,i.inFlow?b&&n&&n():k&&!b?g+=vn.lineComment(g,i.indent,l(k)):h&&r&&r(),g}ud.stringifyPair=Ew});var us=R(ls=>{"use strict";var fd=jr("process");function Cw(e,...t){e==="debug"&&console.log(...t)}function Rw(e,t){(e==="debug"||e==="warn")&&(typeof fd.emitWarning=="function"?fd.emitWarning(t):console.warn(t))}ls.debug=Cw;ls.warn=Rw});var Qr=R(Xr=>{"use strict";var Yr=M(),hd=te(),Ur="<<",Kr={identify:e=>e===Ur||typeof e=="symbol"&&e.description===Ur,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new hd.Scalar(Symbol(Ur)),{addToJSMap:pd}),stringify:()=>Ur},Pw=(e,t)=>(Kr.identify(t)||Yr.isScalar(t)&&(!t.type||t.type===hd.Scalar.PLAIN)&&Kr.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Kr.tag&&i.default);function pd(e,t,i){let n=md(e,i);if(Yr.isSeq(n))for(let r of n.items)ds(e,t,r);else if(Array.isArray(n))for(let r of n)ds(e,t,r);else ds(e,t,n)}function ds(e,t,i){let n=md(e,i);if(!Yr.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 md(e,t){return e&&Yr.isAlias(t)?t.resolve(e.doc,e):t}Xr.addMergeToJSMap=pd;Xr.isMergeKey=Pw;Xr.merge=Kr});var hs=R(wd=>{"use strict";var Aw=us(),vd=Qr(),xw=mn(),gd=M(),fs=bt();function Tw(e,t,{key:i,value:n}){if(gd.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,n);else if(vd.isMergeKey(e,i))vd.addMergeToJSMap(e,t,n);else{let r=fs.toJS(i,"",e);if(t instanceof Map)t.set(r,fs.toJS(n,r,e));else if(t instanceof Set)t.add(r);else{let a=Iw(i,r,e),o=fs.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 Iw(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(gd.isNode(e)&&i?.doc){let n=xw.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)+'..."'),Aw.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)}wd.addPairToJSMap=Tw});var Ct=R(ps=>{"use strict";var yd=un(),_w=dd(),jw=hs(),Zr=M();function Ow(e,t,i){let n=yd.createNode(e,void 0,i),r=yd.createNode(t,void 0,i);return new ea(n,r)}var ea=class e{constructor(t,i=null){Object.defineProperty(this,Zr.NODE_TYPE,{value:Zr.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:n}=this;return Zr.isNode(i)&&(i=i.clone(t)),Zr.isNode(n)&&(n=n.clone(t)),new e(i,n)}toJSON(t,i){let n=i?.mapAsMap?new Map:{};return jw.addPairToJSMap(i,n,this)}toString(t,i,n){return t?.doc?_w.stringifyPair(this,t,i,n):JSON.stringify(this)}};ps.Pair=ea;ps.createPair=Ow});var ms=R(bd=>{"use strict";var Kt=M(),Nd=mn(),ta=dn();function $w(e,t,i){return(t.inFlow??e.flow?Fw:Hw)(e,t,i)}function Hw({comment:e,items:t},i,{blockItemPrefix:n,flowChars:r,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(Kt.isNode(h))!d&&h.spaceBefore&&f.push(""),ia(i,f,h.commentBefore,d),h.comment&&(g=h.comment);else if(Kt.isPair(h)){let N=Kt.isNode(h.key)?h.key:null;N&&(!d&&N.spaceBefore&&f.push(""),ia(i,f,N.commentBefore,d))}d=!1;let S=Nd.stringify(h,u,()=>g=null,()=>d=!0);g&&(S+=ta.lineComment(S,a,l(g))),d&&g&&(d=!1),f.push(n+S)}let p;if(f.length===0)p=r.start+r.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
48
48
  ${c}${h}`:`
49
49
  `}}return e?(p+=`
50
- `+Gr.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Ew({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(Ut.isNode(h))h.spaceBefore&&d.push(""),Kr(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(Ut.isPair(h)){let k=Ut.isNode(h.key)?h.key:null;k&&(k.spaceBefore&&d.push(""),Kr(t,d,k.commentBefore,!1),k.comment&&(l=!0));let S=Ut.isNode(h.value)?h.value:null;S?(S.comment&&(v=S.comment),S.commentBefore&&(l=!0)):h.value==null&&k?.comment&&(v=k.comment)}v&&(l=!0);let N=dd.stringify(h,c,()=>v=null);l||(l=d.length>u||N.includes(`
51
- `)),m<e.length-1?N+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((k,S)=>k+S.length+2,2)+(N.length+2)>t.options.lineWidth)),l&&(N+=",")),v&&(N+=Gr.lineComment(N,n,s(v))),d.push(N),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?`
50
+ `+ta.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Fw({items:e},t,{flowChars:i,itemIndent:n}){let{indent:r,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;n+=a;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(Kt.isNode(h))h.spaceBefore&&d.push(""),ia(t,d,h.commentBefore,!1),h.comment&&(g=h.comment);else if(Kt.isPair(h)){let N=Kt.isNode(h.key)?h.key:null;N&&(N.spaceBefore&&d.push(""),ia(t,d,N.commentBefore,!1),N.comment&&(l=!0));let k=Kt.isNode(h.value)?h.value:null;k?(k.comment&&(g=k.comment),k.commentBefore&&(l=!0)):h.value==null&&N?.comment&&(g=N.comment)}g&&(l=!0);let S=Nd.stringify(h,c,()=>g=null);l||(l=d.length>u||S.includes(`
51
+ `)),m<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((N,k)=>N+k.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),g&&(S+=ta.lineComment(S,n,s(g))),d.push(S),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,g)=>h+g.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?`
52
52
  ${a}${r}${h}`:`
53
53
  `;return`${m}
54
- ${r}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Kr({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=Gr.indentComment(t(n),e);i.push(a.trimStart())}}fd.stringifyCollection=Sw});var Rt=R(rs=>{"use strict";var Cw=is(),Rw=es(),Pw=$r(),Ct=M(),Yr=Et(),Aw=Z();function hn(e,t){let i=Ct.isScalar(t)?t.value:t;for(let n of e)if(Ct.isPair(n)&&(n.key===t||n.key===i||Ct.isScalar(n.key)&&n.key.value===i))return n}var ns=class extends Pw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ct.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(Yr.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;Ct.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new Yr.Pair(t,t?.value):n=new Yr.Pair(t.key,t.value);let r=hn(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);Ct.isScalar(r.value)&&Aw.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=hn(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=hn(this.items,t)?.value;return(!i&&Ct.isScalar(r)?r.value:r)??void 0}has(t){return!!hn(this.items,t)}set(t,i){this.add(new Yr.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)Rw.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!Ct.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})),Cw.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};rs.YAMLMap=ns;rs.findPair=hn});var Si=R(pd=>{"use strict";var xw=M(),hd=Rt(),Tw={collection:"map",default:!0,nodeClass:hd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return xw.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>hd.YAMLMap.from(e,t,i)};pd.map=Tw});var Pt=R(md=>{"use strict";var Iw=on(),_w=is(),jw=$r(),Qr=M(),Ow=Z(),$w=Nt(),as=class extends jw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Qr.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Xr(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=Xr(t);if(typeof n!="number")return;let r=this.items[n];return!i&&Qr.isScalar(r)?r.value:r}has(t){let i=Xr(t);return typeof i=="number"&&i<this.items.length}set(t,i){let n=Xr(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[n];Qr.isScalar(r)&&Ow.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($w.toJS(a,String(r++),i));return n}toString(t,i,n){return t?_w.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(Iw.createNode(s,void 0,n))}}return a}};function Xr(e){let t=Qr.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}md.YAMLSeq=as});var ki=R(gd=>{"use strict";var Hw=M(),vd=Pt(),Dw={collection:"seq",default:!0,nodeClass:vd.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Hw.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>vd.YAMLSeq.from(e,t,i)};gd.seq=Dw});var pn=R(wd=>{"use strict";var Fw=un(),Lw={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),Fw.stringifyString(e,t,i,n)}};wd.string=Lw});var Zr=R(bd=>{"use strict";var yd=Z(),Nd={identify:e=>e==null,createNode:()=>new yd.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new yd.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Nd.test.test(e)?e:t.options.nullStr};bd.nullTag=Nd});var os=R(kd=>{"use strict";var Mw=Z(),Sd={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Mw.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Sd.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};kd.boolTag=Sd});var Ei=R(Ed=>{"use strict";function Bw({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}Ed.stringifyNumber=Bw});var cs=R(ea=>{"use strict";var qw=Z(),ss=Ei(),Vw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ss.stringifyNumber},zw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ss.stringifyNumber(e)}},Ww={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 qw.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:ss.stringifyNumber};ea.float=Ww;ea.floatExp=zw;ea.floatNaN=Vw});var us=R(ia=>{"use strict";var Cd=Ei(),ta=e=>typeof e=="bigint"||Number.isInteger(e),ls=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function Rd(e,t,i){let{value:n}=e;return ta(n)&&n>=0?i+n.toString(t):Cd.stringifyNumber(e)}var Jw={identify:e=>ta(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>ls(e,2,8,i),stringify:e=>Rd(e,8,"0o")},Uw={identify:ta,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>ls(e,0,10,i),stringify:Cd.stringifyNumber},Gw={identify:e=>ta(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>ls(e,2,16,i),stringify:e=>Rd(e,16,"0x")};ia.int=Uw;ia.intHex=Gw;ia.intOct=Jw});var Ad=R(Pd=>{"use strict";var Kw=Si(),Yw=Zr(),Xw=ki(),Qw=pn(),Zw=os(),ds=cs(),fs=us(),ey=[Kw.map,Xw.seq,Qw.string,Yw.nullTag,Zw.boolTag,fs.intOct,fs.int,fs.intHex,ds.floatNaN,ds.floatExp,ds.float];Pd.schema=ey});var Id=R(Td=>{"use strict";var ty=Z(),iy=Si(),ny=ki();function xd(e){return typeof e=="bigint"||Number.isInteger(e)}var na=({value:e})=>JSON.stringify(e),ry=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:na},{identify:e=>e==null,createNode:()=>new ty.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:na},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:na},{identify:xd,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})=>xd(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:na}],ay={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},oy=[iy.map,ny.seq].concat(ry,ay);Td.schema=oy});var ps=R(_d=>{"use strict";var mn=Rr("buffer"),hs=Z(),sy=un(),cy={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof mn.Buffer=="function")return mn.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 mn.Buffer=="function")s=o instanceof mn.Buffer?o.toString("base64"):mn.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=hs.Scalar.BLOCK_LITERAL),t!==hs.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===hs.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return sy.stringifyString({comment:e,type:t,value:s},n,r,a)}};_d.binary=cy});var oa=R(aa=>{"use strict";var ra=M(),ms=Et(),ly=Z(),uy=Pt();function jd(e,t){if(ra.isSeq(e))for(let i=0;i<e.items.length;++i){let n=e.items[i];if(!ra.isPair(n)){if(ra.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new ms.Pair(new ly.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
54
+ ${r}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function ia({indent:e,options:{commentString:t}},i,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){let a=ta.indentComment(t(n),e);i.push(a.trimStart())}}bd.stringifyCollection=$w});var Pt=R(gs=>{"use strict";var Dw=ms(),Lw=hs(),Mw=qr(),Rt=M(),na=Ct(),Bw=te();function gn(e,t){let i=Rt.isScalar(t)?t.value:t;for(let n of e)if(Rt.isPair(n)&&(n.key===t||n.key===i||Rt.isScalar(n.key)&&n.key.value===i))return n}var vs=class extends Mw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Rt.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(na.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;Rt.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new na.Pair(t,t?.value):n=new na.Pair(t.key,t.value);let r=gn(this.items,n.key),a=this.schema?.sortMapEntries;if(r){if(!i)throw new Error(`Key ${n.key} already set`);Rt.isScalar(r.value)&&Bw.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=gn(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let r=gn(this.items,t)?.value;return(!i&&Rt.isScalar(r)?r.value:r)??void 0}has(t){return!!gn(this.items,t)}set(t,i){this.add(new na.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)Lw.addPairToJSMap(i,r,a);return r}toString(t,i,n){if(!t)return JSON.stringify(this);for(let r of this.items)if(!Rt.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})),Dw.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:i})}};gs.YAMLMap=vs;gs.findPair=gn});var Ci=R(Sd=>{"use strict";var qw=M(),kd=Pt(),Vw={collection:"map",default:!0,nodeClass:kd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return qw.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>kd.YAMLMap.from(e,t,i)};Sd.map=Vw});var At=R(Ed=>{"use strict";var Ww=un(),zw=ms(),Jw=qr(),aa=M(),Gw=te(),Uw=bt(),ws=class extends Jw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(aa.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=ra(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let n=ra(t);if(typeof n!="number")return;let r=this.items[n];return!i&&aa.isScalar(r)?r.value:r}has(t){let i=ra(t);return typeof i=="number"&&i<this.items.length}set(t,i){let n=ra(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[n];aa.isScalar(r)&&Gw.isScalarValue(i)?r.value=i:this.items[n]=i}toJSON(t,i){let n=[];i?.onCreate&&i.onCreate(n);let r=0;for(let a of this.items)n.push(Uw.toJS(a,String(r++),i));return n}toString(t,i,n){return t?zw.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(Ww.createNode(s,void 0,n))}}return a}};function ra(e){let t=aa.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Ed.YAMLSeq=ws});var Ri=R(Rd=>{"use strict";var Kw=M(),Cd=At(),Yw={collection:"seq",default:!0,nodeClass:Cd.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Kw.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Cd.YAMLSeq.from(e,t,i)};Rd.seq=Yw});var wn=R(Pd=>{"use strict";var Xw=pn(),Qw={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),Xw.stringifyString(e,t,i,n)}};Pd.string=Qw});var oa=R(Td=>{"use strict";var Ad=te(),xd={identify:e=>e==null,createNode:()=>new Ad.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ad.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&xd.test.test(e)?e:t.options.nullStr};Td.nullTag=xd});var ys=R(_d=>{"use strict";var Zw=te(),Id={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Zw.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Id.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?i.options.trueStr:i.options.falseStr}};_d.boolTag=Id});var Pi=R(jd=>{"use strict";function ey({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}jd.stringifyNumber=ey});var bs=R(sa=>{"use strict";var ty=te(),Ns=Pi(),iy={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:Ns.stringifyNumber},ny={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():Ns.stringifyNumber(e)}},ry={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 ty.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Ns.stringifyNumber};sa.float=ry;sa.floatExp=ny;sa.floatNaN=iy});var Ss=R(la=>{"use strict";var Od=Pi(),ca=e=>typeof e=="bigint"||Number.isInteger(e),ks=(e,t,i,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),i);function $d(e,t,i){let{value:n}=e;return ca(n)&&n>=0?i+n.toString(t):Od.stringifyNumber(e)}var ay={identify:e=>ca(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>ks(e,2,8,i),stringify:e=>$d(e,8,"0o")},oy={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>ks(e,0,10,i),stringify:Od.stringifyNumber},sy={identify:e=>ca(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>ks(e,2,16,i),stringify:e=>$d(e,16,"0x")};la.int=oy;la.intHex=sy;la.intOct=ay});var Fd=R(Hd=>{"use strict";var cy=Ci(),ly=oa(),uy=Ri(),dy=wn(),fy=ys(),Es=bs(),Cs=Ss(),hy=[cy.map,uy.seq,dy.string,ly.nullTag,fy.boolTag,Cs.intOct,Cs.int,Cs.intHex,Es.floatNaN,Es.floatExp,Es.float];Hd.schema=hy});var Md=R(Ld=>{"use strict";var py=te(),my=Ci(),vy=Ri();function Dd(e){return typeof e=="bigint"||Number.isInteger(e)}var ua=({value:e})=>JSON.stringify(e),gy=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ua},{identify:e=>e==null,createNode:()=>new py.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ua},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ua},{identify:Dd,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})=>Dd(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:ua}],wy={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},yy=[my.map,vy.seq].concat(gy,wy);Ld.schema=yy});var Ps=R(Bd=>{"use strict";var yn=jr("buffer"),Rs=te(),Ny=pn(),by={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof yn.Buffer=="function")return yn.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 yn.Buffer=="function")s=o instanceof yn.Buffer?o.toString("base64"):yn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Rs.Scalar.BLOCK_LITERAL),t!==Rs.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Rs.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return Ny.stringifyString({comment:e,type:t,value:s},n,r,a)}};Bd.binary=by});var ha=R(fa=>{"use strict";var da=M(),As=Ct(),ky=te(),Sy=At();function qd(e,t){if(da.isSeq(e))for(let i=0;i<e.items.length;++i){let n=e.items[i];if(!da.isPair(n)){if(da.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let r=n.items[0]||new As.Pair(new ky.Scalar(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
56
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]=ra.isPair(n)?n:new ms.Pair(n)}}else t("Expected a sequence for this tag");return e}function Od(e,t,i){let{replacer:n}=i,r=new uy.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(ms.createPair(s,c,i))}return r}var dy={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:jd,createNode:Od};aa.createPairs=Od;aa.pairs=dy;aa.resolvePairs=jd});var ws=R(gs=>{"use strict";var $d=M(),vs=Nt(),vn=Rt(),fy=Pt(),Hd=oa(),Gt=class e extends fy.YAMLSeq{constructor(){super(),this.add=vn.YAMLMap.prototype.add.bind(this),this.delete=vn.YAMLMap.prototype.delete.bind(this),this.get=vn.YAMLMap.prototype.get.bind(this),this.has=vn.YAMLMap.prototype.has.bind(this),this.set=vn.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($d.isPair(r)?(a=vs.toJS(r.key,"",i),o=vs.toJS(r.value,a,i)):a=vs.toJS(r,"",i),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,i,n){let r=Hd.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Gt.tag="tag:yaml.org,2002:omap";var hy={collection:"seq",identify:e=>e instanceof Map,nodeClass:Gt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Hd.resolvePairs(e,t),n=[];for(let{key:r}of i.items)$d.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Gt,i)},createNode:(e,t,i)=>Gt.from(e,t,i)};gs.YAMLOMap=Gt;gs.omap=hy});var Bd=R(ys=>{"use strict";var Dd=Z();function Fd({value:e,source:t},i){return t&&(e?Ld:Md).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Ld={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 Dd.Scalar(!0),stringify:Fd},Md={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 Dd.Scalar(!1),stringify:Fd};ys.falseTag=Md;ys.trueTag=Ld});var qd=R(sa=>{"use strict";var py=Z(),Ns=Ei(),my={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:Ns.stringifyNumber},vy={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():Ns.stringifyNumber(e)}},gy={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 py.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:Ns.stringifyNumber};sa.float=gy;sa.floatExp=vy;sa.floatNaN=my});var zd=R(wn=>{"use strict";var Vd=Ei(),gn=e=>typeof e=="bigint"||Number.isInteger(e);function ca(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 bs(e,t,i){let{value:n}=e;if(gn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return Vd.stringifyNumber(e)}var wy={identify:gn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>ca(e,2,2,i),stringify:e=>bs(e,2,"0b")},yy={identify:gn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>ca(e,1,8,i),stringify:e=>bs(e,8,"0")},Ny={identify:gn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>ca(e,0,10,i),stringify:Vd.stringifyNumber},by={identify:gn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>ca(e,2,16,i),stringify:e=>bs(e,16,"0x")};wn.int=Ny;wn.intBin=wy;wn.intHex=by;wn.intOct=yy});var ks=R(Ss=>{"use strict";var da=M(),la=Et(),ua=Rt(),Kt=class e extends ua.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;da.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new la.Pair(t.key,null):i=new la.Pair(t,null),ua.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=ua.findPair(this.items,t);return!i&&da.isPair(n)?da.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=ua.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new la.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(la.createPair(o,null,n));return a}};Kt.tag="tag:yaml.org,2002:set";var Sy={collection:"map",identify:e=>e instanceof Set,nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Kt.from(e,t,i),resolve(e,t){if(da.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Kt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ss.YAMLSet=Kt;Ss.set=Sy});var Cs=R(fa=>{"use strict";var ky=Ei();function Es(e,t){let i=e[0],n=i==="-"||i==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*r(60)+r(s),r(0));return i==="-"?r(-1)*a:a}function Wd(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ky.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 Ey={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})=>Es(e,i),stringify:Wd},Cy={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=>Es(e,!1),stringify:Wd},Jd={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(Jd.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=Es(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$/,"")??""};fa.floatTime=Cy;fa.intTime=Ey;fa.timestamp=Jd});var Kd=R(Gd=>{"use strict";var Ry=Si(),Py=Zr(),Ay=ki(),xy=pn(),Ty=ps(),Ud=Bd(),Rs=qd(),ha=zd(),Iy=Wr(),_y=ws(),jy=oa(),Oy=ks(),Ps=Cs(),$y=[Ry.map,Ay.seq,xy.string,Py.nullTag,Ud.trueTag,Ud.falseTag,ha.intBin,ha.intOct,ha.int,ha.intHex,Rs.floatNaN,Rs.floatExp,Rs.float,Ty.binary,Iy.merge,_y.omap,jy.pairs,Oy.set,Ps.intTime,Ps.floatTime,Ps.timestamp];Gd.schema=$y});var of=R(Ts=>{"use strict";var Zd=Si(),Hy=Zr(),ef=ki(),Dy=pn(),Fy=os(),As=cs(),xs=us(),Ly=Ad(),My=Id(),tf=ps(),yn=Wr(),nf=ws(),rf=oa(),Yd=Kd(),af=ks(),pa=Cs(),Xd=new Map([["core",Ly.schema],["failsafe",[Zd.map,ef.seq,Dy.string]],["json",My.schema],["yaml11",Yd.schema],["yaml-1.1",Yd.schema]]),Qd={binary:tf.binary,bool:Fy.boolTag,float:As.float,floatExp:As.floatExp,floatNaN:As.floatNaN,floatTime:pa.floatTime,int:xs.int,intHex:xs.intHex,intOct:xs.intOct,intTime:pa.intTime,map:Zd.map,merge:yn.merge,null:Hy.nullTag,omap:nf.omap,pairs:rf.pairs,seq:ef.seq,set:af.set,timestamp:pa.timestamp},By={"tag:yaml.org,2002:binary":tf.binary,"tag:yaml.org,2002:merge":yn.merge,"tag:yaml.org,2002:omap":nf.omap,"tag:yaml.org,2002:pairs":rf.pairs,"tag:yaml.org,2002:set":af.set,"tag:yaml.org,2002:timestamp":pa.timestamp};function qy(e,t,i){let n=Xd.get(t);if(n&&!e)return i&&!n.includes(yn.merge)?n.concat(yn.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(Xd.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(yn.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?Qd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Qd).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},[])}Ts.coreKnownTags=By;Ts.getTags=qy});var js=R(sf=>{"use strict";var Is=M(),Vy=Si(),zy=ki(),Wy=pn(),ma=of(),Jy=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_s=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ma.getTags(t,"compat"):t?ma.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?ma.coreKnownTags:{},this.tags=ma.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Is.MAP,{value:Vy.map}),Object.defineProperty(this,Is.SCALAR,{value:Wy.string}),Object.defineProperty(this,Is.SEQ,{value:zy.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Jy:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};sf.Schema=_s});var lf=R(cf=>{"use strict";var Uy=M(),Os=dn(),Nn=sn();function Gy(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=Os.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Nn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(Uy.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Nn.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Os.stringify(e.contents,r,()=>s=null,c);s&&(l+=Nn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Os.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(Nn.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(Nn.indentComment(a(c),"")))}return i.join(`
57
+ ${a.comment}`:n.comment}n=r}e.items[i]=da.isPair(n)?n:new As.Pair(n)}}else t("Expected a sequence for this tag");return e}function Vd(e,t,i){let{replacer:n}=i,r=new Sy.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(As.createPair(s,c,i))}return r}var Ey={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qd,createNode:Vd};fa.createPairs=Vd;fa.pairs=Ey;fa.resolvePairs=qd});var Is=R(Ts=>{"use strict";var Wd=M(),xs=bt(),Nn=Pt(),Cy=At(),zd=ha(),Yt=class e extends Cy.YAMLSeq{constructor(){super(),this.add=Nn.YAMLMap.prototype.add.bind(this),this.delete=Nn.YAMLMap.prototype.delete.bind(this),this.get=Nn.YAMLMap.prototype.get.bind(this),this.has=Nn.YAMLMap.prototype.has.bind(this),this.set=Nn.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let n=new Map;i?.onCreate&&i.onCreate(n);for(let r of this.items){let a,o;if(Wd.isPair(r)?(a=xs.toJS(r.key,"",i),o=xs.toJS(r.value,a,i)):a=xs.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=zd.createPairs(t,i,n),a=new this;return a.items=r.items,a}};Yt.tag="tag:yaml.org,2002:omap";var Ry={collection:"seq",identify:e=>e instanceof Map,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=zd.resolvePairs(e,t),n=[];for(let{key:r}of i.items)Wd.isScalar(r)&&(n.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Yt,i)},createNode:(e,t,i)=>Yt.from(e,t,i)};Ts.YAMLOMap=Yt;Ts.omap=Ry});var Yd=R(_s=>{"use strict";var Jd=te();function Gd({value:e,source:t},i){return t&&(e?Ud:Kd).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Ud={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 Jd.Scalar(!0),stringify:Gd},Kd={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 Jd.Scalar(!1),stringify:Gd};_s.falseTag=Kd;_s.trueTag=Ud});var Xd=R(pa=>{"use strict";var Py=te(),js=Pi(),Ay={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:js.stringifyNumber},xy={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():js.stringifyNumber(e)}},Ty={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 Py.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:js.stringifyNumber};pa.float=Ty;pa.floatExp=xy;pa.floatNaN=Ay});var Zd=R(kn=>{"use strict";var Qd=Pi(),bn=e=>typeof e=="bigint"||Number.isInteger(e);function ma(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 Os(e,t,i){let{value:n}=e;if(bn(n)){let r=n.toString(t);return n<0?"-"+i+r.substr(1):i+r}return Qd.stringifyNumber(e)}var Iy={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>ma(e,2,2,i),stringify:e=>Os(e,2,"0b")},_y={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>ma(e,1,8,i),stringify:e=>Os(e,8,"0")},jy={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>ma(e,0,10,i),stringify:Qd.stringifyNumber},Oy={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>ma(e,2,16,i),stringify:e=>Os(e,16,"0x")};kn.int=jy;kn.intBin=Iy;kn.intHex=Oy;kn.intOct=_y});var Hs=R($s=>{"use strict";var wa=M(),va=Ct(),ga=Pt(),Xt=class e extends ga.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;wa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new va.Pair(t.key,null):i=new va.Pair(t,null),ga.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let n=ga.findPair(this.items,t);return!i&&wa.isPair(n)?wa.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=ga.findPair(this.items,t);n&&!i?this.items.splice(this.items.indexOf(n),1):!n&&i&&this.items.push(new va.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(va.createPair(o,null,n));return a}};Xt.tag="tag:yaml.org,2002:set";var $y={collection:"map",identify:e=>e instanceof Set,nodeClass:Xt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Xt.from(e,t,i),resolve(e,t){if(wa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Xt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};$s.YAMLSet=Xt;$s.set=$y});var Ds=R(ya=>{"use strict";var Hy=Pi();function Fs(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 ef(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Hy.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 Fy={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})=>Fs(e,i),stringify:ef},Dy={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=>Fs(e,!1),stringify:ef},tf={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(tf.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=Fs(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$/,"")??""};ya.floatTime=Dy;ya.intTime=Fy;ya.timestamp=tf});var af=R(rf=>{"use strict";var Ly=Ci(),My=oa(),By=Ri(),qy=wn(),Vy=Ps(),nf=Yd(),Ls=Xd(),Na=Zd(),Wy=Qr(),zy=Is(),Jy=ha(),Gy=Hs(),Ms=Ds(),Uy=[Ly.map,By.seq,qy.string,My.nullTag,nf.trueTag,nf.falseTag,Na.intBin,Na.intOct,Na.int,Na.intHex,Ls.floatNaN,Ls.floatExp,Ls.float,Vy.binary,Wy.merge,zy.omap,Jy.pairs,Gy.set,Ms.intTime,Ms.floatTime,Ms.timestamp];rf.schema=Uy});var mf=R(Vs=>{"use strict";var lf=Ci(),Ky=oa(),uf=Ri(),Yy=wn(),Xy=ys(),Bs=bs(),qs=Ss(),Qy=Fd(),Zy=Md(),df=Ps(),Sn=Qr(),ff=Is(),hf=ha(),of=af(),pf=Hs(),ba=Ds(),sf=new Map([["core",Qy.schema],["failsafe",[lf.map,uf.seq,Yy.string]],["json",Zy.schema],["yaml11",of.schema],["yaml-1.1",of.schema]]),cf={binary:df.binary,bool:Xy.boolTag,float:Bs.float,floatExp:Bs.floatExp,floatNaN:Bs.floatNaN,floatTime:ba.floatTime,int:qs.int,intHex:qs.intHex,intOct:qs.intOct,intTime:ba.intTime,map:lf.map,merge:Sn.merge,null:Ky.nullTag,omap:ff.omap,pairs:hf.pairs,seq:uf.seq,set:pf.set,timestamp:ba.timestamp},eN={"tag:yaml.org,2002:binary":df.binary,"tag:yaml.org,2002:merge":Sn.merge,"tag:yaml.org,2002:omap":ff.omap,"tag:yaml.org,2002:pairs":hf.pairs,"tag:yaml.org,2002:set":pf.set,"tag:yaml.org,2002:timestamp":ba.timestamp};function tN(e,t,i){let n=sf.get(t);if(n&&!e)return i&&!n.includes(Sn.merge)?n.concat(Sn.merge):n.slice();let r=n;if(!r)if(Array.isArray(e))r=[];else{let a=Array.from(sf.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(Sn.merge)),r.reduce((a,o)=>{let s=typeof o=="string"?cf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(cf).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},[])}Vs.coreKnownTags=eN;Vs.getTags=tN});var Js=R(vf=>{"use strict";var Ws=M(),iN=Ci(),nN=Ri(),rN=wn(),ka=mf(),aN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,zs=class e{constructor({compat:t,customTags:i,merge:n,resolveKnownTags:r,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ka.getTags(t,"compat"):t?ka.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=r?ka.coreKnownTags:{},this.tags=ka.getTags(i,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,Ws.MAP,{value:iN.map}),Object.defineProperty(this,Ws.SCALAR,{value:rN.string}),Object.defineProperty(this,Ws.SEQ,{value:nN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?aN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};vf.Schema=zs});var wf=R(gf=>{"use strict";var oN=M(),Gs=mn(),En=dn();function sN(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=Gs.createStringifyContext(e,t),{commentString:a}=r.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(En.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(oN.isNode(e.contents)){if(e.contents.spaceBefore&&n&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(En.indentComment(u,""))}r.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Gs.stringify(e.contents,r,()=>s=null,c);s&&(l+=En.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Gs.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(En.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(En.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}cf.stringifyDocument=Gy});var bn=R(uf=>{"use strict";var Ky=an(),Ci=$r(),Ce=M(),Yy=Et(),Xy=Nt(),Qy=js(),Zy=lf(),$s=Ir(),eN=Lo(),tN=on(),Hs=Fo(),Ds=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ce.NODE_TYPE,{value:Ce.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 Hs.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,{[Ce.NODE_TYPE]:{value:Ce.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=Ce.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ri(this.contents)&&this.contents.add(t)}addIn(t,i){Ri(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=$s.anchorNames(this);t.anchor=!i||n.has(i)?$s.findNewAnchor(i||"a",n):i}return new Ky.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=k=>typeof k=="number"||k instanceof String||k instanceof Number,N=i.filter(v).map(String);N.length>0&&(i=i.concat(N)),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}=$s.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=tN.createNode(t,u,m);return s&&Ce.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 Yy.Pair(r,a)}delete(t){return Ri(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Ci.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ri(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Ce.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Ci.isEmptyPath(t)?!i&&Ce.isScalar(this.contents)?this.contents.value:this.contents:Ce.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Ce.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Ci.isEmptyPath(t)?this.contents!==void 0:Ce.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Ci.collectionFromPath(this.schema,[t],i):Ri(this.contents)&&this.contents.set(t,i)}setIn(t,i){Ci.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Ci.collectionFromPath(this.schema,Array.from(t),i):Ri(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 Hs.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 Hs.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 Qy.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=Xy.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"?eN.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 Zy.stringifyDocument(this,t)}};function Ri(e){if(Ce.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}uf.Document=Ds});var En=R(kn=>{"use strict";var Sn=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},Fs=class extends Sn{constructor(t,i,n){super("YAMLParseError",t,i,n)}},Ls=class extends Sn{constructor(t,i,n){super("YAMLWarning",t,i,n)}},iN=(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)+`…
60
+ `}gf.stringifyDocument=sN});var Cn=R(yf=>{"use strict";var cN=ln(),Ai=qr(),Pe=M(),lN=Ct(),uN=bt(),dN=Js(),fN=wf(),Us=Dr(),hN=Qo(),pN=un(),Ks=Xo(),Ys=class e{constructor(t,i,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Pe.NODE_TYPE,{value:Pe.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 Ks.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,{[Pe.NODE_TYPE]:{value:Pe.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=Pe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){xi(this.contents)&&this.contents.add(t)}addIn(t,i){xi(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let n=Us.anchorNames(this);t.anchor=!i||n.has(i)?Us.findNewAnchor(i||"a",n):i}return new cN.Alias(t.anchor)}createNode(t,i,n){let r;if(typeof i=="function")t=i.call({"":t},"",t),r=i;else if(Array.isArray(i)){let g=N=>typeof N=="number"||N instanceof String||N instanceof Number,S=i.filter(g).map(String);S.length>0&&(i=i.concat(S)),r=i}else n===void 0&&i&&(n=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Us.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:p},h=pN.createNode(t,u,m);return s&&Pe.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 lN.Pair(r,a)}delete(t){return xi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Ai.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):xi(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Pe.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Ai.isEmptyPath(t)?!i&&Pe.isScalar(this.contents)?this.contents.value:this.contents:Pe.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Pe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Ai.isEmptyPath(t)?this.contents!==void 0:Pe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Ai.collectionFromPath(this.schema,[t],i):xi(this.contents)&&this.contents.set(t,i)}setIn(t,i){Ai.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Ai.collectionFromPath(this.schema,Array.from(t),i):xi(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 Ks.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 Ks.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 dN.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=uN.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"?hN.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 fN.stringifyDocument(this,t)}};function xi(e){if(Pe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}yf.Document=Ys});var An=R(Pn=>{"use strict";var Rn=class extends Error{constructor(t,i,n,r){super(),this.name=t,this.code=n,this.message=r,this.pos=i}},Xs=class extends Rn{constructor(t,i,n){super("YAMLParseError",t,i,n)}},Qs=class extends Rn{constructor(t,i,n){super("YAMLWarning",t,i,n)}},mN=(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
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+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};kn.YAMLError=Sn;kn.YAMLParseError=Fs;kn.YAMLWarning=Ls;kn.prettifyError=iN});var Cn=R(df=>{"use strict";function nN(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,N=null,k=null,S=null,b=null,C=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:(!b||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(v||N)&&(k=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,C??(C=g.offset),l=!1,u=!1,m=!0;break;case"tag":{N&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),N=g,C??(C=g.offset),l=!1,u=!1,m=!0;break}case i:(v||N)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),b&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),b=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){S&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),S=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:S,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:N,newlineAfterProp:k,end:w,start:C??w}}df.resolveProps=nN});var va=R(ff=>{"use strict";function Ms(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(Ms(t.key)||Ms(t.value))return!0}return!1;default:return!0}}ff.containsNewline=Ms});var Bs=R(hf=>{"use strict";var rN=va();function aN(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&rN.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}hf.flowIndentCheck=aN});var qs=R(mf=>{"use strict";var pf=M();function oN(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||pf.isScalar(a)&&pf.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}mf.mapIncludes=oN});var bf=R(Nf=>{"use strict";var vf=Et(),sN=Rt(),gf=Cn(),cN=va(),wf=Bs(),lN=qs(),yf="All mapping items must start at the same column";function uN({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??sN.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=gf.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",yf)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||cN.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",yf);i.atKey=!0;let N=h.end,k=f?e(i,f,h,r):t(i,N,d,null,h,r);i.schema.compat&&wf.flowIndentCheck(n.indent,f,r),i.atKey=!1,lN.mapIncludes(i,s.items,k)&&r(N,"DUPLICATE_KEY","Map keys must be unique");let S=gf.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:r,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){v&&(m?.type==="block-map"&&!S.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<S.found.offset-1024&&r(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=m?e(i,m,S,r):t(i,c,p,null,S,r);i.schema.compat&&wf.flowIndentCheck(n.indent,m,r),c=b.range[2];let C=new vf.Pair(k,b);i.options.keepSourceTokens&&(C.srcToken=u),s.items.push(C)}else{v&&r(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(k.comment?k.comment+=`
68
- `+S.comment:k.comment=S.comment);let b=new vf.Pair(k);i.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}Nf.resolveBlockMap=uN});var kf=R(Sf=>{"use strict";var dN=Pt(),fN=Cn(),hN=Bs();function pN({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??dN.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=fN.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&&hN.flowIndentCheck(n.indent,d,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}Sf.resolveBlockSeq=pN});var Pi=R(Ef=>{"use strict";function mN(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}}Ef.resolveEnd=mN});var Af=R(Pf=>{"use strict";var vN=M(),gN=Et(),Cf=Rt(),wN=Pt(),yN=Pi(),Rf=Cn(),NN=va(),bN=qs(),Vs="Block collections are not allowed within flow collections",zs=e=>e&&(e.type==="block-map"||e.type==="block-seq");function SN({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Cf.YAMLMap:wN.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 N=n.items[v],{start:k,key:S,sep:b,value:C}=N,y=Rf.resolveProps(k,{flow:s,indicator:"explicit-key-ind",next:S??b?.[0],offset:d,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!y.found){if(!y.anchor&&!y.tag&&!b&&!C){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&&NN.containsNewline(S)&&r(S,"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 k)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];vN.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&&!b&&!y.found){let w=C?e(i,C,y,r):t(i,y.end,b,null,y,r);l.items.push(w),d=w.range[2],zs(C)&&r(w.range,"BLOCK_IN_FLOW",Vs)}else{i.atKey=!0;let w=y.end,g=S?e(i,S,y,r):t(i,w,k,null,y,r);zs(S)&&r(g.range,"BLOCK_IN_FLOW",Vs),i.atKey=!1;let E=Rf.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:C,offset:g.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(E.found){if(!o&&!y.found&&i.options.strict){if(b)for(let q of b){if(q===E.found)break;if(q.type==="newline"){r(q,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}y.start<E.found.offset-1024&&r(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?r(C,"MISSING_CHAR",`Missing space after : in ${s}`):r(E.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let _=C?e(i,C,E,r):E.found?t(i,E.end,b,null,E,r):null;_?zs(C)&&r(_.range,"BLOCK_IN_FLOW",Vs):E.comment&&(g.comment?g.comment+=`
71
- `+E.comment:g.comment=E.comment);let K=new gN.Pair(g,_);if(i.options.keepSourceTokens&&(K.srcToken=N),o){let q=l;bN.mapIncludes(i,q.items,g)&&r(w,"DUPLICATE_KEY","Map keys must be unique"),q.items.push(K)}else{let q=new Cf.YAMLMap(i.schema);q.flow=!0,q.items.push(K);let U=(_??g).range;q.range=[g.range[0],U[1],U[2]],l.items.push(q)}d=_?_.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),N=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",N),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=yN.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}Pf.resolveFlowCollection=SN});var Tf=R(xf=>{"use strict";var kN=M(),EN=Z(),CN=Rt(),RN=Pt(),PN=bf(),AN=kf(),xN=Af();function Ws(e,t,i,n,r,a){let o=i.type==="block-map"?PN.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?AN.resolveBlockSeq(e,t,i,n,a):xN.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 TN(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===CN.YAMLMap.tagName&&s==="map"||o===RN.YAMLSeq.tagName&&s==="seq")return Ws(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),Ws(e,t,i,r,o)}let l=Ws(e,t,i,r,o,c),u=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=kN.isNode(u)?u:new EN.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}xf.composeCollection=TN});var Us=R(If=>{"use strict";var Js=Z();function IN(e,t,i){let n=t.offset,r=_N(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?Js.Scalar.BLOCK_FOLDED:Js.Scalar.BLOCK_LITERAL,o=t.source?jN(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,N]=o[h];if(N===""||N==="\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+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[v,N]=o[h];l+=v.length+N.length+1;let k=N[N.length-1]==="\r";if(k&&(N=N.slice(0,-1)),N&&v.length<c){let b=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-N.length-(k?2:1),"BAD_INDENT",b),v=""}a===Js.Scalar.BLOCK_LITERAL?(d+=f+v.slice(c)+N,f=`
75
- `):v.length>c||N[0]===" "?(f===" "?f=`
65
+ `}};Pn.YAMLError=Rn;Pn.YAMLParseError=Xs;Pn.YAMLWarning=Qs;Pn.prettifyError=mN});var xn=R(Nf=>{"use strict";function vN(e,{flow:t,indicator:i,next:n,offset:r,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,m=!1,h=null,g=null,S=null,N=null,k=null,b=null,C=null;for(let v of e)switch(m&&(v.type!=="space"&&v.type!=="newline"&&v.type!=="comma"&&a(v.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&v.type!=="comment"&&v.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),v.type){case"space":!t&&(i!=="doc-start"||n?.type!=="flow-collection")&&v.source.includes(" ")&&(h=v),u=!0;break;case"comment":{u||a(v,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=v.source.substring(1)||" ";d?d+=f+E:d=E,f="",l=!1;break}case"newline":l?d?d+=v.source:(!b||i!=="seq-item-ind")&&(c=!0):f+=v.source,l=!0,p=!0,(g||S)&&(N=v),u=!0;break;case"anchor":g&&a(v,"MULTIPLE_ANCHORS","A node can have at most one anchor"),v.source.endsWith(":")&&a(v.offset+v.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=v,C??(C=v.offset),l=!1,u=!1,m=!0;break;case"tag":{S&&a(v,"MULTIPLE_TAGS","A node can have at most one tag"),S=v,C??(C=v.offset),l=!1,u=!1,m=!0;break}case i:(g||S)&&a(v,"BAD_PROP_ORDER",`Anchors and tags must be after the ${v.source} indicator`),b&&a(v,"UNEXPECTED_TOKEN",`Unexpected ${v.source} in ${t??"collection"}`),b=v,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(v,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=v,l=!1,u=!1;break}default:a(v,"UNEXPECTED_TOKEN",`Unexpected ${v.type} token`),l=!1,u=!1}let y=e[e.length-1],w=y?y.offset+y.source.length:r;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:S,newlineAfterProp:N,end:w,start:C??w}}Nf.resolveProps=vN});var Sa=R(bf=>{"use strict";function Zs(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(Zs(t.key)||Zs(t.value))return!0}return!1;default:return!0}}bf.containsNewline=Zs});var ec=R(kf=>{"use strict";var gN=Sa();function wN(e,t,i){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&gN.containsNewline(t)&&i(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}kf.flowIndentCheck=wN});var tc=R(Ef=>{"use strict";var Sf=M();function yN(e,t,i){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let r=typeof n=="function"?n:(a,o)=>a===o||Sf.isScalar(a)&&Sf.isScalar(o)&&a.value===o.value;return t.some(a=>r(a.key,i))}Ef.mapIncludes=yN});var Tf=R(xf=>{"use strict";var Cf=Ct(),NN=Pt(),Rf=xn(),bN=Sa(),Pf=ec(),kN=tc(),Af="All mapping items must start at the same column";function SN({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??NN.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=Rf.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),g=!h.found;if(g){if(f&&(f.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&r(c,"BAD_INDENT",Af)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||bN.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",Af);i.atKey=!0;let S=h.end,N=f?e(i,f,h,r):t(i,S,d,null,h,r);i.schema.compat&&Pf.flowIndentCheck(n.indent,f,r),i.atKey=!1,kN.mapIncludes(i,s.items,N)&&r(S,"DUPLICATE_KEY","Map keys must be unique");let k=Rf.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:N.range[2],onError:r,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){g&&(m?.type==="block-map"&&!k.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<k.found.offset-1024&&r(N.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=m?e(i,m,k,r):t(i,c,p,null,k,r);i.schema.compat&&Pf.flowIndentCheck(n.indent,m,r),c=b.range[2];let C=new Cf.Pair(N,b);i.options.keepSourceTokens&&(C.srcToken=u),s.items.push(C)}else{g&&r(N.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(N.comment?N.comment+=`
68
+ `+k.comment:N.comment=k.comment);let b=new Cf.Pair(N);i.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}xf.resolveBlockMap=SN});var _f=R(If=>{"use strict";var EN=At(),CN=xn(),RN=ec();function PN({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=a?.nodeClass??EN.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=CN.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&&RN.flowIndentCheck(n.indent,d,r),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}If.resolveBlockSeq=PN});var Ti=R(jf=>{"use strict";function AN(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}}jf.resolveEnd=AN});var Ff=R(Hf=>{"use strict";var xN=M(),TN=Ct(),Of=Pt(),IN=At(),_N=Ti(),$f=xn(),jN=Sa(),ON=tc(),ic="Block collections are not allowed within flow collections",nc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function $N({composeNode:e,composeEmptyNode:t},i,n,r,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Of.YAMLMap:IN.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=n.offset+n.start.source.length;for(let g=0;g<n.items.length;++g){let S=n.items[g],{start:N,key:k,sep:b,value:C}=S,y=$f.resolveProps(N,{flow:s,indicator:"explicit-key-ind",next:k??b?.[0],offset:d,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!y.found){if(!y.anchor&&!y.tag&&!b&&!C){g===0&&y.comma?r(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<n.items.length-1&&r(y.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),y.comment&&(l.comment?l.comment+=`
69
+ `+y.comment:l.comment=y.comment),d=y.end;continue}!o&&i.options.strict&&jN.containsNewline(k)&&r(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)y.comma&&r(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(y.comma||r(y.start,"MISSING_CHAR",`Missing , between ${s} items`),y.comment){let w="";e:for(let v of N)switch(v.type){case"comma":case"space":break;case"comment":w=v.source.substring(1);break e;default:break e}if(w){let v=l.items[l.items.length-1];xN.isPair(v)&&(v=v.value??v.key),v.comment?v.comment+=`
70
+ `+w:v.comment=w,y.comment=y.comment.substring(w.length+1)}}if(!o&&!b&&!y.found){let w=C?e(i,C,y,r):t(i,y.end,b,null,y,r);l.items.push(w),d=w.range[2],nc(C)&&r(w.range,"BLOCK_IN_FLOW",ic)}else{i.atKey=!0;let w=y.end,v=k?e(i,k,y,r):t(i,w,N,null,y,r);nc(k)&&r(v.range,"BLOCK_IN_FLOW",ic),i.atKey=!1;let E=$f.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:C,offset:v.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(E.found){if(!o&&!y.found&&i.options.strict){if(b)for(let q of b){if(q===E.found)break;if(q.type==="newline"){r(q,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}y.start<E.found.offset-1024&&r(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?r(C,"MISSING_CHAR",`Missing space after : in ${s}`):r(E.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let I=C?e(i,C,E,r):E.found?t(i,E.end,b,null,E,r):null;I?nc(C)&&r(I.range,"BLOCK_IN_FLOW",ic):E.comment&&(v.comment?v.comment+=`
71
+ `+E.comment:v.comment=E.comment);let U=new TN.Pair(v,I);if(i.options.keepSourceTokens&&(U.srcToken=S),o){let q=l;ON.mapIncludes(i,q.items,v)&&r(w,"DUPLICATE_KEY","Map keys must be unique"),q.items.push(U)}else{let q=new Of.YAMLMap(i.schema);q.flow=!0,q.items.push(U);let J=(I??v).range;q.range=[v.range[0],J[1],J[2]],l.items.push(q)}d=I?I.range[2]:E.end}}let f=o?"}":"]",[p,...m]=n.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let g=s[0].toUpperCase()+s.substring(1),S=u?`${g} must end with a ${f}`:`${g} in block collection must be sufficiently indented and end with a ${f}`;r(d,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let g=_N.resolveEnd(m,h,i.options.strict,r);g.comment&&(l.comment?l.comment+=`
72
+ `+g.comment:l.comment=g.comment),l.range=[n.offset,h,g.offset]}else l.range=[n.offset,h,h];return l}Hf.resolveFlowCollection=$N});var Lf=R(Df=>{"use strict";var HN=M(),FN=te(),DN=Pt(),LN=At(),MN=Tf(),BN=_f(),qN=Ff();function rc(e,t,i,n,r,a){let o=i.type==="block-map"?MN.resolveBlockMap(e,t,i,n,a):i.type==="block-seq"?BN.resolveBlockSeq(e,t,i,n,a):qN.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 VN(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===DN.YAMLMap.tagName&&s==="map"||o===LN.YAMLSeq.tagName&&s==="seq")return rc(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),rc(e,t,i,r,o)}let l=rc(e,t,i,r,o,c),u=c.resolve?.(l,f=>r(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=HN.isNode(u)?u:new FN.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Df.composeCollection=VN});var oc=R(Mf=>{"use strict";var ac=te();function WN(e,t,i){let n=t.offset,r=zN(t,e.options.strict,i);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};let a=r.mode===">"?ac.Scalar.BLOCK_FOLDED:ac.Scalar.BLOCK_LITERAL,o=t.source?JN(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let g=o[h][1];if(g===""||g==="\r")s=h;else break}if(s===0){let h=r.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",g=n+r.length;return t.source&&(g+=t.source.length),{value:h,type:a,comment:r.comment,range:[n,g,g]}}let c=t.indent+r.indent,l=t.offset+r.length,u=0;for(let h=0;h<s;++h){let[g,S]=o[h];if(S===""||S==="\r")r.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&i(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=g.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+S.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
74
+ `;for(let h=u;h<s;++h){let[g,S]=o[h];l+=g.length+S.length+1;let N=S[S.length-1]==="\r";if(N&&(S=S.slice(0,-1)),S&&g.length<c){let b=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(N?2:1),"BAD_INDENT",b),g=""}a===ac.Scalar.BLOCK_LITERAL?(d+=f+g.slice(c)+S,f=`
75
+ `):g.length>c||S[0]===" "?(f===" "?f=`
76
76
  `:!p&&f===`
77
77
  `&&(f=`
78
78
 
79
- `),d+=f+v.slice(c)+N,f=`
80
- `,p=!0):N===""?f===`
79
+ `),d+=f+g.slice(c)+S,f=`
80
+ `,p=!0):S===""?f===`
81
81
  `?d+=`
82
82
  `:f=`
83
- `:(d+=f+N,f=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
83
+ `:(d+=f+S,f=" ",p=!1)}switch(r.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 _N({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 jN(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}If.resolveBlockScalar=IN});var Ks=R(jf=>{"use strict";var Gs=Z(),ON=Pi();function $N(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=Gs.Scalar.PLAIN,c=HN(a,l);break;case"single-quoted-scalar":s=Gs.Scalar.QUOTE_SINGLE,c=DN(a,l);break;case"double-quoted-scalar":s=Gs.Scalar.QUOTE_DOUBLE,c=FN(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=ON.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function HN(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}`),_f(e)}function DN(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),_f(e.slice(1,-1)).replace(/''/g,"'")}function _f(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let m=n+r.length+t.source.length;return{value:d,type:a,comment:r.comment,range:[n,m,m]}}function zN({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 JN(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}Mf.resolveBlockScalar=WN});var cc=R(qf=>{"use strict";var sc=te(),GN=Ti();function UN(e,t,i){let{offset:n,type:r,source:a,end:o}=e,s,c,l=(f,p,m)=>i(n+f,p,m);switch(r){case"scalar":s=sc.Scalar.PLAIN,c=KN(a,l);break;case"single-quoted-scalar":s=sc.Scalar.QUOTE_SINGLE,c=YN(a,l);break;case"double-quoted-scalar":s=sc.Scalar.QUOTE_DOUBLE,c=XN(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=GN.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function KN(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}`),Bf(e)}function YN(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Bf(e.slice(1,-1)).replace(/''/g,"'")}function Bf(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
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
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 FN(e,t){let i="";for(let n=1;n<e.length-1;++n){let r=e[n];if(!(r==="\r"&&e[n+1]===`
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 XN(e,t){let i="";for(let n=1;n<e.length-1;++n){let r=e[n];if(!(r==="\r"&&e[n+1]===`
92
92
  `))if(r===`
93
- `){let{fold:a,offset:o}=LN(e,n);i+=a,n=o}else if(r==="\\"){let a=e[++n],o=MN[a];if(o)i+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=QN(e,n);i+=a,n=o}else if(r==="\\"){let a=e[++n],o=ZN[a];if(o)i+=o;else if(a===`
94
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+=BN(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!==`
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+=eb(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
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 LN(e,t){let i="",n=e[t+1];for(;(n===" "||n===" "||n===`
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 QN(e,t){let i="",n=e[t+1];for(;(n===" "||n===" "||n===`
98
98
  `||n==="\r")&&!(n==="\r"&&e[t+2]!==`
99
99
  `);)n===`
100
100
  `&&(i+=`
101
- `),t+=1,n=e[t+1];return i||(i=" "),{fold:i,offset:t}}var MN={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function BN(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}}jf.resolveFlowScalar=$N});var Hf=R($f=>{"use strict";var Yt=M(),Of=Z(),qN=Us(),VN=Ks();function zN(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?qN.resolveBlockScalar(e,t,n):VN.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[Yt.SCALAR]:c?l=WN(e.schema,r,c,i,n):t.type==="scalar"?l=JN(e,r,t,n):l=e.schema[Yt.SCALAR];let u;try{let d=l.resolve(r,f=>n(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Yt.isScalar(d)?d:new Of.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(i??t,"TAG_RESOLVE_FAILED",f),u=new Of.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 WN(e,t,i,n,r){if(i==="!")return e[Yt.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[Yt.SCALAR])}function JN({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[Yt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[Yt.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}$f.composeScalar=zN});var Ff=R(Df=>{"use strict";function UN(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}Df.emptyScalarPosition=UN});var Bf=R(Xs=>{"use strict";var GN=an(),KN=M(),YN=Tf(),Lf=Hf(),XN=Pi(),QN=Ff(),ZN={composeNode:Mf,composeEmptyNode:Ys};function Mf(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=eb(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=Lf.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=YN.composeCollection(ZN,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=Ys(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&&(!KN.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 Ys(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:QN.emptyScalarPosition(t,i,n),indent:-1,source:""},d=Lf.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 eb({options:e},{offset:t,source:i,end:n},r){let a=new GN.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=XN.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Xs.composeEmptyNode=Ys;Xs.composeNode=Mf});var zf=R(Vf=>{"use strict";var tb=bn(),qf=Bf(),ib=Pi(),nb=Cn();function rb(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new tb.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=nb.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?qf.composeNode(l,r,u,o):qf.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=ib.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Vf.composeDoc=rb});var Zs=R(Uf=>{"use strict";var ab=Rr("process"),ob=Fo(),sb=bn(),Rn=En(),Wf=M(),cb=zf(),lb=Pi();function Pn(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function Jf(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,n=e[t+1];return i||(i=" "),{fold:i,offset:t}}var ZN={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function eb(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}}qf.resolveFlowScalar=UN});var zf=R(Wf=>{"use strict";var Qt=M(),Vf=te(),tb=oc(),ib=cc();function nb(e,t,i,n){let{value:r,type:a,comment:o,range:s}=t.type==="block-scalar"?tb.resolveBlockScalar(e,t,n):ib.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[Qt.SCALAR]:c?l=rb(e.schema,r,c,i,n):t.type==="scalar"?l=ab(e,r,t,n):l=e.schema[Qt.SCALAR];let u;try{let d=l.resolve(r,f=>n(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Qt.isScalar(d)?d:new Vf.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(i??t,"TAG_RESOLVE_FAILED",f),u=new Vf.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 rb(e,t,i,n,r){if(i==="!")return e[Qt.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[Qt.SCALAR])}function ab({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[Qt.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(n))??i[Qt.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}Wf.composeScalar=nb});var Gf=R(Jf=>{"use strict";function ob(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}Jf.emptyScalarPosition=ob});var Yf=R(uc=>{"use strict";var sb=ln(),cb=M(),lb=Lf(),Uf=zf(),ub=Ti(),db=Gf(),fb={composeNode:Kf,composeEmptyNode:lc};function Kf(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=hb(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=Uf.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=lb.composeCollection(fb,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=lc(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&&(!cb.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 lc(e,t,i,n,{spaceBefore:r,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:db.emptyScalarPosition(t,i,n),indent:-1,source:""},d=Uf.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 hb({options:e},{offset:t,source:i,end:n},r){let a=new sb.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=ub.resolveEnd(n,o,e.strict,r);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}uc.composeEmptyNode=lc;uc.composeNode=Kf});var Zf=R(Qf=>{"use strict";var pb=Cn(),Xf=Yf(),mb=Ti(),vb=xn();function gb(e,t,{offset:i,start:n,value:r,end:a},o){let s=Object.assign({_directives:t},e),c=new pb.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=vb.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?Xf.composeNode(l,r,u,o):Xf.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=mb.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Qf.composeDoc=gb});var fc=R(ih=>{"use strict";var wb=jr("process"),yb=Xo(),Nb=Cn(),Tn=An(),eh=M(),bb=Zf(),kb=Ti();function In(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 th(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?`
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 Qs=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=Pn(i);a?this.warnings.push(new Rn.YAMLWarning(o,n,r)):this.errors.push(new Rn.YAMLParseError(o,n,r))},this.directives=new ob.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=Jf(this.prelude);if(n){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
- ${n}`:n;else if(r||t.directives.docStart||!a)t.commentBefore=n;else if(Wf.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Wf.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
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 dc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,n,r,a)=>{let o=In(i);a?this.warnings.push(new Tn.YAMLWarning(o,n,r)):this.errors.push(new Tn.YAMLParseError(o,n,r))},this.directives=new yb.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:n,afterEmptyLine:r}=th(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(eh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];eh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
107
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:Jf(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(ab.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,n,r)=>{let a=Pn(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=cb.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 Rn.YAMLParseError(Pn(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Rn.YAMLParseError(Pn(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=lb.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 Rn.YAMLParseError(Pn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),r=new sb.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}}};Uf.Composer=Qs});var Yf=R(ga=>{"use strict";var ub=Us(),db=Ks(),fb=En(),Gf=un();function hb(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 fb.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return db.resolveFlowScalar(e,t,n);case"block-scalar":return ub.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function pb(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=Gf.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:`
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:th(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(wb.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,n,r)=>{let a=In(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",n,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=bb.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 Tn.YAMLParseError(In(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 Tn.YAMLParseError(In(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let i=kb.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 Tn.YAMLParseError(In(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 Nb.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}}};ih.Composer=dc});var ah=R(Ea=>{"use strict";var Sb=oc(),Eb=cc(),Cb=An(),nh=pn();function Rb(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 Cb.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Eb.resolveFlowScalar(e,t,n);case"block-scalar":return Sb.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function Pb(e,t){let{implicitKey:i=!1,indent:n,inFlow:r=!1,offset:a=-1,type:o="PLAIN"}=t,s=nh.stringifyString({type:o,value:e},{implicitKey:i,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),u=s.substring(0,l),d=s.substring(l+1)+`
112
- `,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return Kf(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
113
- `}),{type:"block-scalar",offset:a,indent:n,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function mb(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=Gf.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">":vb(e,c);break;case'"':ec(e,c,"double-quoted-scalar");break;case"'":ec(e,c,"single-quoted-scalar");break;default:ec(e,c,"scalar")}}function vb(e,t){let i=t.indexOf(`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return rh(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 Ab(e,t,i={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=nh.stringifyString({type:o,value:t},{implicitKey:r||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":xb(e,c);break;case'"':hc(e,c,"double-quoted-scalar");break;case"'":hc(e,c,"single-quoted-scalar");break;default:hc(e,c,"scalar")}}function xb(e,t){let i=t.indexOf(`
114
114
  `),n=t.substring(0,i),r=t.substring(i+1)+`
115
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,e.source=r}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];Kf(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:r})}}function Kf(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function ec(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})}}}ga.createScalarToken=pb;ga.resolveAsScalar=hb;ga.setScalarValue=mb});var Qf=R(Xf=>{"use strict";var gb=e=>"type"in e?ya(e):wa(e);function ya(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=ya(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=wa(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=wa(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=wa(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 wa({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=ya(t)),i)for(let a of i)r+=a.source;return n&&(r+=ya(n)),r}Xf.stringify=gb});var ih=R(th=>{"use strict";var tc=Symbol("break visit"),wb=Symbol("skip children"),Zf=Symbol("remove item");function Xt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),eh(Object.freeze([]),e,t)}Xt.BREAK=tc;Xt.SKIP=wb;Xt.REMOVE=Zf;Xt.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};Xt.parentCollection=(e,t)=>{let i=Xt.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 eh(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=eh(Object.freeze(e.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===tc)return tc;s===Zf&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}th.visit=Xt});var Na=R(pe=>{"use strict";var ic=Yf(),yb=Qf(),Nb=ih(),nc="\uFEFF",rc="",ac="",oc="",bb=e=>!!e&&"items"in e,Sb=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function kb(e){switch(e){case nc:return"<BOM>";case rc:return"<DOC>";case ac:return"<FLOW_END>";case oc:return"<SCALAR>";default:return JSON.stringify(e)}}function Eb(e){switch(e){case nc:return"byte-order-mark";case rc:return"doc-mode";case ac:return"flow-error-end";case oc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
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}];rh(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 rh(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 hc(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})}}}Ea.createScalarToken=Pb;Ea.resolveAsScalar=Rb;Ea.setScalarValue=Ab});var sh=R(oh=>{"use strict";var Tb=e=>"type"in e?Ra(e):Ca(e);function Ra(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Ra(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ca(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ca(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ca(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 Ca({start:e,key:t,sep:i,value:n}){let r="";for(let a of e)r+=a.source;if(t&&(r+=Ra(t)),i)for(let a of i)r+=a.source;return n&&(r+=Ra(n)),r}oh.stringify=Tb});var dh=R(uh=>{"use strict";var pc=Symbol("break visit"),Ib=Symbol("skip children"),ch=Symbol("remove item");function Zt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),lh(Object.freeze([]),e,t)}Zt.BREAK=pc;Zt.SKIP=Ib;Zt.REMOVE=ch;Zt.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};Zt.parentCollection=(e,t)=>{let i=Zt.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 lh(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=lh(Object.freeze(e.concat([[r,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===pc)return pc;s===ch&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}uh.visit=Zt});var Pa=R(ge=>{"use strict";var mc=ah(),_b=sh(),jb=dh(),vc="\uFEFF",gc="",wc="",yc="",Ob=e=>!!e&&"items"in e,$b=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Hb(e){switch(e){case vc:return"<BOM>";case gc:return"<DOC>";case wc:return"<FLOW_END>";case yc:return"<SCALAR>";default:return JSON.stringify(e)}}function Fb(e){switch(e){case vc:return"byte-order-mark";case gc:return"doc-mode";case wc:return"flow-error-end";case yc: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}pe.createScalarToken=ic.createScalarToken;pe.resolveAsScalar=ic.resolveAsScalar;pe.setScalarValue=ic.setScalarValue;pe.stringify=yb.stringify;pe.visit=Nb.visit;pe.BOM=nc;pe.DOCUMENT=rc;pe.FLOW_END=ac;pe.SCALAR=oc;pe.isCollection=bb;pe.isScalar=Sb;pe.prettyToken=kb;pe.tokenType=Eb});var lc=R(rh=>{"use strict";var An=Na();function $e(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var nh=new Set("0123456789ABCDEFabcdef"),Cb=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ba=new Set(",[]{}"),Rb=new Set(` ,[]{}
121
- \r `),sc=e=>!e||Rb.has(e),cc=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}ge.createScalarToken=mc.createScalarToken;ge.resolveAsScalar=mc.resolveAsScalar;ge.setScalarValue=mc.setScalarValue;ge.stringify=_b.stringify;ge.visit=jb.visit;ge.BOM=vc;ge.DOCUMENT=gc;ge.FLOW_END=wc;ge.SCALAR=yc;ge.isCollection=Ob;ge.isScalar=$b;ge.prettyToken=Hb;ge.tokenType=Fb});var kc=R(hh=>{"use strict";var _n=Pa();function He(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var fh=new Set("0123456789ABCDEFabcdef"),Db=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Aa=new Set(",[]{}"),Lb=new Set(` ,[]{}
121
+ \r `),Nc=e=>!e||Lb.has(e),bc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let n=this.next??"stream";for(;n&&(i||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
122
122
  `?!0:i==="\r"?this.buffer[t+1]===`
123
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
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==="...")&&$e(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]===An.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 An.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==="...")&&$e(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&&!$e(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===":")&&$e(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(sc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,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("..."))&&$e(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield An.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(sc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||$e(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(`
125
+ `||n>=this.indentNext||!i&&!this.atEnd?t+n:-1}if(i==="-"||i==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&He(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]===_n.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 _n.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==="...")&&He(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&&!He(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===":")&&He(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(Nc),"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("..."))&&He(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield _n.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(Nc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||He(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
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=>$e(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`
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=>He(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":i+=1;break;case`
129
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
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
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
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 An.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($e(a)||t&&ba.has(a))break;i=n}else if($e(r)){let a=this.buffer[n+1];if(r==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield _n.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(He(a)||t&&Aa.has(a))break;i=n}else if(He(r)){let a=this.buffer[n+1];if(r==="\r"&&(a===`
134
134
  `?(n+=1,r=`
135
- `,a=this.buffer[n+1]):i=n),a==="#"||t&&ba.has(a))break;if(r===`
136
- `){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&ba.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield An.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(sc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if($e(n)||i&&ba.has(n)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!$e(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(Cb.has(i))i=this.buffer[++t];else if(i==="%"&&nh.has(this.buffer[t+1])&&nh.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===`
135
+ `,a=this.buffer[n+1]):i=n),a==="#"||t&&Aa.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&&Aa.has(r))break;i=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield _n.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(Nc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,n=this.charAt(1);if(He(n)||i&&Aa.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(;!He(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(Db.has(i))i=this.buffer[++t];else if(i==="%"&&fh.has(this.buffer[t+1])&&fh.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)}};rh.Lexer=cc});var dc=R(ah=>{"use strict";var uc=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}}}};ah.LineCounter=uc});var hc=R(uh=>{"use strict";var Pb=Rr("process"),oh=Na(),Ab=lc();function At(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function sh(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 lh(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 Sa(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 Ai(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 ka(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 ch(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!At(t.start,"explicit-key-ind")&&!At(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,lh(t.value)?t.value.end?ka(t.value.end,t.sep):t.value.end=t.sep:ka(t.start,t.sep),delete t.sep)}var fc=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 Ab.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,Pb.env.LOG_TOKENS&&console.log("|",oh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=oh.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"&&ch(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&&sh(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":{sh(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=Sa(this.peek(2)),n=Ai(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,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)}};hh.Lexer=bc});var Ec=R(ph=>{"use strict";var Sc=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}}}};ph.LineCounter=Sc});var Rc=R(yh=>{"use strict";var Mb=jr("process"),mh=Pa(),Bb=kc();function xt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function vh(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 wh(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 xa(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 Ii(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 Ta(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 gh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!xt(t.start,"explicit-key-ind")&&!xt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,wh(t.value)?t.value.end?Ta(t.value.end,t.sep):t.value.end=t.sep:Ta(t.start,t.sep),delete t.sep)}var Cc=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 Bb.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,Mb.env.LOG_TOKENS&&console.log("|",mh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=mh.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"&&gh(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&&vh(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":{vh(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=xa(this.peek(2)),n=Ii(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(`
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)){ka(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(At(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(lh(i.key)&&!At(i.sep,"newline")){let o=Ai(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(At(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ai(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]}):At(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&&!At(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)){ka(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||At(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=Sa(n),a=Ai(r);ch(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 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)){Ta(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(xt(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(wh(i.key)&&!xt(i.sep,"newline")){let o=Ii(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(xt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ii(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]}):xt(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&&!xt(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)){Ta(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||xt(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=xa(n),a=Ii(r);gh(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=Sa(t),n=Ai(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=Sa(t),n=Ai(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())}}};uh.Parser=fc});var mh=R(Tn=>{"use strict";var dh=Zs(),xb=bn(),xn=En(),Tb=Xo(),Ib=M(),_b=dc(),fh=hc();function hh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new _b.LineCounter||null,prettyErrors:t}}function jb(e,t={}){let{lineCounter:i,prettyErrors:n}=hh(t),r=new fh.Parser(i?.addNewLine),a=new dh.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(xn.prettifyError(e,i)),s.warnings.forEach(xn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function ph(e,t={}){let{lineCounter:i,prettyErrors:n}=hh(t),r=new fh.Parser(i?.addNewLine),a=new dh.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 xn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(xn.prettifyError(e,i)),o.warnings.forEach(xn.prettifyError(e,i))),o}function Ob(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=ph(e,i);if(!r)return null;if(r.warnings.forEach(a=>Tb.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 $b(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 Ib.isDocument(e)&&!n?e.toString(i):new xb.Document(e,n,i).toString(i)}Tn.parse=Ob;Tn.parseAllDocuments=jb;Tn.parseDocument=ph;Tn.stringify=$b});var mc=R(z=>{"use strict";var Hb=Zs(),Db=bn(),Fb=js(),pc=En(),Lb=an(),xt=M(),Mb=Et(),Bb=Z(),qb=Rt(),Vb=Pt(),zb=Na(),Wb=lc(),Jb=dc(),Ub=hc(),Ea=mh(),vh=en();z.Composer=Hb.Composer;z.Document=Db.Document;z.Schema=Fb.Schema;z.YAMLError=pc.YAMLError;z.YAMLParseError=pc.YAMLParseError;z.YAMLWarning=pc.YAMLWarning;z.Alias=Lb.Alias;z.isAlias=xt.isAlias;z.isCollection=xt.isCollection;z.isDocument=xt.isDocument;z.isMap=xt.isMap;z.isNode=xt.isNode;z.isPair=xt.isPair;z.isScalar=xt.isScalar;z.isSeq=xt.isSeq;z.Pair=Mb.Pair;z.Scalar=Bb.Scalar;z.YAMLMap=qb.YAMLMap;z.YAMLSeq=Vb.YAMLSeq;z.CST=zb;z.Lexer=Wb.Lexer;z.LineCounter=Jb.LineCounter;z.Parser=Ub.Parser;z.parse=Ea.parse;z.parseAllDocuments=Ea.parseAllDocuments;z.parseDocument=Ea.parseDocument;z.stringify=Ea.stringify;z.visit=vh.visit;z.visitAsync=vh.visitAsync});import{promises as pl}from"fs";import Vp from"path";var lo=Pu(mc(),1);import{promises as Hp}from"fs";import lt from"path";import{createHash as Xb}from"node:crypto";import{promises as He}from"node:fs";import Re from"node:path";import{TextDecoder as Qb}from"node:util";import vc from"path";var Gb=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Kb=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Yb(e){return e.toLowerCase().startsWith(".env")}function Xe(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Yb(n))?"environment-file":i.some(n=>Kb.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Gb.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function gc(e,t){let i=Xe(t);if(i)return i;let n=vc.resolve(e.projectRoot,...t.split("/")),r=vc.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===vc.resolve(e.configFile)?"native-runtime":null}function Tt(e){return e!==0&&e!==0n&&e!=="0"}function ae(e,t){return Tt(e.dev)&&Tt(t.dev)&&Tt(e.ino)&&Tt(t.ino)}function L(e,t){let i=Tt(e.dev)&&Tt(t.dev);if(i&&e.dev!==t.dev)return!1;let n=Tt(e.ino)&&Tt(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var In=1024*1024;function wc(e,t){let i=Re.relative(e,t);return i===""||!Re.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Re.sep}`)}function Zb(e){let t=Re.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})||Re.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=Xe(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 eS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function tS(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ca(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ae(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function gh(e){let t=await He.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function iS(e,t){let i=Re.resolve(e),n=Re.resolve(t);if(!wc(i,n))throw new Error("Native artifact path is outside its root");let r=[await gh(i)],a=i;for(let o of Re.relative(i,n).split(Re.sep).filter(Boolean)){a=Re.join(a,o);let s=await gh(a);if(!wc(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function wh(e){for(let t of e){let i=await He.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!tS(t,i)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function oe(e){let t=Zb(e.ref),i=eS(e.maxBytes??In),n=Re.resolve(e.root,...t.split("/")),r=await iS(e.root,Re.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await He.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 He.realpath(n);if(!wc(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await He.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),He.lstat(n),He.realpath(n)]);if(await wh(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ca(a,c)||!Ca(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 S=i+1-f,b=await s.read(p,0,Math.min(p.length,S),null);if(b.bytesRead===0)break;if(f+=b.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),He.lstat(n),He.realpath(n)]);if(await wh(r),!h.isFile()||h.isSymbolicLink()||v!==o||!Ca(c,m)||!Ca(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let N=Buffer.concat(d,f),k;try{k=new Qb("utf-8",{fatal:!0}).decode(N)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:Xb("sha256").update(N).digest("hex"),text:k}}finally{await s.close()}}import{randomUUID as nS}from"crypto";import{promises as se}from"fs";import De from"path";function Nc(e,t){let i=De.relative(e,t);return i===""||!De.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${De.sep}`)}function rS(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ae(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function yh(e){let t=await se.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 se.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function _n(e){for(let t of e){let i=await se.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!rS(t,i)||await se.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function aS(e,t){let i=De.resolve(e),n=De.resolve(t);if(!Nc(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await yh(i)],a=De.relative(i,n).split(De.sep).filter(Boolean),o=i;for(let s of a){await _n(r),o=De.join(o,s);try{await se.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await yh(o);if(!Nc(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await _n(r),r}async function oS(e){let t;try{t=await se.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 sS(e,t,i={}){let n=De.dirname(e),r=i.containedRoot?await aS(i.containedRoot,n):null;r||await se.mkdir(n,{recursive:!0});let a=De.join(n,`.${De.basename(e)}.${nS()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await se.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([se.lstat(a),se.realpath(a)]);if(await _n(r),!c.isFile()||c.isSymbolicLink()||!yc(s,c)||!Nc(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(),!yc(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 _n(r);let c=await se.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!yc(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await se.link(a,e),await se.unlink(a)):await se.rename(a,e),await oS(n)}catch(c){if(await o?.close(),!r)await se.rm(a,{force:!0});else try{await _n(r),await se.rm(a,{force:!0})}catch{}throw c}}async function Qt(e,t,i={}){await sS(e,t,i)}async function Fe(e,t,i={}){await Qt(e,JSON.stringify(t,null,2)+`
143
- `,i)}var Sc=Pu(mc(),1);import Ra from"path";var xa=64*1024,Pa=1024,Aa=64,kc=5,cS=[".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/**"],me={include:["**/*"],exclude:[...cS],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function lS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Ra.posix.isAbsolute(i)||Ra.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function Zt(e){let t=lS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function bh(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 Ec(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||Ra.posix.isAbsolute(n)||Ra.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function jn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Sh(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 Ta(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>Pa)throw new Error(`${t} exceeds ${Pa} 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>Aa)throw new Error(`${t} contains more than ${Aa} wildcard tokens`);return e}function Nh(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=>Ta(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function bc(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 uS(e){if(e===void 0)return{...me,include:[...me.include],exclude:[...me.exclude]};let t=jn(e,"native.snapshot");return{include:Nh(t.include,"native.snapshot.include",me.include),exclude:Nh(t.exclude,"native.snapshot.exclude",me.exclude),max_files:bc(t.max_files,me.max_files,"native.snapshot.max_files"),max_total_bytes:bc(t.max_total_bytes,me.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:bc(t.max_duration_ms,me.max_duration_ms,"native.snapshot.max_duration_ms")}}function dS(e){if(e===void 0)return;let t=jn(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=jn(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:Zt(n),toArtifactRoot:Zt(r),stage:a,...o?{cleanup:o}:{}}}function fS(e){let t=jn(e,"native");if(typeof t.artifact_root!="string")throw new Error("native.artifact_root must be a string");let i=t.clarification_mode??"sequential";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let n=t.archive_confirmation??"automatic";if(n!=="automatic"&&n!=="required")throw new Error("native.archive_confirmation must be automatic or required");let r=t.max_verify_failures??kc;if(!Number.isSafeInteger(r)||r<1)throw new Error("native.max_verify_failures must be a positive integer");let a=dS(t.pending_root_move);return{artifact_root:Zt(t.artifact_root),language:Sh(t.language,"en","native.language"),clarification_mode:i,archive_confirmation:n,max_verify_failures:r,snapshot:uS(t.snapshot),...a?{pending_root_move:a}:{}}}function hS(e){let t=jn(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:bh(t.artifact_layout),language:Sh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function pS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function mS(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 Ia(e,t={}){let i=(0,Sc.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=pS(r.ambient_resume),o=r.native===void 0?void 0:fS(r.native),s=r.classic===void 0?void 0:hS(r.classic),c=mS(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Cc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Zt(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:kc,snapshot:{...me,include:[...me.include],exclude:[...me.exclude]}}}}import{createHash as gS}from"crypto";import{promises as Oa}from"fs";import It from"path";import{constants as _a,promises as ei}from"fs";var Le=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function Rc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function kh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function On(e){return{dev:e.dev,ino:e.ino,birthtime:Rc(e)}}function ja(e,t){let i=On(e),n=On(t);return ae(i,n)?L(i,n):L(i,n)&&Rc(e)===Rc(t)&&kh(e)===kh(t)&&e.size===t.size}async function ti(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 ei.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Le("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Le("too-large",`${n} exceeds ${t} bytes`);let o=await ei.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:On(a)});let s=process.platform==="win32"?_a.O_RDONLY:_a.O_RDONLY|_a.O_NOFOLLOW|_a.O_NONBLOCK,c;try{c=await ei.open(e,s)}catch(l){throw l.code==="ELOOP"?new Le("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),ei.lstat(e,{bigint:r}),ei.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ja(a,l)||!ja(a,u))throw new Le("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:On(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let k=t+1-p,{bytesRead:S}=await c.read(m,0,Math.min(m.length,k),null);if(S===0)break;if(p+=S,p>t)throw new Le("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([c.stat({bigint:r}),ei.lstat(e,{bigint:r}),ei.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||N!==o||!ja(a,h)||!ja(a,v))throw new Le("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:On(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:N}}finally{await c.close()}}function vS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Pc(e,t){let i=It.relative(e,t);return i===""||!It.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${It.sep}`)}async function Eh(e,t){let i=It.resolve(e),n=await Oa.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Oa.realpath(i)}async function Ch(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=It.join(r,i[a]);let o;try{o=await Oa.lstat(r)}catch(u){if(vS(u))return{exists:!1,kind:"missing"};throw u}let s=It.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 Oa.realpath(r);if(!Pc(t,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function $n(e,t,i){let n=Ec(t,i.label),r=It.resolve(e),a=await Eh(r,i.label),o=n.split("/"),s=It.resolve(r,...o);if(!Pc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Ch(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function xi(e,t,i,n){let r=await $n(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 Eh(r.projectRoot,n.label);return ti(r.target,i,{...n,verify:async(o,s)=>{if(!Pc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Ch(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var Hn=".comet/config.yaml";function wS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ac(e,t={}){return(await $a(e,t)).document}async function yS(e){try{return(await xi(e,Hn,xa,{label:Hn})).bytes}catch(t){if(wS(t))return null;throw t}}function NS(e){return e?{exists:!0,sha256:gS("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function $a(e,t={}){let i=await yS(e);return{document:i?Ia(i.toString("utf8"),t):null,identity:NS(i)}}var WT=16*1024;import{promises as Ti}from"fs";import G from"path";import ES from"os";var Ha=".comet/config.yaml";async function Tc(e){try{return await Ti.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function CS(e){try{let t=await Ti.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Dn(e,t){let i=G.relative(e,t);return i===""||!G.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${G.sep}`)}async function Fn(e){let t=[],i=e;for(;!await Tc(i);){let r=G.dirname(i);if(r===i)break;t.push(G.basename(i)),i=r}let n=await Ti.realpath(i);return G.resolve(n,...t.reverse())}async function xh(e){try{return(await Ti.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Da(e){let t=G.resolve(e);try{(await Ti.stat(t)).isDirectory()||(t=G.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=G.resolve(ES.homedir());for(;;){if(!(t===n&&i!==n)){let o=G.join(t,...Ha.split("/")),s=t===i||await CS(o);if(await Tc(o)&&s)return t}if(await Tc(G.join(t,".git")))return t;let a=G.dirname(t);if(a===t)return i;t=a}}function Fa(e){return Zt(e)}async function RS(e,t){let i=Fa(t),n=G.resolve(e,...i.split("/")),r=await Ti.realpath(e),a=await Fn(n);if(!Dn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Ic(e,t){let i=Fa(t),n=await RS(e,i),r=G.join(n,"comet");if(await xh(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Fn(n),Fn(r)]);if(!Dn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:G.resolve(e),configFile:G.join(e,...Ha.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:G.join(r,"specs"),changesDir:G.join(r,"changes"),archiveDir:G.join(r,"archive"),runtimeDir:G.join(r,"runtime"),locksDir:G.join(r,"runtime","locks"),transactionsDir:G.join(r,"runtime","transactions")}}function J(e,t){return Dn(G.resolve(e),G.resolve(t))}async function H(e,t){let i=G.resolve(e),n=G.resolve(t);if(!Dn(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await xh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([Fn(i),Fn(n)]);if(!Dn(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var _c=me;var La=Ta;function AS(e="docs",t="en"){return Cc(e,t)}async function _t(e){let t=(await Ac(e))?.config??null;return t?.native?t:null}async function Ln(e){let t=await _t(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 Th(e){let t=await Da(e.startPath),i=await _t(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Ha} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?Fa(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??AS(n??"docs"),a=await Ic(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as ik}from"fs";import nk from"path";import{AsyncLocalStorage as xS}from"async_hooks";import{randomUUID as jh}from"crypto";import{promises as Pe}from"fs";import Oh from"os";import le from"path";var Ih=16*1024,$h=".coordinator",TS=5e3,_h=new xS,Ma=new Map;function IS(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function _S(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 Hh(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 jc(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ae(i,n)?L(i,n):L(i,n)&&e.size===t.size}function Oc(e,t){return jc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function st(e){let t,i;try{let n=await ti(e,Ih,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Le?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Ih} 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:_S(JSON.parse(t.toString("utf8")),e),identity:Hh(i)}}async function jS(e){return(await st(e))?.owner??null}function Dh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Oh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=LS(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function OS(e,t){try{await Pe.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Pe.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function $c(e,t){let i=await st(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Pe.mkdir(t,{recursive:!0});let n=le.join(t,`${le.basename(e.file)}.${e.owner.id}.${jh()}.removed`);try{await Pe.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await st(n);if(!r||r.owner.id!==e.owner.id||!jc(r.identity,e.identity))throw await OS(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Pe.rm(n,{force:!0}),"removed"}function Fh(e){return{id:jh(),pid:process.pid,hostname:Oh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Lh(e,t){let i;try{i=await Pe.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await jS(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
144
- `,"utf8"),await i.sync(),Hh(await i.stat({bigint:!0}))}finally{await i.close()}}async function $S(e,t){let i=await H(e.nativeRoot,e.locksDir);await Pe.mkdir(i,{recursive:!0});let n=await H(e.nativeRoot,le.join(i,$h));await Pe.mkdir(n,{recursive:!0});let r=Fh(t),a=le.join(n,`.${r.id}.tmp`),o=le.join(n,`${r.id}.claim`);try{let s=await Lh(a,r);await Pe.rename(a,o);let c=await st(o);if(!c||!jc(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 Pe.rm(a,{force:!0})}}async function HS(e){let t=le.dirname(e.file),i=!1,n=le.basename(e.file);for(let r of await Pe.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=le.join(t,r.name);if(le.resolve(a)!==le.resolve(e.file))try{let o=await st(a),s=Dh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await $c(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Mh(e){let t=await st(e.file);if(t){if(t.owner.id!==e.owner.id||!Oc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await $c(t,le.dirname(e.file))}}async function DS(e,t){let i=Date.now()+TS;for(;;){let n=await $S(e,t);if(!await HS(n))return n;if(await Mh(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 FS(e){let t=Ma.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Ma.set(e,r),await t,()=>{i(),Ma.get(e)===r&&Ma.delete(e)}}async function Bh(e,t,i){let n=le.resolve(e.locksDir),r=_h.getStore();if(r?.has(n))return i();let a=await FS(n);try{let o=await DS(e,t),s=new Map(r??[]);return s.set(n,o),await _h.run(s,async()=>{try{return await i()}finally{await Mh(o)}})}finally{a()}}async function Mn(e,t,i){return Bh(e,`acquire ${t}`,async()=>{let n=await H(e.nativeRoot,e.locksDir);await Pe.mkdir(n,{recursive:!0});let r=await H(e.nativeRoot,le.join(n,IS(t))),a=Fh(i),o=await Lh(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Bn(e){await st(e.file)&&await Bh(e,`release ${le.basename(e.file)}`,async()=>{let t=await st(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=le.join(e.locksDir,$h);await $c(t,i)})}function LS(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function qh(e){return Dh(await st(e))}import ct from"path";import{TextDecoder as JS}from"util";import{createHash as MS}from"node:crypto";import{constants as Ba,promises as be}from"node:fs";import Me from"node:path";import{TextDecoder as BS}from"node:util";function Va(e,t){let i=Me.relative(e,t);return i===""||!Me.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Me.sep}`)}function Vh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function qS(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function VS(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function qa(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Hc(e,t){let i=await be.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await be.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Dc(e,t,i){let n=Me.resolve(e),r=Me.resolve(t);if(!Va(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Hc(n,i)],o=n;for(let s of Me.relative(n,r).split(Me.sep).filter(Boolean)){await Qe(a,i),o=Me.join(o,s);let c=await Hc(o,i);if(!Va(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Qe(a,i),a}async function Qe(e,t){for(let i of e){let n=await be.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!qS(i,n)||await be.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function zS(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 Ze(e){let t=Vh(e.maxBytes),i=Me.resolve(e.file),n=await Dc(e.root,Me.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Hc(Me.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Qe(n,e.label);let a=await be.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=VS(a),s=await be.realpath(i);if(!Va(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Va(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ba.O_RDONLY:Ba.O_RDONLY|Ba.O_NOFOLLOW|Ba.O_NONBLOCK,l=await be.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([be.lstat(i),be.realpath(i)]);if(await Qe(n,e.label),await Qe(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!qa(o,u)||!qa(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await zS(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),be.lstat(i),be.realpath(i)]);if(await Qe(n,e.label),await Qe(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!qa(o,m)||!qa(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:MS("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function zh(e){let t=await Ze(e),i;try{i=new BS("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 qn(e){let t=await Dc(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await be.readdir(e.directory,{withFileTypes:!0});else{let n=Vh(e.maxEntries);i=[];let r=await be.opendir(e.directory);try{for await(let a of r)if(i.push(a),i.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await r.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Qe(t,e.label),{entries:i,verify:()=>Qe(t,e.label)}}async function za(e){let t=await Dc(e.root,e.directory,e.label);return{verify:()=>Qe(t,e.label)}}var US=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),GS=new Set(["id","type","source","target","staged","backup"]),KS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),YS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Uh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var XS=256*1024,$I=1024*1024,HI=16*1024;var DI=64*1024*1024;var QS=new JS("utf-8",{fatal:!0});function Ja(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ua(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 Gh(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Fc(e,t){if(typeof e!="string"||e.length===0||ct.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Wa(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Wh(e,t){if(Fc(e,t),e.includes("\\")||e!==ct.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function ZS(e,t){let i=Ja(e,`transaction operations[${t}]`);if(Ua(i,GS,`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`);Fc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Fc(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 Kh(e){let t=Ja(e,"Native Archive transaction journal");if(Ua(t,KS,"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"||!Uh.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(!Gh(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Wa(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=Ja(s,`Archive transaction operations[${c}]`);if(Ua(l,YS,`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`);Wh(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Wh(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Wa(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(Wa(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`);Wa(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 ek(e){let t=Ja(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Kh(t);if(Ua(t,US,"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"||!Uh.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ct.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ct.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(!Gh(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(ZS),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function tk(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ct.join(e.transactionsDir,t)}function Yh(e,t){let i=tk(e,t);return{directory:i,journal:ct.join(i,"transaction.json"),events:ct.join(i,"events.jsonl"),staged:ct.join(i,"staged"),backups:ct.join(i,"backups")}}async function Lc(e,t){let i=Yh(e,t);return await Promise.all(Object.values(i).map(n=>H(e.nativeRoot,n))),i}async function Mc(e,t,i={}){let n=await Lc(e,t),r=await Ze({root:e.nativeRoot,file:n.journal,maxBytes:XS,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(QS.decode(r.bytes)),o=ek(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function rk(e,t){let i;try{i=await ik.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 Mc(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function ak(e,t){let i=Date.now()+5e3,n=nk.join(e.locksDir,"root-move.lock");for(;;)try{return await Mn(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await qh(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function et(e,t,i,n){let r=await ak(e,t);try{if(await Ln(e.projectRoot),await rk(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Bn(r)}}function Xh(e){return Number.isSafeInteger(e)&&e>=1}async function Qh(e){if(!Xh(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(!Xh(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 Za}from"crypto";import{spawn as cp}from"node:child_process";import{promises as X}from"fs";import V from"path";import{createHash as Zh}from"crypto";import{createReadStream as ok}from"fs";async function Vn(e){let t=Zh("sha256");for await(let i of ok(e))t.update(i);return t.digest("hex")}function W(e){return Zh("sha256").update(e).digest("hex")}var Ga={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Uc=1e3,sk=8*1024*1024,ck=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lk=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),uk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),dk=new Set(["schema","include","exclude","hash"]),fk=new Set(["provider","gitSelection","physicalSelection","projection"]),hk=new Set(["provider","selection"]),pk=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),mk=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),vk=new Set(["schema","status","before","after"]),gk=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),wk=new Set(["path","hash","size","type","gitObjectId"]),yk=new Set(["path","size","type","reason"]),Nk=new Set(["ref","hash","count"]),bk=new Set(["change-created","legacy-migration","explicit"]),Sk=new Set(["file","directory","other"]),kk=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"]),eo=/^[a-f0-9]{64}$/u,lp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Ek=new Set(["EACCES","EPERM"]),ji=64*1024,zc=64*1024,Ck=6e4,Rk=1e3,Pk=2,Gc={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Ak={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function up(e){let t=e.deadlineMs??Ck;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 Be(e){return Math.max(0,e.deadlineAt-Date.now())}function j(e){return Be(e)>=1}function Bc(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 Jn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function xk(e){let t={...Ak,...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 Tk(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&&V.win32.isAbsolute(n)?V.win32.resolve(n):"C:\\Windows",a=V.win32.join(r,"System32","taskkill.exe");if(!V.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=cp(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),Rk),u.unref()}catch{d(!1)}});for(let s=0;s<Pk;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 Kc(e,t,i,n){let r=Be(e);if(r<1)throw Bc();let a=e.gitProcess,o=cp(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=Tk(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?Bc(m.error):Bc()}return{code:p,spawnError:s}});return{child:o,completion:f}}function dp(e){let t={...Gc,...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 Ya(e,t,i,n=zc){let{child:r,completion:a}=Kc(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>=ji)return;let m=ji-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 qc(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Ka(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}=Kc(e,t,i,n.stdin!==void 0),c=[],l=Za("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,N=!1,k=!1,S=b=>{let C=0;for(;C<b.byteLength;){let y=b.indexOf(0,C),w=y<0?b.byteLength:y,g=b.subarray(C,w);if(!v&&g.byteLength>0&&(h.byteLength+g.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,N=!0):h=Buffer.concat([h,g])),y<0)break;m+=1,h.byteLength===0&&!v&&(k=!0);let E=h.byteLength+1;!v&&m<=n.maxRecords&&p+E<=n.maxBytes?(c.push(h),p+=E):N=!0,h=Buffer.alloc(0),v=!1,C=y+1}};o.stdout.on("data",b=>{l.update(b),f+=b.byteLength,f>n.maxBytes&&(N=!0);let C=n.outputChunkBytes;if(C===void 0){S(b);return}for(let y=0;y<b.byteLength;y+=C)S(b.subarray(y,Math.min(b.byteLength,y+C)))}),o.stderr.on("data",b=>{if(d>=ji)return;let C=ji-d,y=Buffer.from(b).subarray(0,C);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:b,spawnError:C})=>{let y=n.acceptedExitCodes??[0];if(b!==null&&y.includes(b)&&C===null&&!k&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:N,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${C?`: ${C.message}`:k||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 Wc(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 Ik(e,t,i){if(i.length===0)return new Set;let n=await Ka(e,t,["check-ignore","--no-index","-z","--stdin"],{...Gc,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=Wc(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function _k(e,t,i){let{child:n,completion:r}=Kc(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>=ji)return;let d=ji-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 Xa(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function jk(e,t){return e.map(i=>{let n=Xa(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function Ok(e){let t=V.resolve(e);for(;;){try{return await X.lstat(V.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=V.dirname(t);if(i===t)return!1;t=i}}async function fp(e,t,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await Ka(e,t,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await Ka(e,t,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await Ka(e,t,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function hp(e){return{stageBefore:qc(e.stagedBefore),combined:qc(e.combined),stageAfter:qc(e.stagedAfter)}}async function pp(e,t,i=Gc,n={}){if(!await Ok(t))return null;let r;try{r=await Ya(e,t,["rev-parse","--is-inside-work-tree"])}catch(N){throw Jn(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}if(r.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let a;try{a=await fp(e,t,i,n)}catch(N){throw Jn(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,d=new Set,f=N=>{for(let k of N){let S=Wc(k),b=S.indexOf(" ");if(b<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let C=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(S.slice(0,b))?.groups;if(!C)throw new Error("Native Git snapshot provider returned a malformed staged header");let y=Xa(S.slice(b+1));if(y===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(y),C.stage==="0"&&u.set(y,C.objectId),C.mode==="160000"&&C.stage==="0"&&d.add(y)}};f(o.records),f(c.records);let p=s.records.map(Wc),m=jk(p,"combined"),h=new Set(m.filter(N=>!l.has(N))),v=new Set(m.filter((N,k)=>!l.has(N)&&p[k].endsWith("/")));for(let N of d)v.delete(N);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:d,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:hp(a)}}function Ot(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function ep(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function $k(e,t){return!Ot(e.stageBefore,e.stageAfter)||!Ot(e.stageAfter,t.stageBefore)||!Ot(e.combined,t.combined)||!Ot(t.stageBefore,t.stageAfter)}async function mp(e,t,i,n,r){let a;try{a=await fp(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw Jn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=hp(a),c=ep(o)||ep(s),l=$k(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:W(`comet.native.git-selection-overflow.v2
145
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var Hk=(1n<<256n)-1n;function Dk(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function tp(e){let t=V.resolve(e.paths.projectRoot),i=V.resolve(e.paths.nativeRoot),n=V.resolve(e.paths.configFile),r=V.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=()=>Be(e.execution)>=1?!0:(f=!0,m=!0,!1),v=S=>{let b=Buffer.from(`${S.type}\0${S.path}`,"utf8"),C=Za("sha256").update("comet.native.physical-selection-record.v1\0").update(b).digest();for(let y=0;y<s.length;y+=1)s[y]^=C[y];if(c=c+BigInt(`0x${C.toString("hex")}`)&Hk,u+=1,d+=b.byteLength,Buffer.byteLength(S.path,"utf8")>e.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(S)},N=async S=>{if(m||!h())return;let b;try{b=await X.opendir(S)}catch(E){if(!h())return;if(!te(E)&&!ee(E)||S===t&&te(E))throw E;p||=ee(E),f||=te(E),m=!0;return}if(!h()){try{await b.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let C=!1,y;try{for(;!m&&h();){let E;try{E=await b.read()}catch(Y){if(!h())break;if(!te(Y)&&!ee(Y)||S===t&&te(Y))throw Y;p||=ee(Y),f||=te(Y),m=!0;break}if(!h()||E===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let _=V.join(S,E.name),K=Lk(t,_);if(_===n||_===r||$t(i,_)||e.denylist.some(Y=>$t(Y,_))||Xe(K)!==null)continue;if(!h())break;let q;try{q=await X.lstat(_)}catch(Y){if(!h())break;if(!te(Y)&&!ee(Y))throw Y;if(p=!0,v({path:K,type:"other"}),o.push({path:K,size:null,type:"file",reason:te(Y)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(K),m||!h())break;continue}if(!h())break;let U=Dk(q);if(U==="directory"){if(Vk(e.policy,K))continue;if(!h())break;let Y;try{Y=await X.realpath(_)}catch(Ue){if(!h())break;if(!te(Ue)&&!ee(Ue))throw Ue;if(p=!0,v({path:K,type:U}),o.push({path:K,size:null,type:"directory",reason:te(Ue)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(K),m||!h())break;continue}if(!h())break;if(!J(e.physicalProjectRoot,Y)||$t(e.physicalNativeRoot,Y))continue;if(v({path:K,type:U}),await e.hooks?.afterNode?.(K),!h()||(await N(_),m))break;continue}if(v({path:K,type:U}),await e.hooks?.afterNode?.(K),!h()||m)break}}catch(E){C=!0,y=E}let w;try{await b.close()}catch(E){w=E}let g=h();if(C)throw y;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await N(t),h(),f?(a.length=0,u=0,d=0):(a.sort((S,b)=>S.path.localeCompare(b.path,"en")),o.sort((S,b)=>S.path.localeCompare(b.path,"en")));let k=f?W(`comet.native.physical-selection-incomplete.v1
142
+ `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=xa(t),n=Ii(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=xa(t),n=Ii(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())}}};yh.Parser=Cc});var Eh=R(On=>{"use strict";var Nh=fc(),qb=Cn(),jn=An(),Vb=us(),Wb=M(),zb=Ec(),bh=Rc();function kh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new zb.LineCounter||null,prettyErrors:t}}function Jb(e,t={}){let{lineCounter:i,prettyErrors:n}=kh(t),r=new bh.Parser(i?.addNewLine),a=new Nh.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(jn.prettifyError(e,i)),s.warnings.forEach(jn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Sh(e,t={}){let{lineCounter:i,prettyErrors:n}=kh(t),r=new bh.Parser(i?.addNewLine),a=new Nh.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 jn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(jn.prettifyError(e,i)),o.warnings.forEach(jn.prettifyError(e,i))),o}function Gb(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=Sh(e,i);if(!r)return null;if(r.warnings.forEach(a=>Vb.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Ub(e,t,i){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=i??t??{};if(!r)return}return Wb.isDocument(e)&&!n?e.toString(i):new qb.Document(e,n,i).toString(i)}On.parse=Gb;On.parseAllDocuments=Jb;On.parseDocument=Sh;On.stringify=Ub});var _a=R(V=>{"use strict";var Kb=fc(),Yb=Cn(),Xb=Js(),Pc=An(),Qb=ln(),Tt=M(),Zb=Ct(),ek=te(),tk=Pt(),ik=At(),nk=Pa(),rk=kc(),ak=Ec(),ok=Rc(),Ia=Eh(),Ch=an();V.Composer=Kb.Composer;V.Document=Yb.Document;V.Schema=Xb.Schema;V.YAMLError=Pc.YAMLError;V.YAMLParseError=Pc.YAMLParseError;V.YAMLWarning=Pc.YAMLWarning;V.Alias=Qb.Alias;V.isAlias=Tt.isAlias;V.isCollection=Tt.isCollection;V.isDocument=Tt.isDocument;V.isMap=Tt.isMap;V.isNode=Tt.isNode;V.isPair=Tt.isPair;V.isScalar=Tt.isScalar;V.isSeq=Tt.isSeq;V.Pair=Zb.Pair;V.Scalar=ek.Scalar;V.YAMLMap=tk.YAMLMap;V.YAMLSeq=ik.YAMLSeq;V.CST=nk;V.Lexer=rk.Lexer;V.LineCounter=ak.LineCounter;V.Parser=ok.Parser;V.parse=Ia.parse;V.parseAllDocuments=Ia.parseAllDocuments;V.parseDocument=Ia.parseDocument;V.stringify=Ia.stringify;V.visit=Ch.visit;V.visitAsync=Ch.visitAsync});import{promises as Rl}from"fs";import em from"path";var bo=Go(_a(),1);import{promises as Gp}from"fs";import ut from"path";import{createHash as uk}from"node:crypto";import{promises as Fe}from"node:fs";import Ae from"node:path";import{TextDecoder as dk}from"node:util";import Ac from"path";var sk=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ck=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function lk(e){return e.toLowerCase().startsWith(".env")}function Ze(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>lk(n))?"environment-file":i.some(n=>ck.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>sk.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function xc(e,t){let i=Ze(t);if(i)return i;let n=Ac.resolve(e.projectRoot,...t.split("/")),r=Ac.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Ac.resolve(e.configFile)?"native-runtime":null}function It(e){return e!==0&&e!==0n&&e!=="0"}function se(e,t){return It(e.dev)&&It(t.dev)&&It(e.ino)&&It(t.ino)}function L(e,t){let i=It(e.dev)&&It(t.dev);if(i&&e.dev!==t.dev)return!1;let n=It(e.ino)&&It(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var $n=1024*1024;function Tc(e,t){let i=Ae.relative(e,t);return i===""||!Ae.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ae.sep}`)}function fk(e){let t=Ae.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})||Ae.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=Ze(e);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function hk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function pk(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ja(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Rh(e){let t=await Fe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Fe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function mk(e,t){let i=Ae.resolve(e),n=Ae.resolve(t);if(!Tc(i,n))throw new Error("Native artifact path is outside its root");let r=[await Rh(i)],a=i;for(let o of Ae.relative(i,n).split(Ae.sep).filter(Boolean)){a=Ae.join(a,o);let s=await Rh(a);if(!Tc(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Ph(e){for(let t of e){let i=await Fe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pk(t,i)||await Fe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ce(e){let t=fk(e.ref),i=hk(e.maxBytes??$n),n=Ae.resolve(e.root,...t.split("/")),r=await mk(e.root,Ae.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Fe.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 Fe.realpath(n);if(!Tc(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Fe.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Fe.lstat(n),Fe.realpath(n)]);if(await Ph(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!ja(a,c)||!ja(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-f,b=await s.read(p,0,Math.min(p.length,k),null);if(b.bytesRead===0)break;if(f+=b.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([s.stat(),Fe.lstat(n),Fe.realpath(n)]);if(await Ph(r),!h.isFile()||h.isSymbolicLink()||g!==o||!ja(c,m)||!ja(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),N;try{N=new dk("utf-8",{fatal:!0}).decode(S)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:uk("sha256").update(S).digest("hex"),text:N}}finally{await s.close()}}import{randomUUID as vk}from"crypto";import{promises as le}from"fs";import De from"path";function _c(e,t){let i=De.relative(e,t);return i===""||!De.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${De.sep}`)}function gk(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ic(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ah(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 Hn(e){for(let t of e){let i=await le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!gk(t,i)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function wk(e,t){let i=De.resolve(e),n=De.resolve(t);if(!_c(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await Ah(i)],a=De.relative(i,n).split(De.sep).filter(Boolean),o=i;for(let s of a){await Hn(r),o=De.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ah(o);if(!_c(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Hn(r),r}async function yk(e){let t;try{t=await le.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 Nk(e,t,i={}){let n=De.dirname(e),r=i.containedRoot?await wk(i.containedRoot,n):null;r||await le.mkdir(n,{recursive:!0});let a=De.join(n,`.${De.basename(e)}.${vk()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Hn(r),!c.isFile()||c.isSymbolicLink()||!Ic(s,c)||!_c(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(),!Ic(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 Hn(r);let c=await le.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Ic(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 yk(n)}catch(c){if(await o?.close(),!r)await le.rm(a,{force:!0});else try{await Hn(r),await le.rm(a,{force:!0})}catch{}throw c}}async function ei(e,t,i={}){await Nk(e,t,i)}async function Le(e,t,i={}){await ei(e,JSON.stringify(t,null,2)+`
143
+ `,i)}var Oc=Go(_a(),1);import Oa from"path";var Dn=64*1024,$a=1024,Ha=64,$c=5,bk=[".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/**"],we={include:["**/*"],exclude:[...bk],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function kk(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Oa.posix.isAbsolute(i)||Oa.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 ti(e){let t=kk(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Th(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Hc(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||Oa.posix.isAbsolute(n)||Oa.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 Fn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ih(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 Fa(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>$a)throw new Error(`${t} exceeds ${$a} 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>Ha)throw new Error(`${t} contains more than ${Ha} wildcard tokens`);return e}function xh(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=>Fa(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function jc(e,t,i){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function Sk(e){if(e===void 0)return{...we,include:[...we.include],exclude:[...we.exclude]};let t=Fn(e,"native.snapshot");return{include:xh(t.include,"native.snapshot.include",we.include),exclude:xh(t.exclude,"native.snapshot.exclude",we.exclude),max_files:jc(t.max_files,we.max_files,"native.snapshot.max_files"),max_total_bytes:jc(t.max_total_bytes,we.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:jc(t.max_duration_ms,we.max_duration_ms,"native.snapshot.max_duration_ms")}}function Ek(e){if(e===void 0)return;let t=Fn(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=Fn(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:ti(n),toArtifactRoot:ti(r),stage:a,...o?{cleanup:o}:{}}}function Ck(e,t={}){let i=Fn(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??$c;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Ek(i.pending_root_move);return{artifact_root:ti(n),language:Ih(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:Sk(i.snapshot),...s?{pending_root_move:s}:{}}}function Rk(e){let t=Fn(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:Th(t.artifact_layout),language:Ih(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function Pk(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Ak(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 Ln(e,t={}){let i=(0,Oc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let 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=Pk(r.ambient_resume),o=r.native===void 0?void 0:Ck(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:Rk(r.classic),c=Ak(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Da(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:ti(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:$c,snapshot:{...we,include:[...we.include],exclude:[...we.exclude]}}}}import{createHash as Tk}from"crypto";import{promises as Ba}from"fs";import _t from"path";import{constants as La,promises as ii}from"fs";var Me=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function Fc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function _h(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Mn(e){return{dev:e.dev,ino:e.ino,birthtime:Fc(e)}}function Ma(e,t){let i=Mn(e),n=Mn(t);return se(i,n)?L(i,n):L(i,n)&&Fc(e)===Fc(t)&&_h(e)===_h(t)&&e.size===t.size}async function ni(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 ii.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Me("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Me("too-large",`${n} exceeds ${t} bytes`);let o=await ii.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Mn(a)});let s=process.platform==="win32"?La.O_RDONLY:La.O_RDONLY|La.O_NOFOLLOW|La.O_NONBLOCK,c;try{c=await ii.open(e,s)}catch(l){throw l.code==="ELOOP"?new Me("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),ii.lstat(e,{bigint:r}),ii.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ma(a,l)||!Ma(a,u))throw new Me("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Mn(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 Me("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([c.stat({bigint:r}),ii.lstat(e,{bigint:r}),ii.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||S!==o||!Ma(a,h)||!Ma(a,g))throw new Me("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:Mn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function xk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Dc(e,t){let i=_t.relative(e,t);return i===""||!_t.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_t.sep}`)}async function jh(e,t){let i=_t.resolve(e),n=await Ba.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ba.realpath(i)}async function Oh(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=_t.join(r,i[a]);let o;try{o=await Ba.lstat(r)}catch(u){if(xk(u))return{exists:!1,kind:"missing"};throw u}let s=_t.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 Ba.realpath(r);if(!Dc(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 Bn(e,t,i){let n=Hc(t,i.label),r=_t.resolve(e),a=await jh(r,i.label),o=n.split("/"),s=_t.resolve(r,...o);if(!Dc(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Oh(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ri(e,t,i,n){let r=await Bn(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 jh(r.projectRoot,n.label);return ni(r.target,i,{...n,verify:async(o,s)=>{if(!Dc(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Oh(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var qn=".comet/config.yaml";function Ik(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Lc(e,t={}){return(await qa(e,t)).document}async function _k(e){try{return(await ri(e,qn,Dn,{label:qn})).bytes}catch(t){if(Ik(t))return null;throw t}}function jk(e){return e?{exists:!0,sha256:Tk("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function qa(e,t={}){let i=await _k(e);return{document:i?Ln(i.toString("utf8"),t):null,identity:jk(i)}}var sI=16*1024;import{promises as _i}from"fs";import G from"path";import Dk from"os";var Wa=".comet/config.yaml";async function qc(e){try{return await _i.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Lk(e){try{let t=await _i.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Vn(e,t){let i=G.relative(e,t);return i===""||!G.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${G.sep}`)}async function Wn(e){let t=[],i=e;for(;!await qc(i);){let r=G.dirname(i);if(r===i)break;t.push(G.basename(i)),i=r}let n=await _i.realpath(i);return G.resolve(n,...t.reverse())}async function Hh(e){try{return(await _i.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function za(e){let t=G.resolve(e);try{(await _i.stat(t)).isDirectory()||(t=G.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=G.resolve(Dk.homedir());for(;;){if(!(t===n&&i!==n)){let o=G.join(t,...Wa.split("/")),s=t===i||await Lk(o);if(await qc(o)&&s)return t}if(await qc(G.join(t,".git")))return t;let a=G.dirname(t);if(a===t)return i;t=a}}function Ja(e){return ti(e)}async function Mk(e,t){let i=Ja(t),n=G.resolve(e,...i.split("/")),r=await _i.realpath(e),a=await Wn(n);if(!Vn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Vc(e,t){let i=Ja(t),n=await Mk(e,i),r=G.join(n,"comet");if(await Hh(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Wn(n),Wn(r)]);if(!Vn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:G.resolve(e),configFile:G.join(e,...Wa.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:G.join(r,"specs"),changesDir:G.join(r,"changes"),archiveDir:G.join(r,"archive"),runtimeDir:G.join(r,"runtime"),locksDir:G.join(r,"runtime","locks"),transactionsDir:G.join(r,"runtime","transactions")}}function z(e,t){return Vn(G.resolve(e),G.resolve(t))}async function $(e,t){let i=G.resolve(e),n=G.resolve(t);if(!Vn(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await Hh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([Wn(i),Wn(n)]);if(!Vn(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Wc=we;var Ga=Fa;function qk(e="docs",t="en"){return Da(e,t)}async function jt(e){let t=(await Lc(e))?.config??null;return t?.native?t:null}async function zn(e){let t=await jt(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 Fh(e){let t=await za(e.startPath),i=await jt(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${Wa} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?Ja(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??qk(n??"docs"),a=await Vc(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as vS}from"fs";import gS from"path";import{AsyncLocalStorage as Vk}from"async_hooks";import{randomUUID as Mh}from"crypto";import{promises as xe}from"fs";import Bh from"os";import fe from"path";var Dh=16*1024,qh=".coordinator",Wk=5e3,Lh=new Vk,Ua=new Map;function zk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Jk(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 Vh(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 zc(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return se(i,n)?L(i,n):L(i,n)&&e.size===t.size}function Jc(e,t){return zc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function ct(e){let t,i;try{let n=await ni(e,Dh,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Me?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Dh} 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:Jk(JSON.parse(t.toString("utf8")),e),identity:Vh(i)}}async function Gk(e){return(await ct(e))?.owner??null}function Wh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Bh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Zk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Uk(e,t){try{await xe.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xe.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Gc(e,t){let i=await ct(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Jc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xe.mkdir(t,{recursive:!0});let n=fe.join(t,`${fe.basename(e.file)}.${e.owner.id}.${Mh()}.removed`);try{await xe.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await ct(n);if(!r||r.owner.id!==e.owner.id||!zc(r.identity,e.identity))throw await Uk(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xe.rm(n,{force:!0}),"removed"}function zh(e){return{id:Mh(),pid:process.pid,hostname:Bh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Jh(e,t){let i;try{i=await xe.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await Gk(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
144
+ `,"utf8"),await i.sync(),Vh(await i.stat({bigint:!0}))}finally{await i.close()}}async function Kk(e,t){let i=await $(e.nativeRoot,e.locksDir);await xe.mkdir(i,{recursive:!0});let n=await $(e.nativeRoot,fe.join(i,qh));await xe.mkdir(n,{recursive:!0});let r=zh(t),a=fe.join(n,`.${r.id}.tmp`),o=fe.join(n,`${r.id}.claim`);try{let s=await Jh(a,r);await xe.rename(a,o);let c=await ct(o);if(!c||!zc(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 xe.rm(a,{force:!0})}}async function Yk(e){let t=fe.dirname(e.file),i=!1,n=fe.basename(e.file);for(let r of await xe.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=fe.join(t,r.name);if(fe.resolve(a)!==fe.resolve(e.file))try{let o=await ct(a),s=Wh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Gc(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Gh(e){let t=await ct(e.file);if(t){if(t.owner.id!==e.owner.id||!Jc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Gc(t,fe.dirname(e.file))}}async function Xk(e,t){let i=Date.now()+Wk;for(;;){let n=await Kk(e,t);if(!await Yk(n))return n;if(await Gh(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 Qk(e){let t=Ua.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Ua.set(e,r),await t,()=>{i(),Ua.get(e)===r&&Ua.delete(e)}}async function Uh(e,t,i){let n=fe.resolve(e.locksDir),r=Lh.getStore();if(r?.has(n))return i();let a=await Qk(n);try{let o=await Xk(e,t),s=new Map(r??[]);return s.set(n,o),await Lh.run(s,async()=>{try{return await i()}finally{await Gh(o)}})}finally{a()}}async function Jn(e,t,i){return Uh(e,`acquire ${t}`,async()=>{let n=await $(e.nativeRoot,e.locksDir);await xe.mkdir(n,{recursive:!0});let r=await $(e.nativeRoot,fe.join(n,zk(t))),a=zh(i),o=await Jh(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Gn(e){await ct(e.file)&&await Uh(e,`release ${fe.basename(e.file)}`,async()=>{let t=await ct(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Jc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=fe.join(e.locksDir,qh);await Gc(t,i)})}function Zk(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Kh(e){return Wh(await ct(e))}import lt from"path";import{TextDecoder as oS}from"util";import{createHash as eS}from"node:crypto";import{constants as Ka,promises as Se}from"node:fs";import Be from"node:path";import{TextDecoder as tS}from"node:util";function Xa(e,t){let i=Be.relative(e,t);return i===""||!Be.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Be.sep}`)}function Yh(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function iS(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nS(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ya(e,t){return L({...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 Uc(e,t){let i=await Se.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Se.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Kc(e,t,i){let n=Be.resolve(e),r=Be.resolve(t);if(!Xa(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Uc(n,i)],o=n;for(let s of Be.relative(n,r).split(Be.sep).filter(Boolean)){await et(a,i),o=Be.join(o,s);let c=await Uc(o,i);if(!Xa(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await et(a,i),a}async function et(e,t){for(let i of e){let n=await Se.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!iS(i,n)||await Se.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function rS(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 tt(e){let t=Yh(e.maxBytes),i=Be.resolve(e.file),n=await Kc(e.root,Be.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>Uc(Be.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await et(n,e.label);let a=await Se.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=nS(a),s=await Se.realpath(i);if(!Xa(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Xa(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Ka.O_RDONLY:Ka.O_RDONLY|Ka.O_NOFOLLOW|Ka.O_NONBLOCK,l=await Se.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Se.lstat(i),Se.realpath(i)]);if(await et(n,e.label),await et(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Ya(o,u)||!Ya(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await rS(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),Se.lstat(i),Se.realpath(i)]);if(await et(n,e.label),await et(r,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!Ya(o,m)||!Ya(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:eS("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Xh(e){let t=await tt(e),i;try{i=new tS("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 Un(e){let t=await Kc(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Se.readdir(e.directory,{withFileTypes:!0});else{let n=Yh(e.maxEntries);i=[];let r=await Se.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 et(t,e.label),{entries:i,verify:()=>et(t,e.label)}}async function Qa(e){let t=await Kc(e.root,e.directory,e.label);return{verify:()=>et(t,e.label)}}var sS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),cS=new Set(["id","type","source","target","staged","backup"]),lS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),uS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var ep=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var dS=256*1024,XI=1024*1024,QI=16*1024;var ZI=64*1024*1024;var fS=new oS("utf-8",{fatal:!0});function eo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function to(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 tp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Yc(e,t){if(typeof e!="string"||e.length===0||lt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Za(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Qh(e,t){if(Yc(e,t),e.includes("\\")||e!==lt.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 hS(e,t){let i=eo(e,`transaction operations[${t}]`);if(to(i,cS,`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`);Yc(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Yc(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 ip(e){let t=eo(e,"Native Archive transaction journal");if(to(t,lS,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!ep.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!tp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Za(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=eo(s,`Archive transaction operations[${c}]`);if(to(l,uS,`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`);Qh(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Qh(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Za(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(Za(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`);Za(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 pS(e){let t=eo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return ip(t);if(to(t,sS,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!ep.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!lt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!lt.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(!tp(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(hS),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 mS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return lt.join(e.transactionsDir,t)}function np(e,t){let i=mS(e,t);return{directory:i,journal:lt.join(i,"transaction.json"),events:lt.join(i,"events.jsonl"),staged:lt.join(i,"staged"),backups:lt.join(i,"backups")}}async function Xc(e,t){let i=np(e,t);return await Promise.all(Object.values(i).map(n=>$(e.nativeRoot,n))),i}async function Qc(e,t,i={}){let n=await Xc(e,t),r=await tt({root:e.nativeRoot,file:n.journal,maxBytes:dS,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(fS.decode(r.bytes)),o=pS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function wS(e,t){let i;try{i=await vS.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 Qc(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function yS(e,t){let i=Date.now()+5e3,n=gS.join(e.locksDir,"root-move.lock");for(;;)try{return await Jn(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await Kh(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 qe(e,t,i,n){let r=await yS(e,t);try{if(await zn(e.projectRoot),await wS(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Gn(r)}}function rp(e){return Number.isSafeInteger(e)&&e>=1}async function ap(e){if(!rp(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(!rp(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 oo}from"crypto";import{spawn as mp}from"node:child_process";import{promises as X}from"fs";import F from"path";import{createHash as op}from"crypto";import{createReadStream as NS}from"fs";async function Kn(e){let t=op("sha256");for await(let i of NS(e))t.update(i);return t.digest("hex")}function W(e){return op("sha256").update(e).digest("hex")}var io={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},rl=1e3,bS=8*1024*1024,kS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SS=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),ES=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),CS=new Set(["schema","include","exclude","hash"]),RS=new Set(["provider","gitSelection","physicalSelection","projection"]),PS=new Set(["provider","selection"]),AS=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),xS=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),TS=new Set(["schema","status","before","after"]),IS=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),_S=new Set(["path","hash","size","type","gitObjectId"]),jS=new Set(["path","size","type","reason"]),OS=new Set(["ref","hash","count"]),$S=new Set(["change-created","legacy-migration","explicit"]),HS=new Set(["file","directory","other"]),FS=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"]),so=/^[a-f0-9]{64}$/u,vp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,DS=new Set(["EACCES","EPERM"]),Fi=64*1024,il=64*1024,LS=6e4,MS=1e3,BS=2,al={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},qS={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function gp(e){let t=e.deadlineMs??LS;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 Ve(e){return Math.max(0,e.deadlineAt-Date.now())}function _(e){return Ve(e)>=1}function Zc(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 $i(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function VS(e){let t={...qS,...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 WS(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&&F.win32.isAbsolute(n)?F.win32.resolve(n):"C:\\Windows",a=F.win32.join(r,"System32","taskkill.exe");if(!F.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=mp(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),MS),u.unref()}catch{d(!1)}});for(let s=0;s<BS;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 ol(e,t,i,n){let r=Ve(e);if(r<1)throw Zc();let a=e.gitProcess,o=mp(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=WS(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?Zc(m.error):Zc()}return{code:p,spawnError:s}});return{child:o,completion:f}}function wp(e){let t={...al,...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 no(e,t,i,n=il){let{child:r,completion:a}=ol(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>=Fi)return;let m=Fi-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 el(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Xn(e,t,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=ol(e,t,i,n.stdin!==void 0),c=[],l=oo("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),g=!1,S=!1,N=!1,k=b=>{let C=0;for(;C<b.byteLength;){let y=b.indexOf(0,C),w=y<0?b.byteLength:y,v=b.subarray(C,w);if(!g&&v.byteLength>0&&(h.byteLength+v.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),g=!0,S=!0):h=Buffer.concat([h,v])),y<0)break;m+=1,h.byteLength===0&&!g&&(N=!0);let E=h.byteLength+1;!g&&m<=n.maxRecords&&p+E<=n.maxBytes?(c.push(h),p+=E):S=!0,h=Buffer.alloc(0),g=!1,C=y+1}};o.stdout.on("data",b=>{l.update(b),f+=b.byteLength,f>n.maxBytes&&(S=!0);let C=n.outputChunkBytes;if(C===void 0){k(b);return}for(let y=0;y<b.byteLength;y+=C)k(b.subarray(y,Math.min(b.byteLength,y+C)))}),o.stderr.on("data",b=>{if(d>=Fi)return;let C=Fi-d,y=Buffer.from(b).subarray(0,C);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:b,spawnError:C})=>{let y=n.acceptedExitCodes??[0];if(b!==null&&y.includes(b)&&C===null&&!N&&h.byteLength===0&&!g){r({records:c,digest:l.digest("hex"),overflow:S,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${C?`: ${C.message}`:N||h.byteLength>0||g?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function ro(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 zS(e,t,i){if(i.length===0)return new Set;let n=await Xn(e,t,["check-ignore","--no-index","-z","--stdin"],{...al,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=ro(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function JS(e,t,i){let{child:n,completion:r}=ol(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>=Fi)return;let d=Fi-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 Hi(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||F.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||F.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function GS(e,t){return e.map(i=>{let n=Hi(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function US(e){let t=F.resolve(e);for(;;){try{return await X.lstat(F.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=F.dirname(t);if(i===t)return!1;t=i}}async function yp(e,t,i,n={}){let r=F.resolve(t.projectRoot),a=F.join(r,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.configFile,a].map(f=>{let p=F.relative(r,F.resolve(f)).replaceAll("\\","/"),m=Hi(p);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},l=await Xn(e,r,["ls-files","--stage","-z",...s],c);await n.afterStageBefore?.();let u=await Xn(e,r,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await n.afterCombined?.();let d=await Xn(e,r,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Np(e){return{stageBefore:el(e.stagedBefore),combined:el(e.combined),stageAfter:el(e.stagedAfter)}}async function bp(e,t,i=al,n={}){let r=F.resolve(t.projectRoot);if(!await US(r))return null;let a;try{a=await no(e,r,["rev-parse","--is-inside-work-tree"])}catch(N){throw $i(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 yp(e,t,i,n)}catch(N){throw $i(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=N=>{for(let k of N){let b=ro(k),C=b.indexOf(" ");if(C<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let y=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(b.slice(0,C))?.groups;if(!y)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=Hi(b.slice(C+1));if(w===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(w),y.stage==="0"&&d.set(w,y.objectId),y.mode==="160000"&&y.stage==="0"&&f.add(w)}};p(s.records),p(l.records);let m=c.records.map(ro),h=GS(m,"combined"),g=new Set(h.filter(N=>!u.has(N))),S=new Set(h.filter((N,k)=>!u.has(N)&&m[k].endsWith("/")));for(let N of f)S.delete(N);return{tracked:u,trackedObjectIds:d,untracked:g,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:Np(o)}}function $t(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function sp(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function KS(e,t){return!$t(e.stageBefore,e.stageAfter)||!$t(e.stageAfter,t.stageBefore)||!$t(e.combined,t.combined)||!$t(t.stageBefore,t.stageAfter)}async function kp(e,t,i,n,r){let a;try{a=await yp(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw $i(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=Np(a),c=sp(o)||sp(s),l=KS(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:W(`comet.native.git-selection-overflow.v2
145
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var YS=(1n<<256n)-1n;function XS(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function cp(e){let t=F.resolve(e.paths.projectRoot),i=F.resolve(e.paths.nativeRoot),n=F.resolve(e.paths.configFile),r=F.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=()=>Ve(e.execution)>=1?!0:(f=!0,m=!0,!1),g=k=>{let b=Buffer.from(`${k.type}\0${k.path}`,"utf8"),C=oo("sha256").update("comet.native.physical-selection-record.v1\0").update(b).digest();for(let y=0;y<s.length;y+=1)s[y]^=C[y];if(c=c+BigInt(`0x${C.toString("hex")}`)&YS,u+=1,d+=b.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(k)},S=async k=>{if(m||!h())return;let b;try{b=await X.opendir(k)}catch(E){if(!h())return;if(!ne(E)&&!ie(E)||k===t&&ne(E))throw E;p||=ie(E),f||=ne(E),m=!0;return}if(!h()){try{await b.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let C=!1,y;try{for(;!m&&h();){let E;try{E=await b.read()}catch(K){if(!h())break;if(!ne(K)&&!ie(K)||k===t&&ne(K))throw K;p||=ie(K),f||=ne(K),m=!0;break}if(!h()||E===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let I=F.join(k,E.name),U=ZS(t,I);if(I===n||I===r||Ht(i,I)||e.denylist.some(K=>Ht(K,I))||Ze(U)!==null)continue;if(!h())break;let q;try{q=await X.lstat(I)}catch(K){if(!h())break;if(!ne(K)&&!ie(K))throw K;if(p=!0,g({path:U,type:"other"}),o.push({path:U,size:null,type:"file",reason:ne(K)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(U),m||!h())break;continue}if(!h())break;let J=XS(q);if(J==="directory"){if(nE(e.policy,U))continue;if(!h())break;let K;try{K=await X.realpath(I)}catch(Ke){if(!h())break;if(!ne(Ke)&&!ie(Ke))throw Ke;if(p=!0,g({path:U,type:J}),o.push({path:U,size:null,type:"directory",reason:ne(Ke)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(U),m||!h())break;continue}if(!h())break;if(!z(e.physicalProjectRoot,K)||Ht(e.physicalNativeRoot,K))continue;if(g({path:U,type:J}),await e.hooks?.afterNode?.(U),!h()||(await S(I),m))break;continue}if(g({path:U,type:J}),await e.hooks?.afterNode?.(U),!h()||m)break}}catch(E){C=!0,y=E}let w;try{await b.close()}catch(E){w=E}let v=h();if(C)throw y;if(v&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await S(t),h(),f?(a.length=0,u=0,d=0):(a.sort((k,b)=>k.path.localeCompare(b.path,"en")),o.sort((k,b)=>k.path.localeCompare(b.path,"en")));let N=f?W(`comet.native.physical-selection-incomplete.v1
146
146
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):W(`comet.native.physical-selection.v1
147
- ${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:k,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:p}}}function vp(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 Fk(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!vp(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 gp(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function ip(e,t){let n=(await Ya(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!lp.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return W(`gitlink:${n}`)}async function np(e,t){let i=await ip(e,t),n=await _k(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await ip(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function zn(e,t){if(Xe(t)!==null)return!1;let i=V.resolve(e.projectRoot,...t.split("/"));return!$t(V.resolve(e.nativeRoot),i)}function Lk(e,t){return V.relative(e,t).split(V.sep).join("/")}function Mk(e,t){return t.map(i=>V.resolve(e,...i.split(/[\\/]/u)))}function $t(e,t){let i=V.resolve(e),n=V.resolve(t);return n===i||J(i,n)}function te(e){return Ek.has(e.code??"")}function ee(e){return e.code==="ENOENT"}function Yc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
148
- `)}function Bk(e,t){return W(`comet.native.snapshot-policy.v1
149
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Vc(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 qk(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function rp(e){let t=La(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?qk(r):void 0;if(a&&!a())return!1;let o=Vc(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=Vc(i,c,a),o===null||o.size===0)return!1}return Vc(i,o,a)?.has(i.length)??!1}}function wp(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>La(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>La(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=Bk(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(rp),excludeMatchers:i.map(rp),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 Vk(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function ap(e,t,i){if(!e)return!0;let n=()=>j(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 Wn(e,t,i){let n=JSON.stringify(i);return W(`${e}
147
+ ${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 Sp(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 QS(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!Sp(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 Ep(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function lp(e,t){let n=(await no(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!vp.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return W(`gitlink:${n}`)}async function up(e,t){let i=await lp(e,t),n=await JS(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await lp(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function Yn(e,t){if(Ze(t)!==null)return!1;let i=F.resolve(e.projectRoot,...t.split("/"));return!Ht(F.resolve(e.nativeRoot),i)}function ZS(e,t){return F.relative(e,t).split(F.sep).join("/")}function eE(e,t){return t.map(i=>F.resolve(e,...i.split(/[\\/]/u)))}function Ht(e,t){let i=F.resolve(e),n=F.resolve(t);return n===i||z(i,n)}function ne(e){return DS.has(e.code??"")}function ie(e){return e.code==="ENOENT"}function sl(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
148
+ `)}function tE(e,t){return W(`comet.native.snapshot-policy.v1
149
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function tl(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 iE(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function dp(e){let t=Ga(e,"Native snapshot pattern"),i=[];for(let n=0;n<t.length;n+=1){let r=t[n];r==="*"&&t[n+1]==="*"?(n+=1,t[n+1]==="/"?(n+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):r==="*"?i.push({kind:"star"}):r==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:r})}return(n,r)=>{let a=r?iE(r):void 0;if(a&&!a())return!1;let o=tl(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=tl(i,c,a),o===null||o.size===0)return!1}return tl(i,o,a)?.has(i.length)??!1}}function Cp(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>Ga(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>Ga(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=tE(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(dp),excludeMatchers:i.map(dp),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 nE(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function fp(e,t,i){if(!e)return!0;let n=()=>_(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function Qn(e,t,i){let n=JSON.stringify(i);return W(`${e}
150
150
  ${Buffer.byteLength(t)}:${t}
151
- ${Buffer.byteLength(n)}:${n}`)}function Jc(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Qa(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Jc(i))return e.splice(t,1),i}return null}function jt(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ae(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function zk(e,t,i,n){if(!j(n))return{status:"budget-exhausted"};let r;try{r=await X.open(e,"r")}catch(c){if(!j(n))return{status:"budget-exhausted"};throw c}if(!j(n))return await r.close(),{status:"budget-exhausted"};let a=Za("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!j(n))return{status:"budget-exhausted"};let c=await r.stat();if(!j(n))return{status:"budget-exhausted"};if(!c.isFile()||!jt(i,c))return{status:"changed"};for(;;){if(!j(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(!j(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!j(n))return{status:"budget-exhausted"};let d=await r.stat();return j(n)?!d.isFile()||!jt(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 Ae(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xe(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function _i(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function tt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function yp(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=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Wk(e,t){let i=Ae(e,`Native snapshot entry ${t}`);xe(i,wk,`Native snapshot entry ${t}`);let n=yp(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!eo.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:tt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!lp.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function Jk(e,t){let i=Ae(e,`Native snapshot omission ${t}`);if(xe(i,yk,`Native snapshot omission ${t}`),!Sk.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!kk.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:yp(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:tt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function Uk(e){let t=Ae(e,"Native snapshot omission overflow");if(xe(t,Nk,"Native snapshot omission overflow"),typeof t.hash!="string"||!eo.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:_i(t.count,"Native snapshot omission overflow count")}}function Ii(e,t){let i=Ae(e,t);if(xe(i,mk,t),typeof i.hash!="string"||!eo.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=tt(i.recordCount,`${t} recordCount`),r=tt(i.storedRecordCount,`${t} storedRecordCount`),a=tt(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 op(e){let t=Ae(e,"Native Git selection evidence");if(xe(t,pk,"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=Ii(t.stageBefore,"Native Git selection stageBefore"),n=Ii(t.combined,"Native Git selection combined"),r=Ii(t.stageAfter,"Native Git selection stageAfter"),a=Ii(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Ii(t.finalCombined,"Native Git selection finalCombined"),s=Ii(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Ot(i,r)||!Ot(r,a)||!Ot(n,o)||!Ot(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 sp(e,t){let i=Ae(e,t);if(xe(i,gk,t),typeof i.hash!="string"||!eo.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=tt(i.visitedNodeCount,`${t} visitedNodeCount`),r=tt(i.recordCount,`${t} recordCount`),a=tt(i.storedRecordCount,`${t} storedRecordCount`),o=tt(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 Gk(e){let t=Ae(e,"Native physical selection evidence");if(xe(t,vk,"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=sp(t.before,"Native physical selection before"),n=sp(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!vp(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 ii(e){let t=Ae(e,"Native content snapshot manifest");if(xe(t,lk,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!bk.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=Ae(t.capture,"Native content snapshot capture");if(xe(y,fk,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let w=y.gitSelection===void 0?void 0:op(y.gitSelection),g=y.physicalSelection===void 0?void 0:Gk(y.physicalSelection),E=null;if(y.projection!==void 0){let _=Ae(y.projection,"Native content snapshot projection");if(xe(_,hk,"Native content snapshot projection"),_.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",..._.selection===void 0?{}:{selection:op(_.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=Ae(t.limits,"Native content snapshot limits");xe(n,uk,"Native content snapshot limits");let r={maxFiles:_i(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:_i(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:_i(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:_i(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:_i(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=Ae(t.policy,"Native snapshot policy");if(xe(y,dk,"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=wp({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(Wk),s=t.omitted.map(Jk),c=tt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:Uk(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>Uc||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"),N=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...v,...N])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||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let k=i?.physicalSelection,S=k?.status==="overflow"||k?.status==="overflow-and-changed",b=k?.status==="changed"||k?.status==="overflow-and-changed";if(S!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(N.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let C={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Yc(C)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return C}async function Np(e,t,i={}){let n=ii(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=V.resolve(e.projectRoot),a=up(i),o=dp(i.gitSelectionLimits),s=await pp(a,r,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(gp(s).filter(g=>zn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>zn(e,g)),d=(g,E)=>E.some(_=>g===_||g.startsWith(`${_}/`)),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 Ik(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!p(g.path)&&zn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await mp(a,r,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let g of l)N.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,E)=>g.path.localeCompare(E.path,"en"));let k=n.omitted.filter(g=>f(g.path)||p(g.path)||!zn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(E=>E.startsWith(`${g.path}/`)):!0);for(let g of N)k.some(E=>E.path===g.path&&E.reason===g.reason)||k.push(g);k.sort((g,E)=>g.path.localeCompare(E.path,"en"));let S=n.omissionOverflow?.count??0,b=n.omissionOverflow?.hash??W("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,b=Wn(b,"git-selection",{source:"git-selection",...s.overflow}));let C=g=>{S+=1,b=Wn(b,"omission",g)};for(;k.length>Uc;){let g=Qa(k);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");C(g)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:k.length+S===0,entries:v,omitted:k,omittedCount:k.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:S}}:{}}),w=y();for(;Yc(w)>n.limits.maxManifestBytes;){let g=Qa(k);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");C(g),w=y()}return ii(w)}function Kk(e,t){if(!ck.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=V.join(e.changesDir,t);if(!J(e.changesDir,i))throw new Error("Native change path escaped");return V.join(i,"runtime","baseline-manifest.json")}async function bp(e,t={}){let i={maxFiles:t.limits?.maxFiles??Ga.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Ga.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Ga.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Ga.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=wp(t.policy),r=up({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=dp(t.gitSelectionLimits),o=xk(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=V.resolve(e.projectRoot),c=await X.realpath(s),l=V.resolve(e.nativeRoot),u=await X.realpath(l),d=V.resolve(e.configFile),f=V.join(s,".comet","current-change.json"),p=Mk(s,t.denylist??[]),m=[],h=[],v=new Map,N=new Map,k=0,S=0,b=W("comet.native.snapshot-omission-overflow.v1"),C=0,y=!1,w=null,g=P=>{S+=1,b=Wn(b,"omission",P)},E=P=>{if(k+=1,h.length<Uc){h.push(P);return}if(Jc(P)){let A=Qa(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),h.push(P);return}g(P)},_=P=>{k+=P.count,S+=P.count,b=Wn(b,"git-selection",{source:"git-selection",...P})},K=P=>{S+=1,b=Wn(b,"manifest-entry",{reason:"manifest-size",entry:P})},q=async(P,A)=>{m.push(P),C+=P.size,v.set(P.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(P.path))},U=(P,A)=>{let T=m.findIndex(Q=>Q.path===P);if(T<0)return;let[D]=m.splice(T,1);C-=D.size,v.delete(P),E(A)},Y=async(P,A,T,D)=>{if(!T.isFile()||T.isSymbolicLink()||!j(r))return;let Q;try{Q=await X.realpath(P)}catch(I){if(!j(r))return;if(!te(I)&&!ee(I))throw I;E({path:A,size:T.size,type:"file",reason:ee(I)?"changed-during-read":"unreadable"});return}if(!j(r)||!J(c,Q)||$t(u,Q))return;if(m.length>=i.maxFiles){E({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){E({path:A,size:T.size,type:"file",reason:"file-size"});return}if(C+T.size>i.maxTotalBytes){E({path:A,size:T.size,type:"file",reason:"total-size"});return}let B,O,x;try{if(B=await zk(Q,T.size,T,r),B.status==="budget-exhausted"||!j(r))return;if(B.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!j(r)||(x=await X.realpath(P),!j(r)))return;O=await X.lstat(P)}catch(I){if(!j(r))return;if(!te(I)&&!ee(I))throw I;E({path:A,size:T.size,type:"file",reason:ee(I)?"changed-during-read":"unreadable"});return}if(j(r)){if(B.bytes!==T.size||x!==Q||!jt(T,B.finalStat)||!jt(B.finalStat,O)||!O.isFile()||O.isSymbolicLink()||O.size!==T.size||O.mtimeMs!==T.mtimeMs||O.ctimeMs!==T.ctimeMs){E({path:A,size:O.isFile()?O.size:null,type:O.isFile()?"file":"other",reason:"changed-during-read"});return}j(r)&&await q({path:A,hash:B.hash,size:O.size,type:"file",...D===void 0?{}:{gitObjectId:D}},{kind:"file",target:P,realTarget:Q,stat:O})}},Ue=async(P,A,T)=>{if(!j(r))return;let D,Q,B;try{if(D=await X.readlink(P,{encoding:"buffer"}),!j(r)||(B=await X.lstat(P),!j(r)))return;Q=await X.readlink(P,{encoding:"buffer"})}catch(I){if(!j(r))return;if(!te(I)&&!ee(I))throw I;E({path:A,size:null,type:"other",reason:ee(I)?"changed-during-read":"unreadable"});return}if(!j(r))return;if(!B.isSymbolicLink()||!jt(T,B)||B.mtimeMs!==T.mtimeMs||B.ctimeMs!==T.ctimeMs||!D.equals(Q)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let O=D.byteLength;if(m.length>=i.maxFiles){E({path:A,size:O,type:"other",reason:"file-count"});return}if(O>i.maxFileBytes){E({path:A,size:O,type:"other",reason:"file-size"});return}if(C+O>i.maxTotalBytes){E({path:A,size:O,type:"other",reason:"total-size"});return}let x=Za("sha256").update("symlink\0").update(D).digest("hex");j(r)&&await q({path:A,hash:x,size:O,type:"file"},{kind:"symlink",target:P,rawTarget:D,stat:B})},Ge=async()=>{for(let[P,A]of[...v]){if(!j(r))return;if(A.kind==="file"){let O,x;try{if(O=await X.realpath(A.target),!j(r))return;x=await X.lstat(A.target)}catch(I){if(!j(r))return;if(!te(I)&&!ee(I))throw I;U(P,{path:P,size:null,type:"file",reason:te(I)?"unreadable":"changed-during-read"});continue}if(!j(r))return;(O!==A.realTarget||!x.isFile()||x.isSymbolicLink()||!jt(A.stat,x)||x.size!==A.stat.size||x.mtimeMs!==A.stat.mtimeMs||x.ctimeMs!==A.stat.ctimeMs)&&U(P,{path:P,size:x.isFile()?x.size:null,type:x.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let O,x;try{if(O=await X.lstat(A.target),!j(r))return;x=await X.readlink(A.target,{encoding:"buffer"})}catch(I){if(!j(r))return;if(!te(I)&&!ee(I))throw I;U(P,{path:P,size:null,type:"other",reason:te(I)?"unreadable":"changed-during-read"});continue}if(!j(r))return;(!O.isSymbolicLink()||!jt(A.stat,O)||O.mtimeMs!==A.stat.mtimeMs||O.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&U(P,{path:P,size:null,type:"other",reason:"changed-during-read"});continue}let T,D;try{if(T=await X.realpath(A.target),!j(r))return;D=await X.lstat(A.target)}catch{if(!j(r))return;U(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(r))return;if(!(T===A.realTarget&&D.isDirectory()&&!D.isSymbolicLink()&&jt(A.stat,D)&&J(c,T)&&!$t(u,T))){U(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"});continue}let B;try{if(!j(r))return;B=await np(r,T)}catch(O){if(Jn(O))throw O;U(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(r))return;B.dirty?U(P,{path:P,size:null,type:"directory",reason:"gitlink-dirty"}):B.hash!==A.hash&&U(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"})}for(let[P,A]of N){if(!j(r))return;try{let T=await X.lstat(A);if(!j(r))return;E({path:P,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!j(r))return;if(ee(T))continue;if(!te(T))throw T;E({path:P,size:null,type:"file",reason:"unreadable"})}}},we=await pp(r,s,a,t.gitSelectionHooks);if(we===null){let P=await tp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let D of P.records){if(D.type!=="file"&&D.type!=="symlink"||v.has(D.path))continue;if(Be(r)<1)break;if(!ap(n,D.path,r))continue;if(Be(r)<1)break;let Q=V.resolve(s,...D.path.split("/")),B;try{B=await X.lstat(Q)}catch(O){if(!j(r))break;if(!te(O)&&!ee(O))throw O;E({path:D.path,size:null,type:"file",reason:ee(O)?"changed-during-read":"unreadable"});continue}if(Be(r)<1)break;if(D.type==="symlink"&&B.isSymbolicLink()){if(await Ue(Q,D.path,B),Be(r)<1)break;continue}if(D.type!=="file"||!B.isFile()||B.isSymbolicLink()){E({path:D.path,size:B.isFile()?B.size:null,type:B.isDirectory()?"directory":B.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Y(Q,D.path,B),Be(r)<1)break}Be(r)>=1&&await Ge();let A=await tp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=Fk(P.evidence,A.evidence);w=T.evidence;for(let D of[...P.omissions,...A.omissions,...T.omissions])h.some(Q=>Q.path===D.path&&Q.reason===D.reason)||E(D)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let P=t.incrementalBaseline,A=new Map,T=!1;if(P){let x=ii(P);for(let I of x.entries)I.gitObjectId!==void 0&&A.set(I.path,I);T=A.size>0}let D=new Set,Q=!0;try{let x=await Ya(r,s,["ls-files","--modified","-z"],zc);for(let I of x.toString("utf8").split("\0")){let ne=Xa(I);ne!==null&&D.add(ne)}}catch{T=!1,Q=!1,A.clear()}let B=new Set,O=new Set;for(let x of gp(we)){if(v.has(x)||!zn(e,x))continue;if(Be(r)<1)break;if(!ap(n,x,r))continue;if(Be(r)<1)break;let I=V.resolve(s,...x.split("/"));if(I===d||I===f||p.some(Ne=>$t(Ne,I)))continue;if(we.gitlinks.has(x)){if(m.length>=i.maxFiles){E({path:x,size:0,type:"file",reason:"file-count"});continue}let Ne,Cr;try{[Ne,Cr]=await Promise.all([X.realpath(I),X.lstat(I)])}catch{E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Cr.isSymbolicLink()||!Cr.isDirectory()||!J(c,Ne)||$t(u,Ne)){E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let gi=await np(r,Ne);if(gi.dirty){E({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await q({path:x,hash:gi.hash,size:0,type:"file"},{kind:"gitlink",target:I,realTarget:Ne,stat:Cr,hash:gi.hash})}catch(gi){if(Jn(gi))throw gi;E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ne;try{ne=await X.lstat(I)}catch(Ne){if(ee(Ne)&&we.tracked.has(x)){N.set(x,I);continue}if(!te(Ne)&&!ee(Ne))throw Ne;E({path:x,size:null,type:"file",reason:ee(Ne)?"changed-during-read":"unreadable"});continue}if(ne.isSymbolicLink()){await Ue(I,x,ne);continue}if(!ne.isFile()){we.nestedRepositories.has(x)||E({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let je=we.trackedObjectIds.get(x),ye=je?A.get(x):void 0;if(T&&ye?.gitObjectId!==void 0&&ye.gitObjectId===je&&!D.has(x)){if(m.length>=i.maxFiles){E({path:x,size:ye.size,type:"file",reason:"file-count"});continue}if(ye.size>i.maxFileBytes){E({path:x,size:ye.size,type:"file",reason:"file-size"});continue}if(C+ye.size>i.maxTotalBytes){E({path:x,size:ye.size,type:"file",reason:"total-size"});continue}m.push({...ye}),C+=ye.size,B.add(x);continue}let Cu=Q&&!D.has(x)?je:void 0;await Y(I,x,ne,Cu),Cu!==void 0&&O.add(x)}if(await Ge(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await mp(r,s,a,we,t.gitSelectionHooks?.outputChunkBytes),B.size>0||T&&O.size>0){let x=await Ya(r,s,["ls-files","--modified","-z"],zc),I=new Set;for(let ne of x.toString("utf8").split("\0")){let je=Xa(ne);je!==null&&I.add(je)}for(let ne of B){if(!I.has(ne))continue;let je=m.find(ye=>ye.path===ne);U(ne,{path:ne,size:je?.size??null,type:"file",reason:"changed-during-read"})}for(let ne of O){if(!I.has(ne))continue;let je=m.find(ye=>ye.path===ne);je&&delete je.gitObjectId}}for(let x of we.omissions)E(x);we.overflow&&_(we.overflow)}m.sort((P,A)=>P.path.localeCompare(A.path,"en")),h.sort((P,A)=>P.path.localeCompare(A.path,"en"));let pg=we===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...we.evidence?{gitSelection:we.evidence}:{}},Eu=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:pg,createdAt:(t.now??new Date).toISOString(),complete:k===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:k,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:S}}:{}}),Oo=Eu();for(;Yc(Oo)>i.maxManifestBytes;){if(h.filter(A=>!Jc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let D=Qa(h);if(D===null)break;g(D)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))k+=1,K(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Oo=Eu()}return Oo}async function Xc(e,t,i={}){let r=(await _t(e.projectRoot))?.native.snapshot??_c;return bp(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 to(e,t){let i=Kk(e,t);await H(e.nativeRoot,i);try{let n=await zh({root:e.nativeRoot,file:i,maxBytes:sk,label:"Native baseline snapshot manifest"});return ii(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as dE}from"crypto";import nl from"path";var Te=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as no,promises as ue}from"node:fs";import Se from"node:path";import{TextDecoder as oE}from"node:util";import iE from"path";var Sp=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Gn(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Un(e,t){let i=Gn(e,t);if(iE.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 nE(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 kp(e){if(!e.run_id)return null;let t=Gn(e,"run_id"),i=Gn(e,"skill"),n=Gn(e,"skill_version"),r=Gn(e,"skill_hash"),a=Un(e,"pending_ref"),o=Un(e,"trajectory_ref"),s=Un(e,"context_ref"),c=Un(e,"artifacts_ref"),l=Un(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:n,skillHash:r,orchestration:e.orchestration,currentStep:Sp(e,"current_step"),iteration:u,pending:Sp(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:nE(e)}}var Q_=256*1024;var rE=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function aE(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=kp(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function io(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=>!rE.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 aE(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 Yn(e,t){let i=Se.relative(e,t);return i===""||!Se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Se.sep}`)}function Cp(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Kn(e,t){return L({...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 sE(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ni(e,t,i){let n=Te[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Se.resolve(e),a=Se.resolve(r,...n.split("/"));if(!Yn(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Ep(e){let t=await ue.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await ue.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Qc(e,t){let i=Se.resolve(e),n=Se.resolve(t);if(!Yn(i,n))throw new Error("Native Run path is outside its change");let r=[await Ep(i)],a=i;for(let o of Se.relative(i,n).split(Se.sep).filter(Boolean)){a=Se.join(a,o);let s;try{s=await Ep(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Yn(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function ro(e){for(let t of e){let i=await ue.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!sE(t,i)||await ue.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function cE(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 Oi(e,t,i,n,r){let a=await Qc(e,Se.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await ue.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=Cp(o),c=await ue.realpath(t);if(!Yn(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?no.O_RDONLY:no.O_RDONLY|no.O_NOFOLLOW|no.O_NONBLOCK,u;try{u=await ue.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),ue.lstat(t),ue.realpath(t)]);if(await ro(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Kn(s,d)||!Kn(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await cE(u,i,n);await r?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([u.stat(),ue.lstat(t),ue.realpath(t)]);if(await ro(a),!v.isFile()||v.isSymbolicLink()||N!==c||!Kn(s,h)||!Kn(s,v))throw new Error(`${n} changed while reading`);let k;try{k=new oE("utf-8",{fatal:!0}).decode(m)}catch(S){throw new Error(`${n} is not valid UTF-8`,{cause:S})}return{text:k,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function lE(e,t,i){let n=await Qc(e,Se.dirname(t));if(!n)return{exists:!1};let r;try{r=await ue.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 ue.realpath(t);if(!Yn(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await ro(n),{exists:!0,identity:Cp(r),realPath:a}}async function uE(e,t,i,n){let r=await Qc(e,Se.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await ue.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()||!Kn(i.identity,a)||await ue.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await ro(r)}async function Zc(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await lE(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Qt(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await uE(e.changeDir,e.file,i,e.label)}});let n=await Oi(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 Rp(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Pp(e){return`${JSON.stringify(e,null,2)}
152
- `}function el(e){return io(e)}async function qe(e,t){let i=ni(e,"stateRef"),n=await Oi(e,i,ve.runStateBytes,"Native Run state",t);return n?io(Rp(n.text,"Native Run state")):null}async function tl(e,t,i){let n=io(t);await Zc({changeDir:e,file:ni(e,"stateRef"),content:Pp(n),maxBytes:ve.runStateBytes,label:"Native Run state",hooks:i})}async function it(e,t,i){let n=ni(e,"trajectoryRef",t),r=await Oi(e,n,ve.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>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 Ap(e,t,i){return(await Oi(e,ni(e,"trajectoryRef",t),ve.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function xp(e,t,i,n){let r=ni(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
153
- `;if(Buffer.byteLength(a,"utf8")>ve.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${ve.trajectoryEventBytes} bytes`);let o=await Oi(e,r,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 Zc({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:ve.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function ao(e,t,i){let n=await Oi(e,ni(e,"checkpointRef",t),ve.checkpointBytes,"Native Run checkpoint",i);return n?Rp(n.text,"Native Run checkpoint"):null}async function Tp(e,t,i,n){await Zc({changeDir:e,file:ni(e,"checkpointRef",t),content:Pp(i),maxBytes:ve.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var fE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rl=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 il(e){return dE("sha256").update(e).digest("hex")}function hE(e,t){if(!fE.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=nl.join(e.changesDir,t);if(!J(e.changesDir,i))throw new Error("Native change path escaped");return nl.join(i,"runtime","trajectory.jsonl")}function pE(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 mE(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 vE(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=pE(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(`
154
- `)])}catch(d){if(!mE(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:il(t),targetHash:il(l),tailHash:il(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function gE(e,t){let i=hE(e,t);await H(e.nativeRoot,i);let n=nl.join(e.changesDir,t),r=await Ap(n,Te.trajectoryRef);return r===null?{status:"clean",file:i}:vE(i,Buffer.from(r))}async function al(e,t){let i=await gE(e,t);return"inspection"in i?i.inspection:i}async function Xn(e,t){let i=await al(e,t);if(i.status!=="clean")throw new rl(i)}import{createHash as wE}from"node:crypto";import{promises as oo}from"node:fs";import Ht from"node:path";var Qn=/^[a-f0-9]{64}$/u,yE=16*1024,NE=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function $i(e){return NE.has(e)}function jp(e,t){let i=Ht.relative(e,t);return Ht.isAbsolute(i)||i===".."||i.startsWith(`..${Ht.sep}`)?null:i.replaceAll("\\","/")||"."}function bE(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Op(e,t){if(e.length===0||bE(e)||e.includes("\\")||Ht.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=Ht.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function ol(e,t){return wE("sha256").update(`${e}
155
- ${t}`).digest("hex")}async function Ip(e,t){let i=await oo.realpath(t),n=await oo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?Ht.normalize(i).toLowerCase():i;return ol(e,`${r}
151
+ ${Buffer.byteLength(n)}:${n}`)}function nl(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ao(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!nl(i))return e.splice(t,1),i}return null}function Ot(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function rE(e,t,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await X.open(e,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=oo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!_(n))return{status:"budget-exhausted"};let c=await r.stat();if(!_(n))return{status:"budget-exhausted"};if(!c.isFile()||!Ot(i,c))return{status:"changed"};for(;;){if(!_(n))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!_(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!_(n))return{status:"budget-exhausted"};let d=await r.stat();return _(n)?!d.isFile()||!Ot(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 Te(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ie(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Oi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function it(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Rp(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=F.posix.normalize(e);if(i!==e||F.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function aE(e,t){let i=Te(e,`Native snapshot entry ${t}`);Ie(i,_S,`Native snapshot entry ${t}`);let n=Rp(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!so.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:it(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!vp.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function oE(e,t){let i=Te(e,`Native snapshot omission ${t}`);if(Ie(i,jS,`Native snapshot omission ${t}`),!HS.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!FS.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Rp(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:it(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function sE(e){let t=Te(e,"Native snapshot omission overflow");if(Ie(t,OS,"Native snapshot omission overflow"),typeof t.hash!="string"||!so.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:Oi(t.count,"Native snapshot omission overflow count")}}function ji(e,t){let i=Te(e,t);if(Ie(i,xS,t),typeof i.hash!="string"||!so.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=it(i.recordCount,`${t} recordCount`),r=it(i.storedRecordCount,`${t} storedRecordCount`),a=it(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 hp(e){let t=Te(e,"Native Git selection evidence");if(Ie(t,AS,"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=ji(t.stageBefore,"Native Git selection stageBefore"),n=ji(t.combined,"Native Git selection combined"),r=ji(t.stageAfter,"Native Git selection stageAfter"),a=ji(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ji(t.finalCombined,"Native Git selection finalCombined"),s=ji(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!$t(i,r)||!$t(r,a)||!$t(n,o)||!$t(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 pp(e,t){let i=Te(e,t);if(Ie(i,IS,t),typeof i.hash!="string"||!so.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=it(i.visitedNodeCount,`${t} visitedNodeCount`),r=it(i.recordCount,`${t} recordCount`),a=it(i.storedRecordCount,`${t} storedRecordCount`),o=it(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 cE(e){let t=Te(e,"Native physical selection evidence");if(Ie(t,TS,"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=pp(t.before,"Native physical selection before"),n=pp(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Sp(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 ai(e){let t=Te(e,"Native content snapshot manifest");if(Ie(t,SS,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!$S.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=Te(t.capture,"Native content snapshot capture");if(Ie(y,RS,"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:hp(y.gitSelection),v=y.physicalSelection===void 0?void 0:cE(y.physicalSelection),E=null;if(y.projection!==void 0){let I=Te(y.projection,"Native content snapshot projection");if(Ie(I,PS,"Native content snapshot projection"),I.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...I.selection===void 0?{}:{selection:hp(I.selection)}}}if(y.provider==="git"){if(v||E)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...w?{gitSelection:w}:{}}}else{if(w)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(v&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...v?{physicalSelection:v}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Te(t.limits,"Native content snapshot limits");Ie(n,ES,"Native content snapshot limits");let r={maxFiles:Oi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Oi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Oi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Oi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Oi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=Te(t.policy,"Native snapshot policy");if(Ie(y,CS,"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=Cp({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(aE),s=t.omitted.map(oE),c=it(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:sE(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>rl||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let g=s.filter(y=>y.reason==="physical-enumeration-limit"),S=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...g,...S])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,k=N?.status==="overflow"||N?.status==="overflow-and-changed",b=N?.status==="changed"||N?.status==="overflow-and-changed";if(k!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let C={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(sl(C)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return C}async function Pp(e,t,i={}){let n=ai(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=F.resolve(e.projectRoot),a=gp(i),o=wp(i.gitSelectionLimits),s=await bp(a,e,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(Ep(s).filter(v=>Yn(e,v))),l=[...s.gitlinks].filter(v=>c.has(v)),u=[...s.nestedRepositories].filter(v=>Yn(e,v)),d=(v,E)=>E.some(I=>v===I||v.startsWith(`${I}/`)),f=v=>d(v,l),p=v=>d(v,u),m=[...n.entries.map(v=>v.path),...n.omitted.flatMap(v=>v.type==="directory"?[v.path,`${v.path}/`]:[v.path])].filter(v=>!c.has(v)&&!f(v)&&!p(v)),h=await zS(a,r,m),g=n.entries.filter(v=>!f(v.path)&&!p(v.path)&&Yn(e,v.path)&&(c.has(v.path)||!h.has(v.path)));await kp(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let v of l)S.push({path:v,size:null,type:"directory",reason:"legacy-gitlink-boundary"});g.sort((v,E)=>v.path.localeCompare(E.path,"en"));let N=n.omitted.filter(v=>f(v.path)||p(v.path)||!Yn(e,v.path)?!1:h.has(v.path)?c.has(v.path)||[...c].some(E=>E.startsWith(`${v.path}/`)):!0);for(let v of S)N.some(E=>E.path===v.path&&E.reason===v.reason)||N.push(v);N.sort((v,E)=>v.path.localeCompare(E.path,"en"));let k=n.omissionOverflow?.count??0,b=n.omissionOverflow?.hash??W("comet.native.snapshot-omission-overflow.v1");s.overflow&&(k+=s.overflow.count,b=Qn(b,"git-selection",{source:"git-selection",...s.overflow}));let C=v=>{k+=1,b=Qn(b,"omission",v)};for(;N.length>rl;){let v=ao(N);if(v===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");C(v)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:N.length+k===0,entries:g,omitted:N,omittedCount:N.length+k,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:k}}:{}}),w=y();for(;sl(w)>n.limits.maxManifestBytes;){let v=ao(N);if(v===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");C(v),w=y()}return ai(w)}function lE(e,t){if(!kS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=F.join(e.changesDir,t);if(!z(e.changesDir,i))throw new Error("Native change path escaped");return F.join(i,"runtime","baseline-manifest.json")}async function Ap(e,t={}){let i={maxFiles:t.limits?.maxFiles??io.maxFiles,maxFileBytes:t.limits?.maxFileBytes??io.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??io.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??io.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=Cp(t.policy),r=gp({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=wp(t.gitSelectionLimits),o=VS(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=F.resolve(e.projectRoot),c=await X.realpath(s),l=F.resolve(e.nativeRoot),u=await X.realpath(l),d=F.resolve(e.configFile),f=F.join(s,".comet","current-change.json"),p=eE(s,t.denylist??[]),m=[],h=[],g=new Map,S=new Map,N=0,k=0,b=W("comet.native.snapshot-omission-overflow.v1"),C=0,y=!1,w=null,v=x=>{k+=1,b=Qn(b,"omission",x)},E=x=>{if(N+=1,h.length<rl){h.push(x);return}if(nl(x)){let A=ao(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");v(A),h.push(x);return}v(x)},I=x=>{N+=x.count,k+=x.count,b=Qn(b,"git-selection",{source:"git-selection",...x})},U=x=>{k+=1,b=Qn(b,"manifest-entry",{reason:"manifest-size",entry:x})},q=async(x,A)=>{m.push(x),C+=x.size,g.set(x.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(x.path))},J=(x,A)=>{let T=m.findIndex(Y=>Y.path===x);if(T<0)return;let[H]=m.splice(T,1);C-=H.size,g.delete(x),E(A)},K=async(x,A,T,H)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let Y;try{Y=await X.realpath(x)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:T.size,type:"file",reason:ie(P)?"changed-during-read":"unreadable"});return}if(!_(r)||!z(c,Y)||Ht(u,Y))return;if(m.length>=i.maxFiles){E({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){E({path:A,size:T.size,type:"file",reason:"file-size"});return}if(C+T.size>i.maxTotalBytes){E({path:A,size:T.size,type:"file",reason:"total-size"});return}let B,j,Q;try{if(B=await rE(Y,T.size,T,r),B.status==="budget-exhausted"||!_(r))return;if(B.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(Q=await X.realpath(x),!_(r)))return;j=await X.lstat(x)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:T.size,type:"file",reason:ie(P)?"changed-during-read":"unreadable"});return}if(_(r)){if(B.bytes!==T.size||Q!==Y||!Ot(T,B.finalStat)||!Ot(B.finalStat,j)||!j.isFile()||j.isSymbolicLink()||j.size!==T.size||j.mtimeMs!==T.mtimeMs||j.ctimeMs!==T.ctimeMs){E({path:A,size:j.isFile()?j.size:null,type:j.isFile()?"file":"other",reason:"changed-during-read"});return}_(r)&&await q({path:A,hash:B.hash,size:j.size,type:"file",...H===void 0?{}:{gitObjectId:H}},{kind:"file",target:x,realTarget:Y,stat:j})}},Ke=async(x,A,T)=>{if(!_(r))return;let H,Y,B;try{if(H=await X.readlink(x,{encoding:"buffer"}),!_(r)||(B=await X.lstat(x),!_(r)))return;Y=await X.readlink(x,{encoding:"buffer"})}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;E({path:A,size:null,type:"other",reason:ie(P)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!B.isSymbolicLink()||!Ot(T,B)||B.mtimeMs!==T.mtimeMs||B.ctimeMs!==T.ctimeMs||!H.equals(Y)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=H.byteLength;if(m.length>=i.maxFiles){E({path:A,size:j,type:"other",reason:"file-count"});return}if(j>i.maxFileBytes){E({path:A,size:j,type:"other",reason:"file-size"});return}if(C+j>i.maxTotalBytes){E({path:A,size:j,type:"other",reason:"total-size"});return}let Q=oo("sha256").update("symlink\0").update(H).digest("hex");_(r)&&await q({path:A,hash:Q,size:j,type:"file"},{kind:"symlink",target:x,rawTarget:H,stat:B})},Ye=async()=>{for(let[x,A]of[...g]){if(!_(r))return;if(A.kind==="file"){let j,Q;try{if(j=await X.realpath(A.target),!_(r))return;Q=await X.lstat(A.target)}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;J(x,{path:x,size:null,type:"file",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(j!==A.realTarget||!Q.isFile()||Q.isSymbolicLink()||!Ot(A.stat,Q)||Q.size!==A.stat.size||Q.mtimeMs!==A.stat.mtimeMs||Q.ctimeMs!==A.stat.ctimeMs)&&J(x,{path:x,size:Q.isFile()?Q.size:null,type:Q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let j,Q;try{if(j=await X.lstat(A.target),!_(r))return;Q=await X.readlink(A.target,{encoding:"buffer"})}catch(P){if(!_(r))return;if(!ne(P)&&!ie(P))throw P;J(x,{path:x,size:null,type:"other",reason:ne(P)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!Ot(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Q))&&J(x,{path:x,size:null,type:"other",reason:"changed-during-read"});continue}let T,H;try{if(T=await X.realpath(A.target),!_(r))return;H=await X.lstat(A.target)}catch{if(!_(r))return;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&H.isDirectory()&&!H.isSymbolicLink()&&Ot(A.stat,H)&&z(c,T)&&!Ht(u,T))){J(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"});continue}let B;try{if(!_(r))return;B=await up(r,T)}catch(j){if($i(j))throw j;J(x,{path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;B.dirty?J(x,{path:x,size:null,type:"directory",reason:"gitlink-dirty"}):B.hash!==A.hash&&J(x,{path:x,size:null,type:"directory",reason:"gitlink-changed"})}for(let[x,A]of S){if(!_(r))return;try{let T=await X.lstat(A);if(!_(r))return;E({path:x,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!_(r))return;if(ie(T))continue;if(!ne(T))throw T;E({path:x,size:null,type:"file",reason:"unreadable"})}}},be=await bp(r,e,a,t.gitSelectionHooks);if(be===null){let x=await cp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let H of x.records){if(H.type!=="file"&&H.type!=="symlink"||g.has(H.path))continue;if(Ve(r)<1)break;if(!fp(n,H.path,r))continue;if(Ve(r)<1)break;let Y=F.resolve(s,...H.path.split("/")),B;try{B=await X.lstat(Y)}catch(j){if(!_(r))break;if(!ne(j)&&!ie(j))throw j;E({path:H.path,size:null,type:"file",reason:ie(j)?"changed-during-read":"unreadable"});continue}if(Ve(r)<1)break;if(H.type==="symlink"&&B.isSymbolicLink()){if(await Ke(Y,H.path,B),Ve(r)<1)break;continue}if(H.type!=="file"||!B.isFile()||B.isSymbolicLink()){E({path:H.path,size:B.isFile()?B.size:null,type:B.isDirectory()?"directory":B.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await K(Y,H.path,B),Ve(r)<1)break}Ve(r)>=1&&await Ye();let A=await cp({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=QS(x.evidence,A.evidence);w=T.evidence;for(let H of[...x.omissions,...A.omissions,...T.omissions])h.some(Y=>Y.path===H.path&&Y.reason===H.reason)||E(H)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let x=t.incrementalBaseline,A=new Map,T=!1;if(x){let P=ai(x);for(let Z of P.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);T=A.size>0}let H=new Set,Y=!0;try{let P=await Xn(r,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(P.overflow)T=!1,Y=!1,A.clear();else for(let Z of P.records){let ee=ro(Z),de=ee.indexOf(" "),oe=de<0?null:Hi(ee.slice(de+1));if(de!==1||oe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&H.add(oe)}}catch(P){if($i(P))throw P;T=!1,Y=!1,A.clear()}let B=new Set;try{let P=await no(r,s,["ls-files","--modified","-z"],il);for(let Z of P.toString("utf8").split("\0")){let ee=Hi(Z);ee!==null&&B.add(ee)}}catch{T=!1,Y=!1,A.clear()}let j=new Set,Q=new Set;for(let P of Ep(be)){if(g.has(P)||!Yn(e,P))continue;if(Ve(r)<1)break;if(!fp(n,P,r))continue;if(Ve(r)<1)break;let Z=F.resolve(s,...P.split("/"));if(Z===d||Z===f||p.some(ke=>Ht(ke,Z)))continue;if(be.gitlinks.has(P)){if(m.length>=i.maxFiles){E({path:P,size:0,type:"file",reason:"file-count"});continue}let ke,_r;try{[ke,_r]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(_r.isSymbolicLink()||!_r.isDirectory()||!z(c,ke)||Ht(u,ke)){E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ni=await up(r,ke);if(Ni.dirty){E({path:P,size:null,type:"directory",reason:"gitlink-dirty"});continue}await q({path:P,hash:Ni.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:ke,stat:_r,hash:Ni.hash})}catch(Ni){if($i(Ni))throw Ni;E({path:P,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await X.lstat(Z)}catch(ke){if(ie(ke)&&be.tracked.has(P)){S.set(P,Z);continue}if(!ne(ke)&&!ie(ke))throw ke;E({path:P,size:null,type:"file",reason:ie(ke)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await Ke(Z,P,ee);continue}if(!ee.isFile()){be.nestedRepositories.has(P)||E({path:P,size:null,type:"other",reason:"changed-during-read"});continue}let de=be.trackedObjectIds.get(P),oe=de?A.get(P):void 0;if(T&&oe?.gitObjectId!==void 0&&oe.gitObjectId===de&&!H.has(P)&&!B.has(P)){if(m.length>=i.maxFiles){E({path:P,size:oe.size,type:"file",reason:"file-count"});continue}if(oe.size>i.maxFileBytes){E({path:P,size:oe.size,type:"file",reason:"file-size"});continue}if(C+oe.size>i.maxTotalBytes){E({path:P,size:oe.size,type:"file",reason:"total-size"});continue}m.push({...oe}),C+=oe.size,j.add(P);continue}let $u=Y&&!H.has(P)&&!B.has(P)?de:void 0;await K(Z,P,ee,$u),$u!==void 0&&Q.add(P)}if(await Ye(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await kp(r,e,a,be,t.gitSelectionHooks?.outputChunkBytes),j.size>0||T&&Q.size>0){let P=await no(r,s,["ls-files","--modified","-z"],il),Z=new Set;for(let ee of P.toString("utf8").split("\0")){let de=Hi(ee);de!==null&&Z.add(de)}for(let ee of j){if(!Z.has(ee))continue;let de=m.find(oe=>oe.path===ee);J(ee,{path:ee,size:de?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Q){if(!Z.has(ee))continue;let de=m.find(oe=>oe.path===ee);de&&delete de.gitObjectId}}for(let P of be.omissions)E(P);be.overflow&&I(be.overflow)}m.sort((x,A)=>x.path.localeCompare(A.path,"en")),h.sort((x,A)=>x.path.localeCompare(A.path,"en"));let Pg=be===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...be.evidence?{gitSelection:be.evidence}:{}},Ou=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Pg,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${b}`,hash:b,count:k}}:{}}),Jo=Ou();for(;sl(Jo)>i.maxManifestBytes;){if(h.filter(A=>!nl(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let H=ao(h);if(H===null)break;v(H)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))N+=1,U(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Jo=Ou()}return Jo}async function cl(e,t,i={}){let r=(await jt(e.projectRoot))?.native.snapshot??Wc;return Ap(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 co(e,t){let i=lE(e,t);await $(e.nativeRoot,i);try{let n=await Xh({root:e.nativeRoot,file:i,maxBytes:bS,label:"Native baseline snapshot manifest"});return ai(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as RE}from"crypto";import pl from"path";var _e=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as uo,promises as he}from"node:fs";import Ee from"node:path";import{TextDecoder as bE}from"node:util";import gE from"path";var mE=Go(_a(),1);var xp=(e,t)=>{let i=e[t];return i==null?null:String(i)};function er(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 Zn(e,t){let i=er(e,t);if(gE.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 wE(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 Tp(e){if(!e.run_id)return null;let t=er(e,"run_id"),i=er(e,"skill"),n=er(e,"skill_version"),r=er(e,"skill_hash"),a=Zn(e,"pending_ref"),o=Zn(e,"trajectory_ref"),s=Zn(e,"context_ref"),c=Zn(e,"artifacts_ref"),l=Zn(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:xp(e,"current_step"),iteration:u,pending:xp(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:wE(e)}}var Cj=256*1024;var yE=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function NE(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=Tp(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function lo(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=>!yE.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 NE(t)}var ye={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 ir(e,t){let i=Ee.relative(e,t);return i===""||!Ee.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ee.sep}`)}function _p(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function tr(e,t){return L({...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 kE(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function oi(e,t,i){let n=_e[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Ee.resolve(e),a=Ee.resolve(r,...n.split("/"));if(!ir(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Ip(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 ll(e,t){let i=Ee.resolve(e),n=Ee.resolve(t);if(!ir(i,n))throw new Error("Native Run path is outside its change");let r=[await Ip(i)],a=i;for(let o of Ee.relative(i,n).split(Ee.sep).filter(Boolean)){a=Ee.join(a,o);let s;try{s=await Ip(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!ir(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function fo(e){for(let t of e){let i=await he.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!kE(t,i)||await he.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function SE(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 Di(e,t,i,n,r){let a=await ll(e,Ee.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=_p(o),c=await he.realpath(t);if(!ir(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?uo.O_RDONLY:uo.O_RDONLY|uo.O_NOFOLLOW|uo.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 fo(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!tr(s,d)||!tr(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await SE(u,i,n);await r?.beforeFinalCheck?.();let[h,g,S]=await Promise.all([u.stat(),he.lstat(t),he.realpath(t)]);if(await fo(a),!g.isFile()||g.isSymbolicLink()||S!==c||!tr(s,h)||!tr(s,g))throw new Error(`${n} changed while reading`);let N;try{N=new bE("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 EE(e,t,i){let n=await ll(e,Ee.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(!ir(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await fo(n),{exists:!0,identity:_p(r),realPath:a}}async function CE(e,t,i,n){let r=await ll(e,Ee.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()||!tr(i.identity,a)||await he.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await fo(r)}async function ul(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await EE(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ei(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await CE(e.changeDir,e.file,i,e.label)}});let n=await Di(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 jp(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Op(e){return`${JSON.stringify(e,null,2)}
152
+ `}function dl(e){return lo(e)}async function We(e,t){let i=oi(e,"stateRef"),n=await Di(e,i,ye.runStateBytes,"Native Run state",t);return n?lo(jp(n.text,"Native Run state")):null}async function fl(e,t,i){let n=lo(t);await ul({changeDir:e,file:oi(e,"stateRef"),content:Op(n),maxBytes:ye.runStateBytes,label:"Native Run state",hooks:i})}async function nt(e,t,i){let n=oi(e,"trajectoryRef",t),r=await Di(e,n,ye.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>ye.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ye.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 $p(e,t,i){return(await Di(e,oi(e,"trajectoryRef",t),ye.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Hp(e,t,i,n){let r=oi(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
153
+ `;if(Buffer.byteLength(a,"utf8")>ye.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${ye.trajectoryEventBytes} bytes`);let o=await Di(e,r,ye.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=ye.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ye.trajectoryEvents} events`);await ul({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:ye.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function ho(e,t,i){let n=await Di(e,oi(e,"checkpointRef",t),ye.checkpointBytes,"Native Run checkpoint",i);return n?jp(n.text,"Native Run checkpoint"):null}async function Fp(e,t,i,n){await ul({changeDir:e,file:oi(e,"checkpointRef",t),content:Op(i),maxBytes:ye.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var PE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ml=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 hl(e){return RE("sha256").update(e).digest("hex")}function AE(e,t){if(!PE.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=pl.join(e.changesDir,t);if(!z(e.changesDir,i))throw new Error("Native change path escaped");return pl.join(i,"runtime","trajectory.jsonl")}function xE(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 TE(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 IE(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=xE(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(`
154
+ `)])}catch(d){if(!TE(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:hl(t),targetHash:hl(l),tailHash:hl(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function _E(e,t){let i=AE(e,t);await $(e.nativeRoot,i);let n=pl.join(e.changesDir,t),r=await $p(n,_e.trajectoryRef);return r===null?{status:"clean",file:i}:IE(i,Buffer.from(r))}async function vl(e,t){let i=await _E(e,t);return"inspection"in i?i.inspection:i}async function nr(e,t){let i=await vl(e,t);if(i.status!=="clean")throw new ml(i)}import{createHash as $E}from"node:crypto";import{promises as mo}from"node:fs";import Ft from"node:path";import{execFileSync as jE}from"child_process";import po from"path";function gl(e,t){return jE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function OE(e,t){let i=po.normalize(e),n=po.normalize(t);return process.platform==="win32"?i.toLowerCase()===n.toLowerCase():i===n}function Dp(e){try{let t=po.resolve(gl(e,["rev-parse","--show-toplevel"])),n=gl(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),r=n?po.resolve(n.slice(9)):t,a=null;try{a=gl(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!OE(t,r),currentWorktreeRoot:t,primaryWorktreeRoot:r,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var rr=/^[a-f0-9]{64}$/u,HE=16*1024,wl=process.platform,FE=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Li(e){return FE.has(e)}function qp(e,t){let i=Ft.relative(e,t);return Ft.isAbsolute(i)||i===".."||i.startsWith(`..${Ft.sep}`)?null:i.replaceAll("\\","/")||"."}function Vp(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Wp(e,t){if(e.length===0||Vp(e)||e.includes("\\")||Ft.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=Ft.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function yl(e,t){return $E("sha256").update(`${e}
155
+ ${t}`).digest("hex")}async function Lp(e,t){let i=await mo.realpath(t),n=await mo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=wl==="win32"?Ft.normalize(i).toLowerCase():i;return yl(e,`${r}
156
156
  ${n.dev}
157
157
  ${n.ino}
158
- ${n.birthtimeMs}`)}async function _p(e,t){let i=await oo.realpath(t),n=await oo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?Ht.normalize(i).toLowerCase():i;return ol(e,r)}function SE(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function sl(e){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"]),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")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Qn.test(String(t.projectRootId))||!Qn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");SE(t.capturedAt),Op(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&&!Qn.test(String(t.projectRootPathId))||a&&!Qn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Qn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid")}function kE(e,t){return Ht.join(e.changesDir,t,"runtime","workspace.json")}function EE(e,t){let i=jp(e.nativeRoot,kE(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Op(i,"Native workspace file ref")}async function CE(e,t){try{let i=await oe({root:e.nativeRoot,ref:EE(e,t),maxBytes:yE});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function RE(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=jp(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([Ip("comet.native.workspace-project-root.v2",e.paths.projectRoot),Ip("comet.native.workspace-native-root.v2",e.paths.nativeRoot),_p("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),_p("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),s={schema:"comet.native.workspace.v2",capturedAt:(e.now??new Date).toISOString(),capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:ol("comet.native.workspace-session.v2",`${i}
158
+ ${n.birthtimeMs}`)}async function Mp(e,t){let i=await mo.realpath(t),n=await mo.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=wl==="win32"?Ft.normalize(i).toLowerCase():i;return yl(e,r)}function DE(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 Bp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Vp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function zp(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Bp(e.changeBranch,"Native workspace change branch"),Bp(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 vo(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"||!rr.test(String(t.projectRootId))||!rr.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");DE(t.capturedAt),Wp(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&&!rr.test(String(t.projectRootPathId))||a&&!rr.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!rr.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(zp(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 LE(e,t){return Ft.join(e.changesDir,t,"runtime","workspace.json")}function ME(e,t){let i=qp(e.nativeRoot,LE(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Wp(i,"Native workspace file ref")}async function BE(e,t){try{let i=await ce({root:e.nativeRoot,ref:ME(e,t),maxBytes:HE});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function qE(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=qp(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([Lp("comet.native.workspace-project-root.v2",e.paths.projectRoot),Lp("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Mp("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Mp("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&&zp(e.binding);let s={capturedAt:o,capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:yl("comet.native.workspace-session.v2",`${i}
159
159
  ${n}
160
- ${e.sessionId}`)}:{}};return sl(s),s}async function so(e,t){let i=await CE(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(sl(i),i)}async function $p(e){sl(e.identity);let t=await RE({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")),process.platform==="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}}var Dt="comet.native.v3",ri="comet.native.v2",ai="comet.native.v1",oi="comet.native.transition.v3",Hi="comet.native.transition.v2",Zn="comet.native.transition.v1";var Dp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],PE=new Set(Dp),Fp=new Set([...Dp,"minimum_runtime_version","revision"]),AE=new Set([...Fp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),xE=new Set(["capability","operation","source","base_hash"]),TE=new Set(["shape","build","verify","archive"]),IE=new Set(["implicit","confirmed"]),_E=new Set(["pending","pass","fail"]),Ft="comet-state.yaml",ul=/^[a-f0-9]{64}$/u,Lp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jE=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,er=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"},si=class extends Error{constructor(i,n){super(i!==Dt||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"},tr=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"},co=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"},Wj=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
161
- `);function nr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Mp(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 ut(e){if(!Lp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function OE(e){if(!Lp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Bp(e,t){if(e.length===0||lt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function $E(e,t){let i=nr(e,`spec_changes[${t}]`);if(Mp(i,xE,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(OE(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"&&Bp(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"||!ul.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"||!ul.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 HE(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 dl(e,t){if(Mp(e,t,Ft),typeof e.name!="string")throw new Error("Native change name is required");if(ut(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"||!TE.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&&!IE.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($E),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"||!_E.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"&&Bp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!HE(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 rr(e){let t=nr(e,Ft);if(t.schema!==ai)throw new Error(`Expected ${ai}`);return{schema:ai,...dl(t,PE)}}function ir(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function cl(e,t,i){if(e===null)return null;let n=typeof e=="string"?jE.exec(e):null;if(!n||n[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function DE(e){if(e==null)return null;if(typeof e!="string"||!ul.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function FE(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ar(e){let t=nr(e,Ft);if(t.schema!==ri)throw new Error(`Expected ${ri}`);if(ir(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ri} minimum_runtime_version must be 2`);return{schema:ri,minimum_runtime_version:2,revision:ir(t.revision,"Native v2 revision"),...dl(t,Fp)}}function dt(e){let t=nr(e,Ft);if(t.schema!==Dt){if(t.schema===ai||t.schema===ri){let o=t.schema===ai?rr(t):ar(t);throw new er(o.name,o.schema)}throw new si(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=ir(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new si(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=ir(t.revision,"Native revision"),r=dl(t,AE),a=DE(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Dt,minimum_runtime_version:3,revision:n,verification_protocol:FE(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:cl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:cl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:cl(t.partial_allowance,"Native partial_allowance","allowances")}}function LE(e){let t=nr(e,Ft);if(t.schema===ai){let r=rr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Dt}`}}if(t.schema===ri){let r=ar(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Dt}`}}if(t.schema!==Dt){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 si(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=ir(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new si(t.schema,i).message};let n=dt(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function ll(e){let t=dt(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 $(e,t){ut(t);let i=lt.join(e.changesDir,t);if(!J(e.changesDir,i))throw new Error("Native change path escaped");return i}async function ci(e,t){let i=lt.join($(e,t),"runtime","schema-migration.json");await H(e.nativeRoot,i);try{return await Hp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function fl(e,t){let i=lt.join($(e,t),"runtime","checkpoint-journal.json");await H(e.nativeRoot,i);try{return await Hp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var ME=256*1024;async function qp(e,t=lt.dirname(e)){let i=lt.relative(t,e).split(lt.sep).join("/"),n=await oe({root:t,ref:i,maxBytes:ME}),r=(0,lo.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 hl(e,t){let i=lt.join($(e,t),Ft);await H(e.nativeRoot,i);let n=LE(await qp(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await ci(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 BE(e,n.state),n)}async function BE(e,t){if(await to(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function fe(e,t){let i=await hl(e,t);if(i.status==="migration-required")throw new er(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new si(i.schema,i.minimumRuntimeVersion);return i.state}async function qE(e,t,i){let n={...t,schema:Dt,minimum_runtime_version:3,revision:i+1},r=await Qh({expectedRevision:i,next:n,read:async()=>{let a=dt(await qp(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Qt(e,(0,lo.stringify)(ll(a))),equals:(a,o)=>JSON.stringify(ll(a))===JSON.stringify(ll(o)),conflict:a=>new tr(t.name,i,a)});return Object.assign(t,r),r}async function Di(e,t,i,n){if(await Ln(e.projectRoot),await ci(e,t.name))throw new er(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await fl(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await fe(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Xn(e,t.name);let a=lt.join($(e,t.name),Ft);return await H(e.nativeRoot,a),qE(a,t,i)}var zp=["Outcome","Scope","Non-goals","Acceptance examples"],VE=[...zp,"Constraints and invariants","Decisions","Open questions","Verification expectations"],zE=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Wp={maxFileBytes:In};function Jp(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
162
- `).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 WE(e,t){let i=Vp.resolve(e,...t.split(/[\\/]/u));if(!J(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await pl.realpath(e),r=await pl.realpath(i);if(!J(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await pl.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function or(e){return{valid:e.length===0,findings:e}}async function ml(e,t){let i=[],n;try{n=(await oe({root:e,ref:t,maxBytes:Wp.maxFileBytes})).text}catch(o){return or([{code:"brief-missing",message:o.message,path:t}])}let r=Jp(n);for(let o of VE)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of zp)(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}),or(i)}async function vl(e,t){let i=[],n;try{n=(await oe({root:e,ref:t,maxBytes:Wp.maxFileBytes})).text}catch(a){return or([{code:"verification-missing",message:a.message,path:t}])}let r=Jp(n);for(let a of zE)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 or(i)}function Lt(e,t){return Vp.join(e.specsDir,t,"spec.md")}async function Up(e,t){let i=[],n=$(e,t.name);for(let r of t.spec_changes){let a=Lt(e,r.capability),o=null;try{await H(e.nativeRoot,a),o=await Vn(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 WE(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return or(i)}import Gp from"node:path";import{createHash as JE}from"crypto";function Ve(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function UE(e,t){t.has(e)&&Ve("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)||Ve("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&Ve("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ve("symbol properties are not supported"),`[${e.map(n=>gl(n,t)).join(",")}]`}finally{t.delete(e)}}function GE(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Ve("only plain objects are supported"),t.has(e)&&Ve("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ve("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))&&Ve("accessor properties are not supported"),`${JSON.stringify(o)}:${gl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function gl(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)||Ve("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?UE(e,t):GE(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ve(`${typeof e} values are not supported`)}return Ve("unsupported value type")}function sr(e){return gl(e,new Set)}function F(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 JE("sha256").update(`${e}
163
- ${sr(t)}`).digest("hex")}var KE="comet.native.acceptance.v1",YE=/^acceptance-[a-f0-9]{64}$/u,XE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),QE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,ZE=/^[a-f0-9]{64}$/u,eC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function tC(e,t){return e<t?-1:e>t?1:0}var ft=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),cr=Object.freeze({maxCriteria:1024}),Kp="<!-- comet-native:acceptance-evidence:start -->",Yp="<!-- comet-native:acceptance-evidence:end -->";function Xp(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 Qp(e,t){let i=t.toString(36),n=F("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function iC(e){if(!ZE.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=eC.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]!==F("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function nC(e,t){let i=Xp(e.text,ft.maxTextBytes),n=e.context.slice(0,ft.maxContextItems).map(r=>Xp(r,ft.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 em(e){let t=iC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(tC),r=n.slice(0,ft.maxFailedCheckIds),a=e.criteria.slice(t,t+ft.maxItems);for(let c of a){let l=[...i,nC(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?Qp(e.acceptanceHash,u):null,limits:{...ft}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ft.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?Qp(e.acceptanceHash,o):null,limits:{...ft}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ft.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Nl(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 wl(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 Zp(e){return e.includes("-->")||e.includes("--!>")}function*Fi(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
160
+ ${e.sessionId}`)}:{}},c=e.binding?{schema:"comet.native.workspace.v3",...s,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...s};return vo(c),c}async function Dt(e,t){let i=await BE(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(vo(i),i)}async function go(e){vo(e.identity);let t=await qE({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")),wl==="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 wo(e){if(vo(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 go(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Dp(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 Jp(e,t){let i=await Dt(e,t);if(i===null)return null;let n=await wo({paths:e,identity:i});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return i}var Lt="comet.native.v3",si="comet.native.v2",ci="comet.native.v1",li="comet.native.transition.v3",Mi="comet.native.transition.v2",ar="comet.native.transition.v1";var Up=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],VE=new Set(Up),Kp=new Set([...Up,"minimum_runtime_version","revision"]),WE=new Set([...Kp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),zE=new Set(["capability","operation","source","base_hash"]),JE=new Set(["shape","build","verify","archive"]),GE=new Set(["implicit","confirmed"]),UE=new Set(["pending","pass","fail"]),Mt="comet-state.yaml",kl=/^[a-f0-9]{64}$/u,Yp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KE=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,or=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"},ui=class extends Error{constructor(i,n){super(i!==Lt||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"},sr=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"},yo=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"},No=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"},RO=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
161
+ `);function lr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xp(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 dt(e){if(!Yp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function YE(e){if(!Yp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Qp(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 XE(e,t){let i=lr(e,`spec_changes[${t}]`);if(Xp(i,zE,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(YE(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"&&Qp(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"||!kl.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"||!kl.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 QE(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 Sl(e,t){if(Xp(e,t,Mt),typeof e.name!="string")throw new Error("Native change name is required");if(dt(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"||!JE.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&&!GE.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(XE),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"||!UE.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"&&Qp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!QE(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 ur(e){let t=lr(e,Mt);if(t.schema!==ci)throw new Error(`Expected ${ci}`);return{schema:ci,...Sl(t,VE)}}function cr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Nl(e,t,i){if(e===null)return null;let n=typeof e=="string"?KE.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 ZE(e){if(e==null)return null;if(typeof e!="string"||!kl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function eC(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 dr(e){let t=lr(e,Mt);if(t.schema!==si)throw new Error(`Expected ${si}`);if(cr(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${si} minimum_runtime_version must be 2`);return{schema:si,minimum_runtime_version:2,revision:cr(t.revision,"Native v2 revision"),...Sl(t,Kp)}}function ft(e){let t=lr(e,Mt);if(t.schema!==Lt){if(t.schema===ci||t.schema===si){let o=t.schema===ci?ur(t):dr(t);throw new or(o.name,o.schema)}throw new ui(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=cr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new ui(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=cr(t.revision,"Native revision"),r=Sl(t,WE),a=ZE(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Lt,minimum_runtime_version:3,revision:n,verification_protocol:eC(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Nl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Nl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Nl(t.partial_allowance,"Native partial_allowance","allowances")}}function tC(e){let t=lr(e,Mt);if(t.schema===ci){let r=ur(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Lt}`}}if(t.schema===si){let r=dr(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Lt}`}}if(t.schema!==Lt){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 ui(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=cr(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new ui(t.schema,i).message};let n=ft(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function bl(e){let t=ft(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 O(e,t){dt(t);let i=ut.join(e.changesDir,t);if(!z(e.changesDir,i))throw new Error("Native change path escaped");return i}async function di(e,t){let i=ut.join(O(e,t),"runtime","schema-migration.json");await $(e.nativeRoot,i);try{return await Gp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function El(e,t){let i=ut.join(O(e,t),"runtime","checkpoint-journal.json");await $(e.nativeRoot,i);try{return await Gp.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var iC=256*1024;async function Zp(e,t=ut.dirname(e)){let i=ut.relative(t,e).split(ut.sep).join("/"),n=await ce({root:t,ref:i,maxBytes:iC}),r=(0,bo.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 Cl(e,t){let i=ut.join(O(e,t),Mt);await $(e.nativeRoot,i);let n=tC(await Zp(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await di(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 nC(e,n.state),n)}async function nC(e,t){if(await co(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function me(e,t){let i=await Cl(e,t);if(i.status==="migration-required")throw new or(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new ui(i.schema,i.minimumRuntimeVersion);return await Jp(e,t),i.state}async function rC(e,t,i){let n={...t,schema:Lt,minimum_runtime_version:3,revision:i+1},r=await ap({expectedRevision:i,next:n,read:async()=>{let a=ft(await Zp(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ei(e,(0,bo.stringify)(bl(a))),equals:(a,o)=>JSON.stringify(bl(a))===JSON.stringify(bl(o)),conflict:a=>new sr(t.name,i,a)});return Object.assign(t,r),r}async function Bi(e,t,i,n){if(await zn(e.projectRoot),await di(e,t.name))throw new or(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await El(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await me(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await nr(e,t.name);let a=ut.join(O(e,t.name),Mt);return await $(e.nativeRoot,a),rC(a,t,i)}var tm=["Outcome","Scope","Non-goals","Acceptance examples"],aC=[...tm,"Constraints and invariants","Decisions","Open questions","Verification expectations"],oC=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],im={maxFileBytes:$n};function nm(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
162
+ `).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 sC(e,t){let i=em.resolve(e,...t.split(/[\\/]/u));if(!z(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Rl.realpath(e),r=await Rl.realpath(i);if(!z(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Rl.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function fr(e){return{valid:e.length===0,findings:e}}async function Pl(e,t){let i=[],n;try{n=(await ce({root:e,ref:t,maxBytes:im.maxFileBytes})).text}catch(o){return fr([{code:"brief-missing",message:o.message,path:t}])}let r=nm(n);for(let o of aC)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of tm)(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}),fr(i)}async function Al(e,t){let i=[],n;try{n=(await ce({root:e,ref:t,maxBytes:im.maxFileBytes})).text}catch(a){return fr([{code:"verification-missing",message:a.message,path:t}])}let r=nm(n);for(let a of oC)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 fr(i)}function Bt(e,t){return em.join(e.specsDir,t,"spec.md")}async function rm(e,t){let i=[],n=O(e,t.name);for(let r of t.spec_changes){let a=Bt(e,r.capability),o=null;try{await $(e.nativeRoot,a),o=await Kn(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 sC(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return fr(i)}import am from"node:path";import{createHash as cC}from"crypto";function ze(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function lC(e,t){t.has(e)&&ze("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)||ze("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&ze("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ze("symbol properties are not supported"),`[${e.map(n=>xl(n,t)).join(",")}]`}finally{t.delete(e)}}function uC(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&ze("only plain objects are supported"),t.has(e)&&ze("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ze("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))&&ze("accessor properties are not supported"),`${JSON.stringify(o)}:${xl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function xl(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)||ze("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?lC(e,t):uC(e,t);case"bigint":case"function":case"symbol":case"undefined":return ze(`${typeof e} values are not supported`)}return ze("unsupported value type")}function hr(e){return xl(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 cC("sha256").update(`${e}
163
+ ${hr(t)}`).digest("hex")}var dC="comet.native.acceptance.v1",fC=/^acceptance-[a-f0-9]{64}$/u,hC=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),pC=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,mC=/^[a-f0-9]{64}$/u,vC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function gC(e,t){return e<t?-1:e>t?1:0}var ht=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),pr=Object.freeze({maxCriteria:1024}),om="<!-- comet-native:acceptance-evidence:start -->",sm="<!-- comet-native:acceptance-evidence:end -->";function cm(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 lm(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 wC(e){if(!mC.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=vC.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 yC(e,t){let i=cm(e.text,ht.maxTextBytes),n=e.context.slice(0,ht.maxContextItems).map(r=>cm(r,ht.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 dm(e){let t=wC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(gC),r=n.slice(0,ht.maxFailedCheckIds),a=e.criteria.slice(t,t+ht.maxItems);for(let c of a){let l=[...i,yC(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?lm(e.acceptanceHash,u):null,limits:{...ht}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ht.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?lm(e.acceptanceHash,o):null,limits:{...ht}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ht.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function _l(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 Tl(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 um(e){return e.includes("-->")||e.includes("--!>")}function*qi(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
164
164
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
165
- `,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=wl(l,t);else if(i)Zp(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=wl(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Zp(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 rC(e){return[...Fi(e)].map(({line:t,body:i})=>({line:t,body:i}))}function yl(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function aC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function bl(e,t,i,n=[]){let r=yl(i),a=t.replaceAll("\\","/").trim(),o=n.map(yl);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-${F(KE,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function Sl(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 oC(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of Fi(e)){r=s+1;let c=o?Nl(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 tm(e,t="brief.md",i=cr.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=oC(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of Fi(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 Fi(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(),Sl(a.map(c=>bl("brief-example",t,c.join(`
166
- `))),"Brief")}function im(e,t="spec.md",i=cr.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(bl("spec-scenario",t,[a.title,...a.body].join(`
167
- `),a.context)),a=null}};for(let{line:s,body:c}of Fi(e)){let l=c?Nl(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=yl(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(),Sl(n,"Specification")}function nm(e,t="spec.md",i=cr.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(bl("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 Fi(e)){let d=u?Nl(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||wl(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(),Sl(n,"Specification mandatory requirements")}function sC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||aC(i)||Gp.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=Gp.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(!QE.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function cC(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=>!XE.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function rm(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=cC(i,n),a=r.acceptance_id;if(typeof a!="string"||!YE.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 sC(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 am(e){let t=rC(e);if(t.some(({line:l,body:u})=>!u&&(l===Kp||l===Yp)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===Kp?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===Yp?[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(`
168
- `).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=rm(o),c=lC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function lC(e){let t=rm([...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 om from"node:path";var uC="comet.native.contract.v1",dC="comet.native.acceptance-set.v1",sm=/^[a-f0-9]{64}$/u,lr={maxAcceptanceCriteria:cr.maxCriteria};function cm(e,t){let i=om.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})||om.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 lm(e){return F("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
169
- `))}function fC(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(sm))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(sm))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=cm(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:lm(e.markdown)},markdown:e.markdown}}function hC(e,t){return um(e.id,t.id)}function um(e,t){return e<t?-1:e>t?1:0}function dm(e){let t=cm(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(fC).sort((d,f)=>um(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=tm(e.briefMarkdown,t,lr.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...im(f,d.source,lr.maxAcceptanceCriteria-a.length)),a.push(...nm(f,d.source,lr.maxAcceptanceCriteria-a.length)));if(a.sort(hC),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>lr.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${lr.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:lm(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=F(dC,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:F(uC,u)}}var li={maxSpecs:64,maxFileBytes:In,maxTotalBytes:4*1024*1024};async function Li(e){if(e.specChanges.length>li.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await oe({root:e.changeDir,ref:e.briefRef,maxBytes:li.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 oe({root:e.changeDir,ref:r.source,maxBytes:li.maxFileBytes});if(i+=a.size,i>li.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:dm({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import pC from"path";var kl="comet.selection.v2",mC=16*1024;function hm(e){return pC.join(e,".comet","current-change.json")}function vC(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fm(e){return e===null||typeof e=="string"}function gC(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(!vC(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&&!fm(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:kl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==kl)throw new Error(`current change selection schema must be ${kl}`);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(!fm(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 pm(e){let t;try{let n=hm(e),{bytes:r}=await ti(n,mC,{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",...gC(t)}}var SO=16*1024;async function mm(e){let t=await pm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(ut(t.selection.change),t.selection)}import wC from"path";function El(e,t){return wC.resolve(e,...t.split(/[\\/]/u))}async function vm(e,t){let i=[],n=$(e,t.name),r=El(n,Te.stateRef),a;try{a=await qe(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=El(n,a.trajectoryRef),s=await al(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 it(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=El(n,a.checkpointRef);try{let u=await ao(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import{randomUUID as pR}from"crypto";import{promises as mR}from"fs";import vR from"path";import{isDeepStrictEqual as Wl}from"util";var yC=/\b(Bearer|Basic)\s+[^\s"']+/giu,NC=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,bC=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,SC=/\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,kC=/("(?:[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,EC=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,CC=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function ke(e){return e.replace(yC,"$1 [REDACTED]").replace(NC,"[REDACTED PRIVATE KEY]").replace(bC,"$1[REDACTED]@").replace(SC,"[REDACTED TOKEN]").replace(kC,'$1"[REDACTED]"').replace(EC,"$1$2$1$3$4[REDACTED]$4").replace(CC,"$1$2[REDACTED]")}var Mi={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var RC=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function PC(e,t){return e<t?-1:e>t?1:0}function AC(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"||!RC.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(PC)}function Cl(e=[]){return AC(e,"Native repair failed check IDs",Mi.maxFailedCheckIds,!0)}function gm(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function xC(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:gm(e.failedAcceptanceIds,t.failedAcceptanceIds)&&gm(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Rl(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(xC(n,a))break;i+=1,n=a}return i}import jm from"node:path";import{createHash as Em}from"node:crypto";import wm from"path";var Pl="comet.native.implementation-scope.v2",Cm="comet.native.content-snapshot-projection.v1",ur="comet.native.content-snapshot-projection.v1",Rm="comet.native.implementation-scope.v2",TC="comet.native.unresolved-scope-id.v1",IC="comet.native.scope-detail-overflow.v1",_C="comet.native.snapshot-projection-overflow.v2",Il=/^[a-f0-9]{64}$/u,di=1024*1024,jC=128,OC=128;function ce(e,t){return e<t?-1:e>t?1:0}function Al(e){if(!Il.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function $C(e,t){return e===t?0:e===null?-1:t===null?1:ce(e,t)}function Bt(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=wm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||wm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Pm(e,t){return e==="."?e:Bt(e,t)}function Bi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function HC(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:Bt(e.path,`${t} path`),hash:e.hash,size:Bi(e.size,`${t} size`),type:"file"}}function DC(e,t){return{path:Pm(e.path,`${t} path`),size:e.size===null?null:Bi(e.size,`${t} size`),type:e.type,reason:e.reason}}function FC(e,t){return ce(e.path,t.path)||ce(e.hash,t.hash)||e.size-t.size}function LC(e,t){return ce(e.path,t.path)||ce(e.reason,t.reason)||ce(e.type,t.type)||(e.size??-1)-(t.size??-1)}function dr(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
170
- `,"utf8")}function Mt(e,t,i){let n=`${t}
171
- ${sr(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function MC(e){if(dr(e)<=di)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=Em("sha256");a.update(`${_C}
172
- `),e.omissionOverflow&&Mt(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,Mt(a,"omission",f)},s=f=>{n+=1,r+=1,Mt(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(;dr(u)>di;){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 xl(e){let t=ii(e),i=t.entries.map((r,a)=>HC(r,`Snapshot entry ${a}`));if(i.sort(FC),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)=>DC(r,`Snapshot omission ${a}`));return n.sort(LC),MC({schema:Cm,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 ho(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:Bt(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)=>ce(i.path,n.path)||ce(i.kind,n.kind))}function po(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function ym(e){return e?{hash:e.hash,size:e.size}:null}function Am(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:ce(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:ym(c),after:ym(l)})}}function BC(e,t){return{...e,attributedTo:t.filter(i=>po(i,e.path))}}function ht(e,t){return{id:`scope:${F(TC,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function qC(e,t){let i=t.omitted.map(n=>ht({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(ht({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(ht({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 Nm(e,t){return qC(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Tl(e,t){return ce(e.kind,t.kind)||ce(e.source,t.source)||$C(e.path,t.path)||ce(e.id,t.id)}function VC(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Tl)}function zC(e){return[...new Set(e.map((t,i)=>Bt(t,`Git path ${i}`)))].sort(ce)}function xm(e){if(typeof e.contractHash!="string"||!Il.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ho(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:zC(e.gitChangedPaths)}}}function WC(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Am(e,t,d=>{let f=i.some(p=>po(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<jC){let p=BC(d,i),m=dr(p);s+m<=di?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function Tm(e,t){return ht({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 JC(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:Bi(Number(t[1]),"Scope overflow change count"),unresolved:Bi(Number(t[2]),"Scope overflow unresolved count"),unattributed:Bi(Number(t[3]),"Scope overflow unattributed count")},n=ui(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Tm(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function UC(e){let t=Em("sha256");t.update(`${IC}
173
- `);let i=0;Am(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){Mt(t,"change",r);let a=0;for(let o of e.declaredArtifacts)po(o,r.path)&&(a+=1,Mt(t,"change-attribution",o));Mt(t,"change-end",{attributionCount:a}),a===0&&Mt(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&&Mt(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function Im(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=WC(e,t,r,i.gitChangedPaths),s=F(ur,e),c=F(ur,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=OC)break;l.push(ht({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=[...Nm("baseline",e),...Nm("current",t),...o.totalChanges===0&&a===null?[ht({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(Ge=>Ge.attributedTo.length===0),E=o.totalChanges-w.length,_=o.totalUnattributed-g.length,K=u-y.detailedOmissionCount,q=_+K,U=[...g.map(Ge=>ht({kind:"unattributed-change",source:"implementation-scope",path:Ge.path,evidence:{after:Ge.after,before:Ge.before,changeKind:Ge.kind}},`Changed path is not covered by a declared artifact: ${Ge.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||q>0?[Tm(y.overflowHash,{changes:E,unattributed:_,unresolved:q})]:[]],Y=VC(U),Ue=y.includeGitAdvisory?f():void 0;return{schema:Pl,contractHash:n,baselineProjectionRef:Al(s),baselineProjectionHash:s,currentProjectionRef:Al(c),currentProjectionHash:c,complete:Y.length===0,declaredArtifacts:r,changes:w,unattributed:g,unresolvedScopes:Y,noCodeReason:a,...Ue?{gitAdvisory:Ue}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,N="0".repeat(64);for(;;){let y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:N});if(dr({...y,scopeHash:N})<=di)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 S=o.totalChanges>m||u>h?UC({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):N,b=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:S}),C={...b,scopeHash:F(Rm,b)};if(dr(C)>di)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return C}function _l(e){let t=xl(e.baseline),i=xl(e.current),n=xm(e);return{authority:n,baseline:t,current:i,scope:Im(t,i,n)}}var GC=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function pt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(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 ui(e,t){if(typeof e!="string"||!Il.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function bm(e,t,i){let n=Al(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function fo(e,t){let i=pt(e,"Native snapshot projection");if(mt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Cm)throw new Error("Native snapshot projection schema is invalid");let n=ii({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=xl(n);if(F(ur,i)!==F(ur,r))throw new Error("Native snapshot projection is not canonical");let a=F(ur,r);if(t!==void 0&&ui(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function jl(e,t){let i=pt(e,`Declared artifact ${t}`);if(mt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Bt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Sm(e,t){if(e===null)return null;let i=pt(e,t);return mt(i,["hash","size"],[],t),{hash:ui(i.hash,`${t} hash`),size:Bi(i.size,`${t} size`)}}function km(e,t){let i=pt(e,`Implementation change ${t}`);if(mt(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(jl),r=ho(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Sm(i.before,`Implementation change ${t} before`),o=Sm(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:Bt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function KC(e,t){let i=pt(e,`Unresolved scope ${t}`);mt(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"?Pm(i.path,`Unresolved scope ${t} path`):Bt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function uo(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)=>Bt(r,`${t} ${a}`)),n=[...new Set(i)].sort(ce);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function mo(e){let t=pt(e,"Native implementation scope"),i=[...GC].filter(w=>w!=="gitAdvisory");if(mt(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Pl)throw new Error("Native implementation scope schema is invalid");let n=ui(t.contractHash,"Implementation scope contractHash"),r=ui(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=bm(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=ui(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=bm(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(jl);if(JSON.stringify(c)!==JSON.stringify(ho(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(km),u=[...l].sort((w,g)=>ce(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=>po(g,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(km),p=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(KC),h=m.filter(w=>w.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=h[0]===void 0?null:JC(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 N=t.noCodeReason,k=[...p.map(w=>ht({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&&N===null?[ht({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")]:[]],S=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Tl))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(S)!==JSON.stringify(k.sort(Tl))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=pt(t.gitAdvisory,"Implementation scope Git advisory");if(mt(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=uo(w.changedPaths,"Git changed paths"),E=uo(w.pathsPresentInSnapshotChanges,"Git present paths"),_=uo(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),K=[...E,..._].sort(ce),q=new Set(l.map(U=>U.path));if(JSON.stringify(K)!==JSON.stringify(g)||(v?.changes??0)===0&&E.some(U=>!q.has(U))||_.some(U=>q.has(U)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:_}}let C={schema:Pl,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...b?{gitAdvisory:b}:{}},y=ui(t.scopeHash,"Implementation scope scopeHash");if(F(Rm,C)!==y)throw new Error("Implementation scope content hash mismatch");return{...C,scopeHash:y}}function YC(e){let t=pt(e,"Native implementation scope authority");if(mt(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(jl);if(JSON.stringify(i)!==JSON.stringify(ho(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=uo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=xm({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 fr(e){let t=pt(e,"Native implementation scope bundle");mt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=YC(t.authority),n=fo(t.baseline),r=fo(t.current),a=mo(t.scope),o=Im(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 _m(e){let t=mo(e.scope);return fr({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}var $m=/^[a-f0-9]{64}$/u;var XC="comet.native.acceptance-trace.v2",QC="comet.native.partial-allowance.v1",ZC="comet.native.verification-evidence.v2";function vt(e,t){if(!$m.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Hm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Dm(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Ol(e,t,i=2e3){let n=ke(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function hr(e,t){let i=jm.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})||jm.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 eR(e,t,i){let n=hr(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Xe(n),a=n.toLowerCase(),o=i?hr(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 $l(e){let t=hr(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 qi(e,t){return e<t?-1:e>t?1:0}function vo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function go(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Fm(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Om(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 tR(e){let t=vo(e,"Native acceptance trace");if(go(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"||!$m.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=hr(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=vo(o,`Native acceptance trace entry ${s}`);if(go(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=>$l(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(qi))||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:hr(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Ol(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>qi(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=vt(t.traceHash,"Native acceptance trace hash");if(F(XC,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Lm(e){let t=vo(e,"Native partial allowance");if(go(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(qi))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Dm(t.change),scopeHash:vt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Ol(t.reason,"Partial allowance reason"),confirmedSummary:Ol(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Hm(t.sourceRevision),confirmedAt:Fm(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=vt(t.allowanceHash,"Native partial allowance hash");if(F(QC,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Hl(e){let t=vo(e,"Native verification evidence");if(go(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=vt(t.implementationScopeHash,"Native verification implementation scope hash"),n=tR(t.acceptanceTrace),r=vt(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:vt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>$l(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(qi)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(qi);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=>$l(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(qi)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Dm(t.change),sourceRevision:Hm(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:vt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:Om(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:eR(t.reportRef,"Native verification report ref"),reportHash:vt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:Om(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Fm(t.createdAt,"Native verification timestamp")},d=vt(t.envelopeHash,"Native verification envelope hash");if(F(ZC,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function pr(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 Mm="repairStagnation",Ee={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},nR=/^[a-f0-9]{64}$/u;var rR=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),aR=["data","runId","sequence","timestamp","type"],Bm=["disposition","overrideSummaryHash","signatureHash"],oR=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],qm=12;function Fl(e,t){return e<t?-1:e>t?1:0}function Vm(e,t,i){let n=Object.keys(e).sort(Fl);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function wo(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 mr(e,t){if(typeof e!="string"||!nR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function sR(e){if(!Array.isArray(e)||e.length>Mi.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(Fl)}function zm(e){if(typeof e!="string"||e.length===0||e.length>Ee.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 Dl(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Ee.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Ee.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>Ee.maxTextCharacters&&(!r||e.length>Ee.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Ee.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>Ee.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Dl(s,t+1,i,`${n}[${c}]`));return}let a=wo(e,n),o=Object.keys(a);if(o.length>Ee.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Ee.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Ee.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Dl(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function cR(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 lR(e,t,i){let n=wo(e,`Native repair trajectory event ${t+1}`);if(Vm(n,aR,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(cR(n.timestamp),typeof n.type!="string"||!rR.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(zm(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 Dl(n.data,0,r,"Native trajectory event data"),wo(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Ll(e){let t=wo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Fl),n=i.length===Bm.length&&i.every((l,u)=>l===Bm[u]);n||Vm(t,oR,"Native repair trajectory projection");let r=mr(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:mr(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=mr(t.contractHash,"Native repair trajectory contract hash"),s=sR(t.failedAcceptanceIds),c=Cl(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 uR(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 dR(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??qm;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Rl({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<Mi.warningAtConsecutiveFailures?"continue":a<Mi.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function fR(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??qm;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 Wm(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Ee.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=zm(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=lR(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Ee.maxTotalDataNodes||c>Ee.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?mr(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?mr(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Mm)){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=Ll(f[Mm]);if(uR(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),dR(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");fR(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>Mi.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function Jm(e){return Wm(e).history}function Um(e){let t=Wm(e).latestProjection;return t?{...t}:null}var Vi={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:[]},Ml=W("comet-native-runtime:v3:semantic-repair-budget"),hR=[{skillVersion:"2",skillHash:W("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:W("comet-native-runtime:v1")}];function Gm(e){return e.skillVersion===Vi.definition.metadata.version&&e.skillHash===Ml||hR.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}async function yo(e){let i={sequence:(await it(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 xp(e.changeDir,e.run.trajectoryRef,i),i}async function Bl(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:W(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Tp(e.changeDir,e.run.checkpointRef,t),t}function Km(e){return W(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 nv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],gR=new Set(nv),rv=new Set([...nv,"minimum_runtime_version","revision"]),wR=new Set([...rv,"operation"]),yR=512*1024,ql=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),NR=new Set([...ql,"implementationScopeHash","repairScopeHash","repairStagnation"]),Vl=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 vr(e,t){return vR.join($(e,t),"runtime","transition.json")}function bR(e){return`transition-${e}`}async function SR(e,t,i){let n=bR(t);return Mn(e,n,i)}async function Wi(e,t,i,n){let r=await SR(e,t,i);try{return await n()}finally{await Bn(r)}}function bo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Jl(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 No(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function nt(e,t){return Wl(e,t)}function zl(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=>!NR.has(u)),a=[...ql].find(u=>!Object.hasOwn(i,u)),o=ql.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(pr(i.summary,"Native transition journal event summary"),ke(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&&(pr(i.noCodeReason,"Native transition journal event no-code reason"),ke(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")?Ll(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 kR(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 zl({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return zl(e,t)}function Ul(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?kR(e.eventData,e.evidenceHash):zl(e.eventData,e.evidenceHash),r=el(e.nextRun),a=e.previousRun===null?null:el(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function Ym(e,t,i=!1){if(e.skill!==Vi.definition.metadata.name||(i?!Gm(e):e.skillVersion!==Vi.definition.metadata.version||e.skillHash!==Ml)||e.orchestration!==Vi.definition.orchestration.mode||e.pendingRef!==Te.pendingRef||e.trajectoryRef!==Te.trajectoryRef||e.contextRef!==Te.contextRef||e.artifactsRef!==Te.artifactsRef||e.checkpointRef!==Te.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Xm(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 Qm(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 Gl(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Ym(a,"next Run",n||r!==null),Qm(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(Ym(r,"previous Run",!0),Qm(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(!Wl(Xm(r),Xm(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function ER(e,t,i){return W(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function av(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Zm(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Kl(e,t,i,n,r=!1){let a=i.eventData,o=Zm(e),s=Zm(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&&Wl(e.spec_changes,t.spec_changes),l=Km({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=ER(e.name,a.summary,t.spec_changes),l=W(`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 ov(e,t){let i=bo(e);if(Jl(i,wR),i.schema!==oi)throw new Error(`Expected Native transition schema ${oi}`);let n=No(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 ${oi} minimum_runtime_version must be ${3}`);let r=No(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=Ul(i,t),o=dt(i.previousState),s=dt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Kl(o,s,a,i.operation),Gl(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:oi,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 CR(e,t){let i=bo(e);if(Jl(i,gR),i.schema!==Zn)throw new Error(`Expected Native transition schema ${Zn}`);let n=Ul(i,t,!0),r=rr(i.previousState),a=rr(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Kl(r,a,n,av(r,a,n.eventData),!0),Gl(r,a,n,!0),{schema:Zn,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 RR(e,t){let i=bo(e);if(Jl(i,rv),i.schema!==Hi)throw new Error(`Expected Native transition schema ${Hi}`);if(No(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Hi} minimum_runtime_version must be 2`);let r=No(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ul(i,t,!0),o=ar(i.previousState),s=ar(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Kl(o,s,a,av(o,s,a.eventData),!0),Gl(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Hi,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 PR(e,t){let i=bo(e);if(i.schema===oi)return{status:"current",journal:ov(i,t)};if(i.schema===Zn)return{status:"migration-required",journal:CR(i,t)};if(i.schema===Hi)return{status:"migration-required",journal:RR(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function AR(e,t){let i=vr(e,t);await H(e.nativeRoot,i);try{let n=await Ze({root:e.nativeRoot,file:i,maxBytes:yR,label:`Native transition journal ${t}`});return PR(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function zi(e,t){let i=await AR(e,t);if(!i)return null;if(i.status==="migration-required")throw new Vl(t);return i.journal}async function sv(e){if(await ci(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await Xn(e.paths,e.nextState.name);let t={schema:oi,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??pR(),change:e.nextState.name,evidenceHash:e.evidenceHash,createdAt:(e.now??new Date).toISOString(),previousState:e.previousState,nextState:e.nextState,previousRun:e.previousRun,nextRun:e.nextRun,eventData:e.eventData},i=ov(t,t.change),n=vr(e.paths,i.change);if(await H(e.paths.nativeRoot,n),await zi(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await Fe(n,i),i}function ev(e,t){if(nt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(nt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function tv(e,t){if(nt(e,t.nextState))return"next";if(nt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function xR(e){let{journal:t}=e;return cv({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 cv(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function iv(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=xR({sequence:a.index+1,journal:t,type:a.event.type});if(!nt(cv(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 gr(e,t,i){if(await ci(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Xn(e,t);let n=await zi(e,t);if(!n)return null;let r=$(e,t),a=iv(await it(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([qe(r),fe(e,t)]),c=ev(o,n),l=tv(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 tl(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!nt(await qe(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 Di(e,n.nextState,n.previousState.revision);if(!nt(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!nt(await fe(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await zi(e,t);if(!u||!nt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=iv(await it(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await yo({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 yo({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Bl({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([qe(r),fe(e,t)]);ev(p,{...n,previousRun:n.nextRun}),tv(m,{...n,previousState:n.nextState});let h=await zi(e,t);if(!h||!nt(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await mR.rm(vr(e,t),{force:!0}),n.nextState}var TR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function IR(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 lv(e){let i=(e.findings??[]).filter(l=>!$i(l.code)),n=i.find(l=>l.requiresUserDecision),r=i.find(l=>l.repairCommand!==null||TR.test(l.code)),a=i.find(l=>l.code==="repair-iteration-limit"||l.code==="repair-override-exhausted"),o=i.find(l=>l.code==="repair-stagnation-stop"),s=[...new Set(i.map(l=>l.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:s};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(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:s};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:s}:s.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:s}:{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:s};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 c=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>"${c}`,requiresUserDecision:!1,requiredInputs:IR(e.state)}}import wr from"path";var uv=8,_R={"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-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"},"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 jR(e){let t=_R[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"}:$i(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 OR(e,t,i){if(!i.path)return null;let n;if(wr.isAbsolute(i.path)?n=wr.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=wr.resolve($(e,t.name),...i.path.split(/[\\/]/u)):n=wr.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!J(e.projectRoot,n))return null;let r=wr.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function $R(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 dv(e){return e.findings.map(t=>{let i=jR(t.code);return{code:t.code,message:t.message,severity:i.severity,path:OR(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:$R(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 fv(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,uv),truncated:t.length>uv}}import gv from"path";import Ji from"path";var Vt={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Ui=/^[a-f0-9]{64}$/u;function So(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ko(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 qt(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 hv(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Yl(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function HR(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Ji.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Ji.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Xl(e,t){return Ji.join($(e,t),"runtime","checkpoints","progress.json")}function Gi(e,t){return Ji.join($(e,t),"runtime","checkpoint-journal.json")}function Ql(e,t,i){if(!Ui.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Ji.join($(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function DR(e){if(!Ui.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Zl(e,t,i){let n=await Ze({root:e,file:t,maxBytes:Vt.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function FR(e,t){let i=So(e,`checkpoint manifest artifact ${t}`);ko(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=HR(qt(i.path,`checkpoint artifact ${t} path`,4096)),r=Xe(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Ui.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:Yl(i.size,`checkpoint artifact ${t} size`)}}function Eo(e,t){let i=So(e,"Native checkpoint manifest");if(ko(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==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>Vt.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(FR),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=Yl(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>Vt.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 eu(e){return W(JSON.stringify(Eo(e,e.change)))}function tu(e,t){let i=So(e,"Native progress checkpoint");if(ko(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==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=hv(i.previousRevision,"Native checkpoint previousRevision"),a=hv(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=qt(i.manifestHash,"Native checkpoint manifestHash",64);if(!Ui.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=DR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=qt(i.inputHash,"Native checkpoint inputHash",64);if(!Ui.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=qt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Yl(i.artifactCount,"Native checkpoint artifactCount");if(u>Vt.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=qt(i.summary,"Native checkpoint summary"),f=qt(i.nextAction,"Native checkpoint nextAction");if(ke(d)!==d||ke(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:qt(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 LR(e,t){let i=So(e,"Native checkpoint journal");if(ko(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let n=dt(i.previousState),r=dt(i.nextState),a=tu(i.checkpoint,t),o=Eo(i.manifest,t),s=qt(i.inputHash,"Native checkpoint journal inputHash",64),c=W(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Ui.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!==eu(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 MR(e,t,i){let n=Ji.resolve(e.projectRoot,...t.split("/"));if(!J(e.projectRoot,n)||J(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=gc(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await Ze({root:e.projectRoot,file:n,maxBytes:Vt.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 BR(e,t){let i=Xl(e,t);await H(e.nativeRoot,i);try{return tu(await Zl(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function iu(e,t,i){let n=Ql(e,t,i);await H(e.nativeRoot,n);let r=await Zl(e.nativeRoot,n,"Native checkpoint manifest"),a=Eo(r,t);if(nu(e,a),eu(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Co(e,t){let i=Gi(e,t);await H(e.nativeRoot,i);try{let n=LR(await Zl(e.nativeRoot,i,"Native checkpoint journal"),t);return nu(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function pv(e,t,i,n){let r=Eo(i,t);nu(e,r);let a=eu(r),o=Ql(e,t,a);await H(e.nativeRoot,o);try{let s=await iu(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 Fe(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function nu(e,t){for(let i of t.artifacts){let n=gc(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function mv(e,t){let i=tu(t,t.change),n=await iu(e,i.change,i.manifestHash),r=W(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=Xl(e,t.change);await H(e.nativeRoot,a),await Fe(a,i,{containedRoot:e.nativeRoot})}async function vv(e){let t;try{t=await BR(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:Xl(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 iu(e.paths,e.name,t.manifestHash);let a=W(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 MR(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:Ql(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}var wv=240,yv=8,Ro=50;function Nv(e){let t=Array.from(e);return t.length<=wv?e:`${t.slice(0,wv-1).join("")}…`}function qR(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function VR(e){let t=[...new Set(e.map(qR))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,yv),reasonCount:e.length,codesTruncated:t.length>yv};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Ro),reasonsTruncated:e.length>Ro}}}async function bv(e){let t=null;try{let s=await Co(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Gi(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:Gi(e.paths,e.state.name)}}let i=await vv({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=VR(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Vt.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Nv(i.checkpoint.summary),nextAction:Nv(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:gv.relative(e.paths.projectRoot,gv.join($(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:Vt.maxArtifacts}}import{promises as AA}from"node:fs";import Zv from"node:path";import Sv from"node:path";var zR="comet.native.archive-preflight.v1",WR="comet.native.archive-preflight.v1",JR="comet.native.archive-operation.v1",UR=/^[a-f0-9]{64}$/u,kv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Po(e,t){return e<t?-1:e>t?1:0}function KR(e,t){if(typeof e!="string"||!UR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function gt(e,t){return e===null?null:KR(e,t)}function YR(e,t){let i=Sv.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Sv.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 XR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function QR(e,t){if(!kv.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=gt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=gt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=gt(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 ZR(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:gt(e.contractHash,"Native archive contract hash"),acceptanceHash:gt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:gt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:gt(e.reportHash,"Native archive report hash"),envelopeHash:gt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:gt(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 eP(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!GR.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(Po);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function tP(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(Po)}function Ev(e){if(!kv.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(QR).sort((c,l)=>Po(c.capability,l.capability));if(new Set(t.map(c=>c.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(c=>({...c,operationHash:F(JR,c)})),n=ZR(e.evidence),r=[...new Set([...eP(e.findingCodes??[]),...tP({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(Po),a=XR(e.revision),o=YR(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let s={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:o,targetExists:e.targetExists,operations:i,evidence:n,findingCodes:r};return{schema:zR,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,targetRef:o,ready:r.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,findingCodes:r,preflightHash:F(WR,s)}}import{createHash as iP}from"node:crypto";import Cv from"node:path";var nP="comet.native.conflict-radar.v1",ge=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}),rP="comet.native.conflict-radar.v1",aP="comet.native.conflict-radar-signals.v1",oP=/^[a-f0-9]{64}$/u,Av=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sP=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),cP=new Set(["capability","operation","baseHash"]),lP=new Set(["path","kind"]);function Ki(e,t){return e<t?-1:e>t?1:0}function ru(e){return Buffer.byteLength(e,"utf8")}function au(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 ou(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(ru(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function uP(e,t){let i=ou(e,t,ge.maxArtifactPathBytes),n=Cv.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)||Cv.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 xv(e,t){if(typeof e!="string"||!oP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function dP(e,t){let i=au(e,cP,t),n=ou(i.capability,`${t} capability`,ge.maxCapabilityBytes);if(!Av.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:xv(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 fP(e,t){let i=au(e,lP,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:uP(i.path,`${t} path`),kind:i.kind}}function hP(e,t){let i=au(e,sP,`Conflict radar change ${t}`),n=ou(i.name,`Conflict radar change ${t} name`,ge.maxNameBytes);if(!Av.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>ge.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>ge.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>dP(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>Ki(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)=>fP(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>Ki(c.path,l.path)||Ki(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:xv(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function pP(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ge.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(hP).sort((r,a)=>Ki(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)>ge.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>ge.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function mP(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 vP(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 gP(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function wP(e,t){let i=[],n=iP("sha256").update(`${aP}
174
- [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(sr(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ge.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(mP(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=vP(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:gP(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Rv(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function yP(e,t){return Rv(e.classification)-Rv(t.classification)||Ki(e.left,t.left)||Ki(e.right,t.right)}function Pv(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:nP,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 su(e){let t=pP(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(wP(t[s],t[c]));i.sort(yP);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=F(rP,{changes:t,relationships:n}),a=i.slice(0,ge.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Pv(t,i,a,r);for(;a.length>0&&ru(JSON.stringify(o))>ge.maxSerializedBytes;)a=a.slice(0,-1),o=Pv(t,i,a,r);if(ru(JSON.stringify(o))>ge.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as XP}from"node:crypto";import{promises as We}from"node:fs";import rt from"node:path";import Tv from"node:path";var Iv="comet.native.check-receipt.v1",NP="comet.native.check-receipt.v1",Yi="scoped-text-safety",cu=1,Ie=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),bP=/^[a-f0-9]{64}$/u,SP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kP="comet.native.checker-policy.v1",EP="comet.native.check-input.v1",CP=2048,_v=F(kP,{policy:Yi,version:cu,limits:Ie,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),RP=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),jv=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],$v=["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"],PP=new Set($v);function hi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pi(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 wt(e,t){if(typeof e!="string"||!bP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function fi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Hv(e,t){let i=fi(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Ov(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 AP(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>CP||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=Tv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Tv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function xP(e){let t=hi(e,"Native check receipt checker");pi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=hi(t.limits,"Native check receipt limits");if(pi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==Yi||t.version!==cu||t.hash!==_v||i.maxFiles!==Ie.maxFiles||i.maxFileBytes!==Ie.maxFileBytes||i.maxTotalBytes!==Ie.maxTotalBytes||i.maxIssues!==Ie.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:Yi,version:cu,hash:_v,limits:{...Ie}}}function TP(e){let t=hi(e,"Native check receipt contract");return pi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:wt(t.expectedHash,"Native check expected contract hash"),beforeHash:wt(t.beforeHash,"Native check before contract hash"),afterHash:wt(t.afterHash,"Native check after contract hash")}}function IP(e){let t=hi(e,"Native check receipt implementation");return pi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:wt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:wt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:wt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:wt(t.afterSnapshotHash,"Native check after snapshot hash")}}function _P(e){let t=hi(e,"Native check receipt counts");pi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:fi(t.filesSelected,"Native check filesSelected"),filesScanned:fi(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:fi(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:fi(t.bytesScanned,"Native check bytesScanned"),issueCount:fi(t.issueCount,"Native check issueCount"),recordedIssueCount:fi(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Ie.maxFiles||i.bytesScanned>Ie.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Ie.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function jP(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||jv.indexOf(e.kind)-jv.indexOf(t.kind)}function OP(e){if(!Array.isArray(e)||e.length>Ie.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=hi(n,`Native check issue ${r}`);if(pi(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!RP.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:AP(a.path,`Native check issue ${r} path`),line:Hv(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(jP);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function $P(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!PP.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=$v.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 HP(e){return F(EP,e)}function Dv(e){let t=hi(e,"Native check receipt");if(pi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Iv)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!SP.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Hv(t.sourceRevision,"Native check source revision"),n=xP(t.checker),r=TP(t.contract),a=IP(t.implementation),o=HP({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(wt(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=Ov(t.startedAt,"Native check receipt startedAt"),c=Ov(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=_P(t.counts),u=OP(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=$P(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>Ie.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Ie.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:Iv,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=wt(t.receiptHash,"Native check receipt content hash");if(F(NP,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var uu="comet.native.verification-receipt.v3",DP=uu,FP="comet.native.declared-artifacts.v1",LP=/^[a-f0-9]{64}$/u,MP=/^acceptance-[a-f0-9]{64}$/u,BP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qP=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,VP=4096,zP=256,WP=1024;function Xi(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 zt(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 yt(e,t){if(typeof e!="string"||!LP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ze(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=ke(e).trim();if(!i||i.length>VP||i!==e.trim())throw new Error(`${t} is invalid`);return i}function lu(e,t){let i=ze(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 yr(e,t,i=ze,n=!1,r=zP){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 JP(e,t){if(typeof e!="string"||!MP.test(e))throw new Error(`${t} is invalid`);return e}function UP(e){let t=Xi(e,"Native verification receipt bindings");if(zt(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!BP.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:yt(t.contractHash,"Native verification receipt contract hash"),scopeHash:yt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:yt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:yt(t.artifactHash,"Native verification receipt artifact hash")}}function GP(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=qP.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function KP(e,t,i,n){let r=Xi(t,`Native ${e} evidence`);if(e==="automated-check"){if(zt(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=lu(r.startedAt,"Native automated-check start time"),o=lu(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=Xi(r.worktree,"Native automated-check worktree");if(zt(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=Xi(r.afterFence,"Native automated-check after fence");if(zt(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:ze(r.executable,"Native automated-check executable"),args:yr(r.args,"Native automated-check arguments",ze,!0),cwd:ze(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:ze(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:yt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:yt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:yt(r.outputHash,"Native automated-check output hash"),outputSummary:ze(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){zt(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=GP(r.checkReceiptRef);if(yt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:yr(r.subjects,"Native static inspection subjects",ze,n==="required-check"),rule:ze(r.rule,"Native static inspection rule"),resultSummary:ze(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return zt(r,["steps","observations"],"Native manual-evidence evidence"),{steps:yr(r.steps,"Native manual evidence steps"),observations:yr(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function YP(e){let t=Xi(e,"Native verification receipt");if(zt(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=ze(t.actor,"Native verification receipt actor"),o=yr(t.acceptanceIds,"Native receipt acceptance IDs",JP,n==="required-check",WP).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:uu,kind:i,role:n,status:r,bindings:UP(t.bindings),acceptanceIds:o,actor:a,issuedAt:lu(t.issuedAt,"Native verification receipt issue time"),evidence:KP(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Yi||s.actor!==`native-runtime:${Yi}`))throw new Error("Native required check policy identity is invalid");return s}function Fv(e){let t=Xi(e,"Native verification receipt");if(zt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==uu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=YP(n),a=yt(t.receiptHash,"Native verification receipt hash");if(F(DP,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function du(e){return F(FP,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var qv=/^[a-f0-9]{64}$/u,Qi=di,N$=3*Qi;function fu(e,t){let i=rt.relative(e,t);return i===""||!rt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${rt.sep}`)}function QP(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ao(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ae(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Lv(e){let t=await We.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await We.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ZP(e,t){let i=rt.resolve(e),n=rt.resolve(t);if(!fu(i,n))throw new Error("Native evidence path is outside its change");let r=[await Lv(i)],a=i;for(let o of rt.relative(i,n).split(rt.sep).filter(Boolean)){a=rt.join(a,o);let s=await Lv(a);if(!fu(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Mv(e){for(let t of e){let i=await We.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!QP(t,i)||await We.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function eA(e,t,i={}){let n=await ZP(t,rt.dirname(e));await i.afterParentChainCaptured?.();let r=await We.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await We.realpath(e);if(!fu(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await We.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),We.lstat(e),We.realpath(e)]);if(await Mv(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Ao(s,r)||!Ao(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Qi)throw new Error(`Native evidence document exceeds ${Qi} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Qi+1-d,N=await o.read(f,0,Math.min(f.length,v),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>Qi)throw new Error(`Native evidence document exceeds ${Qi} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),We.lstat(e),We.realpath(e)]);if(await Mv(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Ao(s,p)||!Ao(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 Vv(e,t){if(!qv.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function tA(e,t,i,n,r){if(!qv.test(i))throw new Error("Native report evidence hash is invalid");let a=await mi({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"||XP("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 Zi(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 iA(e,t,i,n,r){return rt.join(r??$(e,t),...Vv(i,n).split("/"))}async function mi(e){let t=e.changeDir??$(e.paths,e.name),i=iA(e.paths,e.name,e.kind,e.hash,t);return await H(e.paths.nativeRoot,i),eA(i,t,e.hooks)}function Bv(e,t){return fo(e,t)}function nA(e,t){let i=mo(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function rA(e,t,i){let n=Lm(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function aA(e,t,i){let n=Hl(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function oA(e,t,i,n=!1,r){let a=await hu(e,t,i.implementationScopeRef,void 0,r);if(n&&await tA(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 zv(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 Nr(e,t,i,n,r){let a=Zi(i,"scopes"),o=nA(await mi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Zi(o.baselineProjectionRef,"snapshots"),c=Zi(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([mi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>Bv(d,s)),mi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>Bv(d,c))]);return _m({baseline:l,current:u,scope:o})}async function hu(e,t,i,n,r){return(await Nr(e,t,i,n,r)).scope}async function zv(e,t,i,n,r){let a=Zi(i,"allowances");return rA(await mi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function pu(e,t,i,n,r){let a=Zi(i,"receipts"),o=Fv(await mi({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 br(e,t,i,n,r){let a=Zi(i,"verifications"),o=aA(await mi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await oA(e,t,o,!1,r),o}async function sA(e){try{let t=await qn({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:ge.maxChanges});return await t.verify(),t.entries}catch(t){if(t.code==="ENOENT")return[];throw t}}async function cA(e,t){let i=await fe(e,t),[n,r]=await Promise.all([i.implementation_scope?hu(e,t,i.implementation_scope):null,so(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 lA(e){let i=(await sA(e)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();return Promise.all(i.map(n=>cA(e,n)))}async function xo(e,t){let i=await lA(e);su(i);let n=i.find(o=>o.name===t);if(!n)throw new Error(`Native conflict target is not visible: ${t}`);let r=0,a=0;for(let o of i){if(o.name===t)continue;let s=su([n,o]).relationships[0];s.classification==="definite-conflict"&&(r+=1),s.classification==="possible-overlap"&&(a+=1)}return{definiteConflictCount:r,possibleOverlapCount:a,findingCodes:[...r>0?["native-change-conflict"]:[],...a>0?["native-change-overlap"]:[]]}}import{execFile as yA,spawn as X$}from"node:child_process";import{promisify as NA}from"node:util";import{promises as uA}from"fs";async function Wv(e,t,i){let n=await Co(e,t);if(!n)return null;if(await pv(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Di(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await mv(e,n.checkpoint),await i?.afterProgressWritten?.(n),await uA.rm(Gi(e,t),{force:!0}),n}async function Sr(e,t){await gr(e,t),await Wv(e,t)}import{constants as mu,promises as _e}from"node:fs";import vi from"node:path";var dA=/^[a-f0-9]{64}$/u,fA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,kr=512*1024;function hA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function To(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ae(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function pA(e,t){let i=vi.resolve(e),n=vi.resolve(t);if(!J(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...vi.relative(i,n).split(vi.sep).filter(Boolean)]){o&&(a=vi.join(a,o));let s=await _e.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await _e.realpath(a);if(r.length>0&&!J(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 Jv(e){for(let t of e){let i=await _e.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!hA(t,i)||await _e.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function mA(e){if(!dA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function vA(e){let t=fA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function gA(e,t,i){return vi.join($(e,t),...mA(i).split("/"))}async function wA(e,t,i){let n=await pA(i,vi.dirname(e)),r=await _e.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>kr)throw new Error(`Native check receipt exceeds ${kr} bytes`);let[a,o]=await Promise.all([_e.realpath(t),_e.realpath(e)]);if(!J(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":mu.O_RDONLY|mu.O_NOFOLLOW|mu.O_NONBLOCK,c=await _e.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(),_e.lstat(e),_e.realpath(e)]);if(await Jv(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!To(r,l)||!To(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let k=kr+1-p,S=await c.read(m,0,Math.min(m.length,k),null);if(S.bytesRead===0)break;if(p+=S.bytesRead,p>kr)throw new Error(`Native check receipt exceeds ${kr} bytes`);f.push(Buffer.from(m.subarray(0,S.bytesRead)))}let[h,v,N]=await Promise.all([c.stat(),_e.lstat(e),_e.realpath(e)]);if(await Jv(n),!v.isFile()||v.isSymbolicLink()||N!==o||!J(a,N)||!To(l,h)||!To(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 Uv(e,t,i){let n=vA(i),r=$(e,t),a=gA(e,t,n);await H(e.nativeRoot,a);let o=Dv(await wA(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var dH=64*1024;var fH=3600*1e3;var hH=NA(yA);var pH=["$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 bA=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Gv(e,t){let i=[];for(let n of bA){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 Kv(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Uv(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 Wt=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 SA(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 kA(e){let t=SA(e.bundle.baseline),i=await Xc(e.paths,t,{origin:"explicit",now:e.now});return _l({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function Xv(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Nr(e.paths,e.state.name,e.state.implementation_scope),i=await Li({changeDir:$(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await kA({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 Qv(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Xv(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 EA(e){let t=await oe({root:$(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:am(t.text)}}function CA(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 RA(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:du(e.implementationScope.scope.declaredArtifacts)}}async function Yv(e){let t=await pu(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Gv(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 Wt([{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 Kv({paths:e.paths,state:e.state,receipt:t});if(r){let a=CA({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 PA(e){let t=RA({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Yv({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Wt)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 Yv({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Wt)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 Wt(i)}function vu(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function gu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:vu(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Xv(e),br(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:vu(e.state.verification_result,"stale"),envelope:null};let n=await EA({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 PA({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{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:vu(e.state.verification_result,"invalid"),envelope:null}}}function xA(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function eg(e){try{return await AA.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function TA(e,t){try{return(await oe({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function IA(e,t,i){let n=Lt(e,i.capability);if(!J(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=Zv.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await TA(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await oe({root:$(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 _A(e,t){return eg(vr(e,t))}async function wu(e){let t=e.now??new Date,i=await fe(e.paths,e.name),n=await _t(e.paths.projectRoot),r=xA(i.name,t),a=Zv.resolve(e.paths.nativeRoot,...r.split("/"));if(!J(e.paths.nativeRoot,a))throw new Error("Native archive target escapes its root");let[o,s,c,l,u,d,f]=await Promise.all([Promise.all(i.spec_changes.map(p=>IA(e.paths,i.name,p))),gu({paths:e.paths,state:i,now:t}),xo(e.paths,i.name),ci(e.paths,i.name),fl(e.paths,i.name),_A(e.paths,i.name),eg(a)]);return Ev({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:l||u||d,targetRef:r,targetExists:f,specs:o,evidence:s.evidence,findingCodes:[...s.findingCodes,...c.findingCodes]})}async function jA(e,t){let i=$(e,t.name),n=await qe(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 ao(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 it(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function OA(e,t){let i=await jA(e,t);return{committed:i,latest:Um(i),history:Jm(i)}}async function tg(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await OA(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 N1=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function $A(e){try{return(await mm(e))?.change??null}catch{return null}}function HA(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 DA(e,t){let i=$(e,t.name),n=[...(await ml(i,t.brief)).findings,...(await Up(e,t)).findings,...await vm(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await to(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 Np(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 Li({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 zi(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 vl(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 yu(e,t,i){let n=await $A(e)===t,r;try{let w=await hl(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 bv({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await tg(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 Li({changeDir:$(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 br(e,r.name,r.verification_evidence);for(let _ of E.acceptanceTrace.entries)g.set(_.acceptanceId,_.status==="failed"?"failed":_.status==="missing"?"missing":"satisfied")}c=em({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=[];try{let w=await xo(e,r.name);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 so(e,r.name);if(w){let g=await $p({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-inspection-unavailable",message:"Native workspace advisory could not be recomputed safely"})}let d=[],f=!1;if(r.phase==="verify"){let w=await Qv({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 wu({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 DA(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,g,E)=>E.findIndex(_=>_.code===w.code&&_.path===w.path)===g),v=dv({paths:e,state:r,findings:h}),N=v.filter(w=>!$i(w.code)),k=r.phase==="archive"&&p?.ready===!0&&N.length===0,S=f||r.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=v.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"),C=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:b||C?null:HA(r,k,S,i?.clarificationMode),archiveReady:k,inspection:a.inspection,findingSummary:fv(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:lv({state:r,findings:v,archiveReady:k,evidenceRetreat:S,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:Ro,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}:{}}}import{promises as ig}from"fs";import ng from"path";var rg=li.maxSpecs*4;async function Nu(e){try{return await Vn(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function ag(e,t){let i=ng.join($(e,t),"specs"),n;try{n=await za({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await ig.opendir(i);try{for await(let s of o){if(a+=1,a>rg)throw new Error(`Native proposed specs directory exceeds ${rg} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;ut(s.name);let c=ng.join(i,s.name,"spec.md");await H(e.nativeRoot,c);let l;try{l=await ig.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>li.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function FA(e,t){let i=await ag(e,t.name),n=[];for(let r of i){if(t.spec_changes.find(c=>c.capability===r)?.operation==="remove")throw new Error(`Capability ${r} has both a proposed spec and a remove intent`);let o=Lt(e,r);await H(e.nativeRoot,o);let s=await Nu(o);n.push({capability:r,operation:s===null?"create":"replace",source:`specs/${r}/spec.md`,base_hash:s})}for(let r of t.spec_changes){if(r.operation!=="remove"||i.includes(r.capability))continue;let a=Lt(e,r.capability);await H(e.nativeRoot,a);let o=await Nu(a);o!==null&&n.push({...r,base_hash:o})}return n.sort((r,a)=>r.capability.localeCompare(a.capability))}async function og(e){ut(e.name);let t=ke(e.summary);return pr(t,"Spec rebase summary"),et(e.paths,`rebase specs for ${e.name}`,()=>Wi(e.paths,e.name,`rebase specs for ${e.name}`,async()=>{await Sr(e.paths,e.name);let i=await fe(e.paths,e.name);if(i.phase==="shape")throw new Error("Shape spec metadata is refreshed by the next command");if(i.archived)throw new Error(`Native change ${i.name} is already archived`);let n=$(e.paths,e.name),r=await qe(n);if(!r||r.runId!==i.run_id||r.currentStep!==i.phase||r.pending)throw new Error(`Native Run state is missing or inconsistent for ${i.name}`);let a=await FA(e.paths,i),o={...i,revision:i.revision+1,phase:"build",spec_changes:a,verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},s={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},c=W(JSON.stringify({operation:"spec-rebase",change:i.name,summary:t,specChanges:a}));await sv({paths:e.paths,previousState:i,nextState:o,previousRun:r,nextRun:s,evidenceHash:c,eventData:{previousPhase:i.phase,nextPhase:"build",evidenceHash:c,summary:t,artifacts:[],noCodeReason:null,verificationResult:null},operation:"spec-rebase",now:e.now,transitionId:e.transitionId});let l=await gr(e.paths,e.name);if(!l)throw new Error("Native spec rebase journal disappeared before completion");return l}))}async function sg(e,t,i){return ut(t),ut(i),et(e,`remove spec ${i} from ${t}`,()=>Wi(e,t,`remove spec ${i} from ${t}`,async()=>(await Sr(e,t),LA(e,t,i))))}async function LA(e,t,i){let n=await fe(e,t);if(n.phase==="archive"||n.archived)throw new Error(`Native change ${t} no longer accepts spec changes`);if((await ag(e,t)).includes(i))throw new Error(`Capability ${i} has both a proposed spec and a remove intent`);if(n.spec_changes.find(l=>l.capability===i)?.operation==="remove")return n;let o=Lt(e,i);await H(e.nativeRoot,o);let s=await Nu(o);if(s===null)throw new Error(`Canonical spec is missing: ${i}`);let c={...n,spec_changes:[...n.spec_changes.filter(l=>l.capability!==i),{capability:i,operation:"remove",base_hash:s}].sort((l,u)=>l.capability.localeCompare(u.capability))};return await Di(e,c,n.revision),c}import qA from"path";var K1={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var rD=16*1024*1024,aD=256*1024,oD=16*1024;var zD=16*1024*1024,Io=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"},_o=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var ZD=10*1024*1024,Je=class extends Error{};function cg(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new Je(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function jo(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Je(`${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 Je(`${t} requires a value`);return e.splice(n,2),r}function bu(e){if(e.length>0)throw new Je(`Unexpected argument: ${e[0]}`)}function Er(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Je(`${t} is required`);return i}async function lg(e){return e?qA.resolve(e):Da(process.cwd())}async function Su(e){let t=await Th({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ku(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
175
- `}}function ug(e,t){if(t instanceof Je)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Io)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 _o)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof tr)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 co)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 Wt)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",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 dg(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}})+`
176
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function fg(e,t){let i=Er(e,"spec subcommand");if(i==="remove"){let n=Er(e,"change name"),r=Er(e,"capability");bu(e);let{config:a,paths:o}=await Su(t),s=await sg(o,n,r),c=await yu(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return ku("spec remove",{...s,continuation:c.continuation},`Marked Native capability ${r} for removal in ${n}
177
- `)}if(i==="rebase"){let n=Er(e,"change name"),r=jo(e,"--summary");if(!r)throw new Je("--summary is required");bu(e);let{config:a,paths:o}=await Su(t),s=await og({paths:o,name:n,summary:r}),c=await yu(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return ku("spec rebase",{...s,continuation:c.continuation},`Rebased Native specs for ${n}
178
- `)}throw new Je(`Unknown spec command: ${i}`)}function VA(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}})+`
179
- `}}async function hg(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{cg(r,"--json"),s=jo(r,"--project-root");let u=[...r,...a],d=await lg(s);c=await t(u,d)}catch(u){c=ug(e,u)}let l=o?VA(c):dg(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
165
+ `,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=Tl(l,t);else if(i)um(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=Tl(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!um(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 NC(e){return[...qi(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Il(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function bC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function jl(e,t,i,n=[]){let r=Il(i),a=t.replaceAll("\\","/").trim(),o=n.map(Il);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(dC,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function Ol(e,t){let i=new Set;for(let n of e){if(i.has(n.id))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(n.id)}return e}function kC(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of qi(e)){r=s+1;let c=o?_l(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 fm(e,t="brief.md",i=pr.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=kC(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of qi(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 qi(e)){if(u<n.start||u>=n.end)continue;let d=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;d&&d[1].length===r?(s(),o=[d[2]]):o!==null&&o.push(c)}return s(),Ol(a.map(c=>jl("brief-example",t,c.join(`
166
+ `))),"Brief")}function hm(e,t="spec.md",i=pr.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(jl("spec-scenario",t,[a.title,...a.body].join(`
167
+ `),a.context)),a=null}};for(let{line:s,body:c}of qi(e)){let l=c?_l(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=Il(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:d,body:[],context:r.map(f=>f.text)}}else if(l){for(a!==null&&l.level<=a.level?o():a!==null&&a.body.push(s);r.at(-1)&&r.at(-1).level>=l.level;)r.pop();r.push(l)}else a!==null&&c&&a.body.push(s)}return o(),Ol(n,"Specification")}function pm(e,t="spec.md",i=pr.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(jl("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 qi(e)){let d=u?_l(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||Tl(l,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){s();continue}let p=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(p){s(),o={parts:[p[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(f)){s(),o={parts:[f],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[f],context:r.map(m=>m.text)}:o.parts.push(f)}return s(),Ol(n,"Specification mandatory requirements")}function SC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||bC(i)||am.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=am.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(!pC.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function EC(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=>!hC.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function mm(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=EC(i,n),a=r.acceptance_id;if(typeof a!="string"||!fC.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 SC(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 vm(e){let t=NC(e);if(t.some(({line:l,body:u})=>!u&&(l===om||l===sm)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===om?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===sm?[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(`
168
+ `).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=mm(o),c=CC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function CC(e){let t=mm([...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 gm from"node:path";var RC="comet.native.contract.v1",PC="comet.native.acceptance-set.v1",wm=/^[a-f0-9]{64}$/u,mr={maxAcceptanceCriteria:pr.maxCriteria};function ym(e,t){let i=gm.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})||gm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Nm(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
169
+ `))}function AC(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(wm))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(wm))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=ym(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Nm(e.markdown)},markdown:e.markdown}}function xC(e,t){return bm(e.id,t.id)}function bm(e,t){return e<t?-1:e>t?1:0}function km(e){let t=ym(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(AC).sort((d,f)=>bm(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=fm(e.briefMarkdown,t,mr.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...hm(f,d.source,mr.maxAcceptanceCriteria-a.length)),a.push(...pm(f,d.source,mr.maxAcceptanceCriteria-a.length)));if(a.sort(xC),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>mr.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${mr.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:Nm(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(PC,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(RC,u)}}var fi={maxSpecs:64,maxFileBytes:$n,maxTotalBytes:4*1024*1024};async function Vi(e){if(e.specChanges.length>fi.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ce({root:e.changeDir,ref:e.briefRef,maxBytes:fi.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 ce({root:e.changeDir,ref:r.source,maxBytes:fi.maxFileBytes});if(i+=a.size,i>fi.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:km({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import TC from"path";var $l="comet.selection.v2",IC=16*1024;function Em(e){return TC.join(e,".comet","current-change.json")}function _C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Sm(e){return e===null||typeof e=="string"}function jC(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(!_C(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&&!Sm(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:$l,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==$l)throw new Error(`current change selection schema must be ${$l}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Sm(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 Cm(e){let t;try{let n=Em(e),{bytes:r}=await ni(n,IC,{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",...jC(t)}}var n0=16*1024;async function Rm(e){let t=await Cm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(dt(t.selection.change),t.selection)}import OC from"path";function Hl(e,t){return OC.resolve(e,...t.split(/[\\/]/u))}async function Pm(e,t){let i=[],n=O(e,t.name),r=Hl(n,_e.stateRef),a;try{a=await We(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=Hl(n,a.trajectoryRef),s=await vl(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 nt(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=Hl(n,a.checkpointRef);try{let u=await ho(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import{randomUUID as TR}from"crypto";import{promises as IR}from"fs";import _R from"path";import{isDeepStrictEqual as nu}from"util";var $C=/\b(Bearer|Basic)\s+[^\s"']+/giu,HC=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,FC=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,DC=/\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,LC=/("(?:[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,MC=/(["'])((?:[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,BC=/\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 Ce(e){return e.replace($C,"$1 [REDACTED]").replace(HC,"[REDACTED PRIVATE KEY]").replace(FC,"$1[REDACTED]@").replace(DC,"[REDACTED TOKEN]").replace(LC,'$1"[REDACTED]"').replace(MC,"$1$2$1$3$4[REDACTED]$4").replace(BC,"$1$2[REDACTED]")}var Wi={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var qC=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function VC(e,t){return e<t?-1:e>t?1:0}function WC(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"||!qC.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(VC)}function Fl(e=[]){return WC(e,"Native repair failed check IDs",Wi.maxFailedCheckIds,!0)}function Am(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function zC(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Am(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Am(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Dl(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(zC(n,a))break;i+=1,n=a}return i}import Wm from"node:path";import{createHash as $m}from"node:crypto";import xm from"path";var Ll="comet.native.implementation-scope.v2",Hm="comet.native.content-snapshot-projection.v1",vr="comet.native.content-snapshot-projection.v1",Fm="comet.native.implementation-scope.v2",JC="comet.native.unresolved-scope-id.v1",GC="comet.native.scope-detail-overflow.v1",UC="comet.native.snapshot-projection-overflow.v2",Vl=/^[a-f0-9]{64}$/u,pi=1024*1024,KC=128,YC=128;function ue(e,t){return e<t?-1:e>t?1:0}function Ml(e){if(!Vl.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function XC(e,t){return e===t?0:e===null?-1:t===null?1:ue(e,t)}function Vt(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=xm.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||xm.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Dm(e,t){return e==="."?e:Vt(e,t)}function zi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function QC(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:Vt(e.path,`${t} path`),hash:e.hash,size:zi(e.size,`${t} size`),type:"file"}}function ZC(e,t){return{path:Dm(e.path,`${t} path`),size:e.size===null?null:zi(e.size,`${t} size`),type:e.type,reason:e.reason}}function eR(e,t){return ue(e.path,t.path)||ue(e.hash,t.hash)||e.size-t.size}function tR(e,t){return ue(e.path,t.path)||ue(e.reason,t.reason)||ue(e.type,t.type)||(e.size??-1)-(t.size??-1)}function gr(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
170
+ `,"utf8")}function qt(e,t,i){let n=`${t}
171
+ ${hr(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function iR(e){if(gr(e)<=pi)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=$m("sha256");a.update(`${UC}
172
+ `),e.omissionOverflow&&qt(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,qt(a,"omission",f)},s=f=>{n+=1,r+=1,qt(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(;gr(u)>pi;){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 Bl(e){let t=ai(e),i=t.entries.map((r,a)=>QC(r,`Snapshot entry ${a}`));if(i.sort(eR),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)=>ZC(r,`Snapshot omission ${a}`));return n.sort(tR),iR({schema:Hm,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:n,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Eo(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:Vt(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)=>ue(i.path,n.path)||ue(i.kind,n.kind))}function Co(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Tm(e){return e?{hash:e.hash,size:e.size}:null}function Lm(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:ue(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:Tm(c),after:Tm(l)})}}function nR(e,t){return{...e,attributedTo:t.filter(i=>Co(i,e.path))}}function pt(e,t){return{id:`scope:${D(JC,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function rR(e,t){let i=t.omitted.map(n=>pt({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(pt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(pt({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 Im(e,t){return rR(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function ql(e,t){return ue(e.kind,t.kind)||ue(e.source,t.source)||XC(e.path,t.path)||ue(e.id,t.id)}function aR(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(ql)}function oR(e){return[...new Set(e.map((t,i)=>Vt(t,`Git path ${i}`)))].sort(ue)}function Mm(e){if(typeof e.contractHash!="string"||!Vl.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Eo(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:oR(e.gitChangedPaths)}}}function sR(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Lm(e,t,d=>{let f=i.some(p=>Co(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<KC){let p=nR(d,i),m=gr(p);s+m<=pi?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function Bm(e,t){return pt({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 cR(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:zi(Number(t[1]),"Scope overflow change count"),unresolved:zi(Number(t[2]),"Scope overflow unresolved count"),unattributed:zi(Number(t[3]),"Scope overflow unattributed count")},n=hi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Bm(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function lR(e){let t=$m("sha256");t.update(`${GC}
173
+ `);let i=0;Lm(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){qt(t,"change",r);let a=0;for(let o of e.declaredArtifacts)Co(o,r.path)&&(a+=1,qt(t,"change-attribution",o));qt(t,"change-end",{attributionCount:a}),a===0&&qt(t,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)n>=e.detailedOmissionCount&&qt(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function qm(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=sR(e,t,r,i.gitChangedPaths),s=D(vr,e),c=D(vr,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let v of w.omitted){if(l.length>=YC)break;l.push(pt({kind:"snapshot-omission",source:y,path:v.path,evidence:{reason:v.reason,size:v.size,type:v.type}},`${y} snapshot omitted ${v.path}: ${v.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Im("baseline",e),...Im("current",t),...o.totalChanges===0&&a===null?[pt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(i.gitChangedPaths===void 0)return;let y=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>y.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!y.has(w))}},p=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),v=w.filter(Ye=>Ye.attributedTo.length===0),E=o.totalChanges-w.length,I=o.totalUnattributed-v.length,U=u-y.detailedOmissionCount,q=I+U,J=[...v.map(Ye=>pt({kind:"unattributed-change",source:"implementation-scope",path:Ye.path,evidence:{after:Ye.after,before:Ye.before,changeKind:Ye.kind}},`Changed path is not covered by a declared artifact: ${Ye.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||q>0?[Bm(y.overflowHash,{changes:E,unattributed:I,unresolved:q})]:[]],K=aR(J),Ke=y.includeGitAdvisory?f():void 0;return{schema:Ll,contractHash:n,baselineProjectionRef:Ml(s),baselineProjectionHash:s,currentProjectionRef:Ml(c),currentProjectionHash:c,complete:K.length===0,declaredArtifacts:r,changes:w,unattributed:v,unresolvedScopes:K,noCodeReason:a,...Ke?{gitAdvisory:Ke}:{}}},m=o.candidates.length,h=l.length,g=i.gitChangedPaths!==void 0,S="0".repeat(64);for(;;){let y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:g,overflowHash:S});if(gr({...y,scopeHash:S})<=pi)break;if(g){g=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>m||u>h?lR({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):S,b=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:g,overflowHash:k}),C={...b,scopeHash:D(Fm,b)};if(gr(C)>pi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return C}function Wl(e){let t=Bl(e.baseline),i=Bl(e.current),n=Mm(e);return{authority:n,baseline:t,current:i,scope:qm(t,i,n)}}var uR=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function mt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vt(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 hi(e,t){if(typeof e!="string"||!Vl.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _m(e,t,i){let n=Ml(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function So(e,t){let i=mt(e,"Native snapshot projection");if(vt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Hm)throw new Error("Native snapshot projection schema is invalid");let n=ai({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=Bl(n);if(D(vr,i)!==D(vr,r))throw new Error("Native snapshot projection is not canonical");let a=D(vr,r);if(t!==void 0&&hi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function zl(e,t){let i=mt(e,`Declared artifact ${t}`);if(vt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Vt(i.path,`Declared artifact ${t} path`),kind:i.kind}}function jm(e,t){if(e===null)return null;let i=mt(e,t);return vt(i,["hash","size"],[],t),{hash:hi(i.hash,`${t} hash`),size:zi(i.size,`${t} size`)}}function Om(e,t){let i=mt(e,`Implementation change ${t}`);if(vt(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(zl),r=Eo(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=jm(i.before,`Implementation change ${t} before`),o=jm(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Vt(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function dR(e,t){let i=mt(e,`Unresolved scope ${t}`);vt(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"?Dm(i.path,`Unresolved scope ${t} path`):Vt(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function ko(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)=>Vt(r,`${t} ${a}`)),n=[...new Set(i)].sort(ue);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function Ro(e){let t=mt(e,"Native implementation scope"),i=[...uR].filter(w=>w!=="gitAdvisory");if(vt(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==Ll)throw new Error("Native implementation scope schema is invalid");let n=hi(t.contractHash,"Implementation scope contractHash"),r=hi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_m(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=hi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_m(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(zl);if(JSON.stringify(c)!==JSON.stringify(Eo(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Om),u=[...l].sort((w,v)=>ue(w.path,v.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(v=>!d.has(`${v.kind}:${v.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(v=>Co(v,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Om),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(dR),h=m.filter(w=>w.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=h[0]===void 0?null:cR(h[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...p.map(w=>pt({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&S===null?[pt({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(ql))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(N.sort(ql))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=mt(t.gitAdvisory,"Implementation scope Git advisory");if(vt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let v=ko(w.changedPaths,"Git changed paths"),E=ko(w.pathsPresentInSnapshotChanges,"Git present paths"),I=ko(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),U=[...E,...I].sort(ue),q=new Set(l.map(J=>J.path));if(JSON.stringify(U)!==JSON.stringify(v)||(g?.changes??0)===0&&E.some(J=>!q.has(J))||I.some(J=>q.has(J)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:v,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:I}}let C={schema:Ll,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...b?{gitAdvisory:b}:{}},y=hi(t.scopeHash,"Implementation scope scopeHash");if(D(Fm,C)!==y)throw new Error("Implementation scope content hash mismatch");return{...C,scopeHash:y}}function fR(e){let t=mt(e,"Native implementation scope authority");if(vt(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(zl);if(JSON.stringify(i)!==JSON.stringify(Eo(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=ko(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Mm({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 wr(e){let t=mt(e,"Native implementation scope bundle");vt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=fR(t.authority),n=So(t.baseline),r=So(t.current),a=Ro(t.scope),o=qm(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 Vm(e){let t=Ro(e.scope);return wr({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}var Jm=/^[a-f0-9]{64}$/u;var hR="comet.native.acceptance-trace.v2",pR="comet.native.partial-allowance.v1",mR="comet.native.verification-evidence.v2";function gt(e,t){if(!Jm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Gm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Um(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 Jl(e,t,i=2e3){let n=Ce(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function yr(e,t){let i=Wm.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})||Wm.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function vR(e,t,i){let n=yr(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Ze(n),a=n.toLowerCase(),o=i?yr(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 Gl(e){let t=yr(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 Ji(e,t){return e<t?-1:e>t?1:0}function Po(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 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 Km(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 zm(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 gR(e){let t=Po(e,"Native acceptance trace");if(Ao(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"||!Jm.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=yr(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=Po(o,`Native acceptance trace entry ${s}`);if(Ao(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=>Gl(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ji))||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:yr(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Jl(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>Ji(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=gt(t.traceHash,"Native acceptance trace hash");if(D(hR,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Ym(e){let t=Po(e,"Native partial allowance");if(Ao(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(Ji))||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:Um(t.change),scopeHash:gt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Jl(t.reason,"Partial allowance reason"),confirmedSummary:Jl(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Gm(t.sourceRevision),confirmedAt:Km(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=gt(t.allowanceHash,"Native partial allowance hash");if(D(pR,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Ul(e){let t=Po(e,"Native verification evidence");if(Ao(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=gt(t.implementationScopeHash,"Native verification implementation scope hash"),n=gR(t.acceptanceTrace),r=gt(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:gt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Gl(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Ji)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(Ji);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=>Gl(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Ji)))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:Um(t.change),sourceRevision:Gm(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:gt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:zm(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:vR(t.reportRef,"Native verification report ref"),reportHash:gt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:zm(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Km(t.createdAt,"Native verification timestamp")},d=gt(t.envelopeHash,"Native verification envelope hash");if(D(mR,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Nr(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 Xm="repairStagnation",Re={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},yR=/^[a-f0-9]{64}$/u;var NR=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),bR=["data","runId","sequence","timestamp","type"],Qm=["disposition","overrideSummaryHash","signatureHash"],kR=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Zm=12;function Yl(e,t){return e<t?-1:e>t?1:0}function ev(e,t,i){let n=Object.keys(e).sort(Yl);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function xo(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 br(e,t){if(typeof e!="string"||!yR.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function SR(e){if(!Array.isArray(e)||e.length>Wi.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(Yl)}function tv(e){if(typeof e!="string"||e.length===0||e.length>Re.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Kl(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Re.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Re.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${n} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Re.maxTextCharacters&&(!r||e.length>Re.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Re.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${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>Re.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Kl(s,t+1,i,`${n}[${c}]`));return}let a=xo(e,n),o=Object.keys(a);if(o.length>Re.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Re.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Re.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Kl(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function ER(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 CR(e,t,i){let n=xo(e,`Native repair trajectory event ${t+1}`);if(ev(n,bR,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(ER(n.timestamp),typeof n.type!="string"||!NR.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(tv(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 Kl(n.data,0,r,"Native trajectory event data"),xo(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Xl(e){let t=xo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Yl),n=i.length===Qm.length&&i.every((l,u)=>l===Qm[u]);n||ev(t,kR,"Native repair trajectory projection");let r=br(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:br(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=br(t.contractHash,"Native repair trajectory contract hash"),s=SR(t.failedAcceptanceIds),c=Fl(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function RR(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 PR(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Zm;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Dl({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<Wi.warningAtConsecutiveFailures?"continue":a<Wi.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function AR(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Zm;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 iv(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Re.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=tv(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=CR(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Re.maxTotalDataNodes||c>Re.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?br(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?br(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Xm)){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=Xl(f[Xm]);if(RR(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),PR(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");AR(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>Wi.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function nv(e){return iv(e).history}function rv(e){let t=iv(e).latestProjection;return t?{...t}:null}var Gi={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:[]},Ql=W("comet-native-runtime:v3:semantic-repair-budget"),xR=[{skillVersion:"2",skillHash:W("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:W("comet-native-runtime:v1")}];function av(e){return e.skillVersion===Gi.definition.metadata.version&&e.skillHash===Ql||xR.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}async function To(e){let i={sequence:(await nt(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 Hp(e.changeDir,e.run.trajectoryRef,i),i}async function Zl(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:W(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Fp(e.changeDir,e.run.checkpointRef,t),t}function ov(e){return W(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 pv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],jR=new Set(pv),mv=new Set([...pv,"minimum_runtime_version","revision"]),OR=new Set([...mv,"operation"]),$R=512*1024,eu=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),HR=new Set([...eu,"implementationScopeHash","repairScopeHash","repairStagnation"]),tu=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 kr(e,t){return _R.join(O(e,t),"runtime","transition.json")}function FR(e){return`transition-${e}`}async function DR(e,t,i){let n=FR(t);return Jn(e,n,i)}async function Ki(e,t,i,n){let r=await DR(e,t,i);try{return await n()}finally{await Gn(r)}}function _o(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function ru(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 Io(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rt(e,t){return nu(e,t)}function iu(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=>!HR.has(u)),a=[...eu].find(u=>!Object.hasOwn(i,u)),o=eu.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(Nr(i.summary,"Native transition journal event summary"),Ce(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&&(Nr(i.noCodeReason,"Native transition journal event no-code reason"),Ce(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")?Xl(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 LR(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 iu({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return iu(e,t)}function au(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?LR(e.eventData,e.evidenceHash):iu(e.eventData,e.evidenceHash),r=dl(e.nextRun),a=e.previousRun===null?null:dl(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function sv(e,t,i=!1){if(e.skill!==Gi.definition.metadata.name||(i?!av(e):e.skillVersion!==Gi.definition.metadata.version||e.skillHash!==Ql)||e.orchestration!==Gi.definition.orchestration.mode||e.pendingRef!==_e.pendingRef||e.trajectoryRef!==_e.trajectoryRef||e.contextRef!==_e.contextRef||e.artifactsRef!==_e.artifactsRef||e.checkpointRef!==_e.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function cv(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 lv(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 ou(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(sv(a,"next Run",n||r!==null),lv(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(sv(r,"previous Run",!0),lv(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(!nu(cv(r),cv(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function MR(e,t,i){return W(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function vv(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function uv(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function su(e,t,i,n,r=!1){let a=i.eventData,o=uv(e),s=uv(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&&nu(e.spec_changes,t.spec_changes),l=ov({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=MR(e.name,a.summary,t.spec_changes),l=W(`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 gv(e,t){let i=_o(e);if(ru(i,OR),i.schema!==li)throw new Error(`Expected Native transition schema ${li}`);let n=Io(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 ${li} minimum_runtime_version must be ${3}`);let r=Io(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=au(i,t),o=ft(i.previousState),s=ft(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(su(o,s,a,i.operation),ou(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:li,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 BR(e,t){let i=_o(e);if(ru(i,jR),i.schema!==ar)throw new Error(`Expected Native transition schema ${ar}`);let n=au(i,t,!0),r=ur(i.previousState),a=ur(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return su(r,a,n,vv(r,a,n.eventData),!0),ou(r,a,n,!0),{schema:ar,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 qR(e,t){let i=_o(e);if(ru(i,mv),i.schema!==Mi)throw new Error(`Expected Native transition schema ${Mi}`);if(Io(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Mi} minimum_runtime_version must be 2`);let r=Io(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=au(i,t,!0),o=dr(i.previousState),s=dr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(su(o,s,a,vv(o,s,a.eventData),!0),ou(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Mi,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 VR(e,t){let i=_o(e);if(i.schema===li)return{status:"current",journal:gv(i,t)};if(i.schema===ar)return{status:"migration-required",journal:BR(i,t)};if(i.schema===Mi)return{status:"migration-required",journal:qR(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function WR(e,t){let i=kr(e,t);await $(e.nativeRoot,i);try{let n=await tt({root:e.nativeRoot,file:i,maxBytes:$R,label:`Native transition journal ${t}`});return VR(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ui(e,t){let i=await WR(e,t);if(!i)return null;if(i.status==="migration-required")throw new tu(t);return i.journal}async function wv(e){if(await di(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await nr(e.paths,e.nextState.name);let t={schema:li,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??TR(),change:e.nextState.name,evidenceHash:e.evidenceHash,createdAt:(e.now??new Date).toISOString(),previousState:e.previousState,nextState:e.nextState,previousRun:e.previousRun,nextRun:e.nextRun,eventData:e.eventData},i=gv(t,t.change),n=kr(e.paths,i.change);if(await $(e.paths.nativeRoot,n),await Ui(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await Le(n,i),i}function dv(e,t){if(rt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(rt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function fv(e,t){if(rt(e,t.nextState))return"next";if(rt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function zR(e){let{journal:t}=e;return yv({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 yv(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function hv(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=zR({sequence:a.index+1,journal:t,type:a.event.type});if(!rt(yv(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 Sr(e,t,i){if(await di(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await nr(e,t);let n=await Ui(e,t);if(!n)return null;let r=O(e,t),a=hv(await nt(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([We(r),me(e,t)]),c=dv(o,n),l=fv(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 fl(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!rt(await We(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let g=await Bi(e,n.nextState,n.previousState.revision);if(!rt(g,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!rt(await me(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await Ui(e,t);if(!u||!rt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=hv(await nt(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await To({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 To({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Zl({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([We(r),me(e,t)]);dv(p,{...n,previousRun:n.nextRun}),fv(m,{...n,previousState:n.nextState});let h=await Ui(e,t);if(!h||!rt(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await IR.rm(kr(e,t),{force:!0}),n.nextState}var JR=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function GR(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 Nv(e){let i=(e.findings??[]).filter(u=>!Li(u.code)),n=i.find(u=>u.requiresUserDecision),r=i.find(u=>u.repairCommand!==null||JR.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:GR(e.state)}}import Er from"path";var bv=8,UR={"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 KR(e){let t=UR[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"}:Li(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 YR(e,t,i){if(!i.path)return null;let n;if(Er.isAbsolute(i.path)?n=Er.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=Er.resolve(O(e,t.name),...i.path.split(/[\\/]/u)):n=Er.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!z(e.projectRoot,n))return null;let r=Er.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function XR(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 kv(e){return e.findings.map(t=>{let i=KR(t.code);return{code:t.code,message:t.message,severity:i.severity,path:YR(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:XR(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 Sv(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,bv),truncated:t.length>bv}}import Av from"path";import Yi from"path";var zt={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Xi=/^[a-f0-9]{64}$/u;function jo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Oo(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 Wt(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 Ev(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function cu(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function QR(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Yi.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Yi.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function lu(e,t){return Yi.join(O(e,t),"runtime","checkpoints","progress.json")}function Qi(e,t){return Yi.join(O(e,t),"runtime","checkpoint-journal.json")}function uu(e,t,i){if(!Xi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Yi.join(O(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function ZR(e){if(!Xi.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function du(e,t,i){let n=await tt({root:e,file:t,maxBytes:zt.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function eP(e,t){let i=jo(e,`checkpoint manifest artifact ${t}`);Oo(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=QR(Wt(i.path,`checkpoint artifact ${t} path`,4096)),r=Ze(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!Xi.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:cu(i.size,`checkpoint artifact ${t} size`)}}function $o(e,t){let i=jo(e,"Native checkpoint manifest");if(Oo(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>zt.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(eP),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=cu(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>zt.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 fu(e){return W(JSON.stringify($o(e,e.change)))}function hu(e,t){let i=jo(e,"Native progress checkpoint");if(Oo(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=Ev(i.previousRevision,"Native checkpoint previousRevision"),a=Ev(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Wt(i.manifestHash,"Native checkpoint manifestHash",64);if(!Xi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=ZR(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Wt(i.inputHash,"Native checkpoint inputHash",64);if(!Xi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Wt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=cu(i.artifactCount,"Native checkpoint artifactCount");if(u>zt.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Wt(i.summary,"Native checkpoint summary"),f=Wt(i.nextAction,"Native checkpoint nextAction");if(Ce(d)!==d||Ce(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Wt(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 tP(e,t){let i=jo(e,"Native checkpoint journal");if(Oo(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=ft(i.previousState),r=ft(i.nextState),a=hu(i.checkpoint,t),o=$o(i.manifest,t),s=Wt(i.inputHash,"Native checkpoint journal inputHash",64),c=W(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Xi.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!==fu(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 iP(e,t,i){let n=Yi.resolve(e.projectRoot,...t.split("/"));if(!z(e.projectRoot,n)||z(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=xc(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await tt({root:e.projectRoot,file:n,maxBytes:zt.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 nP(e,t){let i=lu(e,t);await $(e.nativeRoot,i);try{return hu(await du(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function pu(e,t,i){let n=uu(e,t,i);await $(e.nativeRoot,n);let r=await du(e.nativeRoot,n,"Native checkpoint manifest"),a=$o(r,t);if(mu(e,a),fu(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Ho(e,t){let i=Qi(e,t);await $(e.nativeRoot,i);try{let n=tP(await du(e.nativeRoot,i,"Native checkpoint journal"),t);return mu(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Cv(e,t,i,n){let r=$o(i,t);mu(e,r);let a=fu(r),o=uu(e,t,a);await $(e.nativeRoot,o);try{let s=await pu(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 Le(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function mu(e,t){for(let i of t.artifacts){let n=xc(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Rv(e,t){let i=hu(t,t.change),n=await pu(e,i.change,i.manifestHash),r=W(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=lu(e,t.change);await $(e.nativeRoot,a),await Le(a,i,{containedRoot:e.nativeRoot})}async function Pv(e){let t;try{t=await nP(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:lu(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 pu(e.paths,e.name,t.manifestHash);let a=W(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 iP(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:uu(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}var xv=240,Tv=8,Fo=50;function Iv(e){let t=Array.from(e);return t.length<=xv?e:`${t.slice(0,xv-1).join("")}…`}function rP(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function aP(e){let t=[...new Set(e.map(rP))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Tv),reasonCount:e.length,codesTruncated:t.length>Tv};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Fo),reasonsTruncated:e.length>Fo}}}async function _v(e){let t=null;try{let s=await Ho(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Qi(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:Qi(e.paths,e.state.name)}}let i=await Pv({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=aP(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:zt.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Iv(i.checkpoint.summary),nextAction:Iv(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:Av.relative(e.paths.projectRoot,Av.join(O(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:zt.maxArtifacts}}import{promises as WA}from"node:fs";import fg from"node:path";import jv from"node:path";var oP="comet.native.archive-preflight.v1",sP="comet.native.archive-preflight.v1",cP="comet.native.archive-operation.v1",lP=/^[a-f0-9]{64}$/u,Ov=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Do(e,t){return e<t?-1:e>t?1:0}function dP(e,t){if(typeof e!="string"||!lP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wt(e,t){return e===null?null:dP(e,t)}function fP(e,t){let i=jv.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||jv.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 hP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function pP(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 mP(e,t){if(!Ov.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=wt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=wt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=wt(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 vP(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:wt(e.contractHash,"Native archive contract hash"),acceptanceHash:wt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:wt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:wt(e.reportHash,"Native archive report hash"),envelopeHash:wt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:wt(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 gP(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!uP.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(Do);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function wP(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(Do)}function $v(e){if(!Ov.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(mP).sort((l,u)=>Do(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(cP,l)})),n=vP(e.evidence),r=pP(e.workspace),a=[...new Set([...gP(e.findingCodes??[]),...wP({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(Do),o=hP(e.revision),s=fP(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:oP,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(sP,c)}}import{createHash as yP}from"node:crypto";import Hv from"node:path";var NP="comet.native.conflict-radar.v1",Ne=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}),bP="comet.native.conflict-radar.v1",kP="comet.native.conflict-radar-signals.v1",SP=/^[a-f0-9]{64}$/u,Lv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EP=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),CP=new Set(["capability","operation","baseHash"]),RP=new Set(["path","kind"]);function Zi(e,t){return e<t?-1:e>t?1:0}function vu(e){return Buffer.byteLength(e,"utf8")}function gu(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 wu(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(vu(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function PP(e,t){let i=wu(e,t,Ne.maxArtifactPathBytes),n=Hv.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)||Hv.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 Mv(e,t){if(typeof e!="string"||!SP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function AP(e,t){let i=gu(e,CP,t),n=wu(i.capability,`${t} capability`,Ne.maxCapabilityBytes);if(!Lv.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:Mv(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 xP(e,t){let i=gu(e,RP,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:PP(i.path,`${t} path`),kind:i.kind}}function TP(e,t){let i=gu(e,EP,`Conflict radar change ${t}`),n=wu(i.name,`Conflict radar change ${t} name`,Ne.maxNameBytes);if(!Lv.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>Ne.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>Ne.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>AP(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>Zi(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)=>xP(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>Zi(c.path,l.path)||Zi(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:Mv(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function IP(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ne.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(TP).sort((r,a)=>Zi(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)>Ne.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>Ne.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function _P(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 jP(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 OP(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function $P(e,t){let i=[],n=yP("sha256").update(`${kP}
174
+ [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(hr(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ne.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(_P(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=jP(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:OP(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function Fv(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function HP(e,t){return Fv(e.classification)-Fv(t.classification)||Zi(e.left,t.left)||Zi(e.right,t.right)}function Dv(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:NP,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 Bv(e){let t=IP(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push($P(t[s],t[c]));i.sort(HP);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(bP,{changes:t,relationships:n}),a=i.slice(0,Ne.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Dv(t,i,a,r);for(;a.length>0&&vu(JSON.stringify(o))>Ne.maxSerializedBytes;)a=a.slice(0,-1),o=Dv(t,i,a,r);if(vu(JSON.stringify(o))>Ne.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as pA}from"node:crypto";import{promises as Ge}from"node:fs";import at from"node:path";import qv from"node:path";var Vv="comet.native.check-receipt.v1",FP="comet.native.check-receipt.v1",en="scoped-text-safety",yu=1,je=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),DP=/^[a-f0-9]{64}$/u,LP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MP="comet.native.checker-policy.v1",BP="comet.native.check-input.v1",qP=2048,Wv=D(MP,{policy:en,version:yu,limits:je,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),VP=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),zv=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Gv=["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"],WP=new Set(Gv);function vi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gi(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 yt(e,t){if(typeof e!="string"||!DP.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function mi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Uv(e,t){let i=mi(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Jv(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 zP(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>qP||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=qv.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||qv.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function JP(e){let t=vi(e,"Native check receipt checker");gi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=vi(t.limits,"Native check receipt limits");if(gi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==en||t.version!==yu||t.hash!==Wv||i.maxFiles!==je.maxFiles||i.maxFileBytes!==je.maxFileBytes||i.maxTotalBytes!==je.maxTotalBytes||i.maxIssues!==je.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:en,version:yu,hash:Wv,limits:{...je}}}function GP(e){let t=vi(e,"Native check receipt contract");return gi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:yt(t.expectedHash,"Native check expected contract hash"),beforeHash:yt(t.beforeHash,"Native check before contract hash"),afterHash:yt(t.afterHash,"Native check after contract hash")}}function UP(e){let t=vi(e,"Native check receipt implementation");return gi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:yt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:yt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:yt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:yt(t.afterSnapshotHash,"Native check after snapshot hash")}}function KP(e){let t=vi(e,"Native check receipt counts");gi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:mi(t.filesSelected,"Native check filesSelected"),filesScanned:mi(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:mi(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:mi(t.bytesScanned,"Native check bytesScanned"),issueCount:mi(t.issueCount,"Native check issueCount"),recordedIssueCount:mi(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>je.maxFiles||i.bytesScanned>je.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>je.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function YP(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||zv.indexOf(e.kind)-zv.indexOf(t.kind)}function XP(e){if(!Array.isArray(e)||e.length>je.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=vi(n,`Native check issue ${r}`);if(gi(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!VP.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:zP(a.path,`Native check issue ${r} path`),line:Uv(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(YP);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function QP(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!WP.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Gv.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 ZP(e){return D(BP,e)}function Kv(e){let t=vi(e,"Native check receipt");if(gi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Vv)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!LP.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Uv(t.sourceRevision,"Native check source revision"),n=JP(t.checker),r=GP(t.contract),a=UP(t.implementation),o=ZP({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(yt(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=Jv(t.startedAt,"Native check receipt startedAt"),c=Jv(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=KP(t.counts),u=XP(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=QP(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>je.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>je.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:Vv,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=yt(t.receiptHash,"Native check receipt content hash");if(D(FP,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var bu="comet.native.verification-receipt.v3",eA=bu,tA="comet.native.declared-artifacts.v1",iA=/^[a-f0-9]{64}$/u,nA=/^acceptance-[a-f0-9]{64}$/u,rA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,oA=4096,sA=256,cA=1024;function tn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Jt(e,t,i){let n=Object.keys(e).sort(),r=[...t].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function Nt(e,t){if(typeof e!="string"||!iA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Je(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Ce(e).trim();if(!i||i.length>oA||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Nu(e,t){let i=Je(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 Cr(e,t,i=Je,n=!1,r=sA){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 lA(e,t){if(typeof e!="string"||!nA.test(e))throw new Error(`${t} is invalid`);return e}function uA(e){let t=tn(e,"Native verification receipt bindings");if(Jt(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!rA.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:Nt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Nt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Nt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Nt(t.artifactHash,"Native verification receipt artifact hash")}}function dA(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=aA.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function fA(e,t,i,n){let r=tn(t,`Native ${e} evidence`);if(e==="automated-check"){if(Jt(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Nu(r.startedAt,"Native automated-check start time"),o=Nu(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=tn(r.worktree,"Native automated-check worktree");if(Jt(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=tn(r.afterFence,"Native automated-check after fence");if(Jt(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Je(r.executable,"Native automated-check executable"),args:Cr(r.args,"Native automated-check arguments",Je,!0),cwd:Je(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:Je(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Nt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Nt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Nt(r.outputHash,"Native automated-check output hash"),outputSummary:Je(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){Jt(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=dA(r.checkReceiptRef);if(Nt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Cr(r.subjects,"Native static inspection subjects",Je,n==="required-check"),rule:Je(r.rule,"Native static inspection rule"),resultSummary:Je(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Jt(r,["steps","observations"],"Native manual-evidence evidence"),{steps:Cr(r.steps,"Native manual evidence steps"),observations:Cr(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function hA(e){let t=tn(e,"Native verification receipt");if(Jt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,n=t.role,r=t.status,a=Je(t.actor,"Native verification receipt actor"),o=Cr(t.acceptanceIds,"Native receipt acceptance IDs",lA,n==="required-check",cA).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:bu,kind:i,role:n,status:r,bindings:uA(t.bindings),acceptanceIds:o,actor:a,issuedAt:Nu(t.issuedAt,"Native verification receipt issue time"),evidence:fA(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==en||s.actor!==`native-runtime:${en}`))throw new Error("Native required check policy identity is invalid");return s}function Yv(e){let t=tn(e,"Native verification receipt");if(Jt(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==bu)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=hA(n),a=Nt(t.receiptHash,"Native verification receipt hash");if(D(eA,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function ku(e){return D(tA,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var eg=/^[a-f0-9]{64}$/u,nn=pi,tH=3*nn;function Su(e,t){let i=at.relative(e,t);return i===""||!at.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${at.sep}`)}function mA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Lo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Xv(e){let t=await Ge.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Ge.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function vA(e,t){let i=at.resolve(e),n=at.resolve(t);if(!Su(i,n))throw new Error("Native evidence path is outside its change");let r=[await Xv(i)],a=i;for(let o of at.relative(i,n).split(at.sep).filter(Boolean)){a=at.join(a,o);let s=await Xv(a);if(!Su(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Qv(e){for(let t of e){let i=await Ge.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!mA(t,i)||await Ge.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function gA(e,t,i={}){let n=await vA(t,at.dirname(e));await i.afterParentChainCaptured?.();let r=await Ge.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Ge.realpath(e);if(!Su(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Ge.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Ge.lstat(e),Ge.realpath(e)]);if(await Qv(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Lo(s,r)||!Lo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>nn)throw new Error(`Native evidence document exceeds ${nn} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let g=nn+1-d,S=await o.read(f,0,Math.min(f.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>nn)throw new Error(`Native evidence document exceeds ${nn} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Ge.lstat(e),Ge.realpath(e)]);if(await Qv(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Lo(s,p)||!Lo(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 tg(e,t){if(!eg.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function wA(e,t,i,n,r){if(!eg.test(i))throw new Error("Native report evidence hash is invalid");let a=await wi({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"||pA("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 rn(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 yA(e,t,i,n,r){return at.join(r??O(e,t),...tg(i,n).split("/"))}async function wi(e){let t=e.changeDir??O(e.paths,e.name),i=yA(e.paths,e.name,e.kind,e.hash,t);return await $(e.paths.nativeRoot,i),gA(i,t,e.hooks)}function Zv(e,t){return So(e,t)}function NA(e,t){let i=Ro(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function bA(e,t,i){let n=Ym(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function kA(e,t,i){let n=Ul(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function SA(e,t,i,n=!1,r){let a=await Eu(e,t,i.implementationScopeRef,void 0,r);if(n&&await wA(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 ig(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 Rr(e,t,i,n,r){let a=rn(i,"scopes"),o=NA(await wi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=rn(o.baselineProjectionRef,"snapshots"),c=rn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([wi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>Zv(d,s)),wi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>Zv(d,c))]);return Vm({baseline:l,current:u,scope:o})}async function Eu(e,t,i,n,r){return(await Rr(e,t,i,n,r)).scope}async function ig(e,t,i,n,r){let a=rn(i,"allowances");return bA(await wi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function Mo(e,t,i,n,r){let a=rn(i,"receipts"),o=Yv(await wi({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 Pr(e,t,i,n,r){let a=rn(i,"verifications"),o=kA(await wi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await SA(e,t,o,!1,r),o}var EA=4096;async function CA(e,t=Ne.maxChanges){try{let i=await Un({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 ng(e,t){let i=await me(e,t),[n,r]=await Promise.all([i.implementation_scope?Eu(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 Bo(e,t,i={}){let r=(await CA(e,EA)).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 ng(e,t),o=0,s=0;for(let c of r){if(c===t)continue;let l=await ng(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Bv([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as $A,spawn as OH}from"node:child_process";import{promisify as HA}from"node:util";import{promises as RA}from"fs";async function rg(e,t,i){let n=await Ho(e,t);if(!n)return null;if(await Cv(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Bi(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Rv(e,n.checkpoint),await i?.afterProgressWritten?.(n),await RA.rm(Qi(e,t),{force:!0}),n}async function Ar(e,t){await Sr(e,t),await rg(e,t)}import{constants as Cu,promises as Oe}from"node:fs";import yi from"node:path";var PA=/^[a-f0-9]{64}$/u,AA=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,xr=512*1024;function xA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qo(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return se(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function TA(e,t){let i=yi.resolve(e),n=yi.resolve(t);if(!z(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...yi.relative(i,n).split(yi.sep).filter(Boolean)]){o&&(a=yi.join(a,o));let s=await Oe.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Oe.realpath(a);if(r.length>0&&!z(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 ag(e){for(let t of e){let i=await Oe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!xA(t,i)||await Oe.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function IA(e){if(!PA.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function _A(e){let t=AA.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function jA(e,t,i){return yi.join(O(e,t),...IA(i).split("/"))}async function OA(e,t,i){let n=await TA(i,yi.dirname(e)),r=await Oe.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>xr)throw new Error(`Native check receipt exceeds ${xr} bytes`);let[a,o]=await Promise.all([Oe.realpath(t),Oe.realpath(e)]);if(!z(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Cu.O_RDONLY|Cu.O_NOFOLLOW|Cu.O_NONBLOCK,c=await Oe.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(),Oe.lstat(e),Oe.realpath(e)]);if(await ag(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!qo(r,l)||!qo(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=xr+1-p,k=await c.read(m,0,Math.min(m.length,N),null);if(k.bytesRead===0)break;if(p+=k.bytesRead,p>xr)throw new Error(`Native check receipt exceeds ${xr} bytes`);f.push(Buffer.from(m.subarray(0,k.bytesRead)))}let[h,g,S]=await Promise.all([c.stat(),Oe.lstat(e),Oe.realpath(e)]);if(await ag(n),!g.isFile()||g.isSymbolicLink()||S!==o||!z(a,S)||!qo(l,h)||!qo(l,g))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function og(e,t,i){let n=_A(i),r=O(e,t),a=jA(e,t,n);await $(e.nativeRoot,a);let o=Kv(await OA(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var Tr=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var KH=64*1024;var YH=3600*1e3;var XH=HA($A);var QH=["$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 FA=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function sg(e,t){let i=[];for(let n of FA){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 cg(e){if(e.receipt.kind!=="static-inspection")return null;let t=await og(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 Gt=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 DA(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function LA(e){let t=DA(e.bundle.baseline),i=await cl(e.paths,t,{origin:"explicit",now:e.now});return Wl({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function ug(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Rr(e.paths,e.state.name,e.state.implementation_scope),i=await Vi({changeDir:O(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await LA({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 dg(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await ug(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 MA(e){let t=await ce({root:O(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:vm(t.text)}}function BA(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 qA(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:ku(e.implementationScope.scope.declaredArtifacts)}}async function lg(e){let t=await Mo(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=sg(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 Gt([{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 cg({paths:e.paths,state:e.state,receipt:t});if(r){let a=BA({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 VA(e){let t=qA({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await lg({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Gt)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 lg({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Gt)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 Gt(i)}function Ru(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Pu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Ru(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([ug(e),Pr(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Ru(e.state.verification_result,"stale"),envelope:null};let n=await MA({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 VA({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:Ru(e.state.verification_result,"invalid"),envelope:null}}}function zA(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function hg(e){try{return await WA.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function JA(e,t){try{return(await ce({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GA(e,t,i){let n=Bt(e,i.capability);if(!z(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=fg.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await JA(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ce({root:O(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 UA(e,t){return hg(kr(e,t))}async function Au(e){let t=e.now??new Date,i=await me(e.paths,e.name),n=await Dt(e.paths,e.name),r=await jt(e.paths.projectRoot),a=zA(i.name,t),o=fg.resolve(e.paths.nativeRoot,...a.split("/"));if(!z(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=>GA(e.paths,i.name,m))),Pu({paths:e.paths,state:i,now:t}),Bo(e.paths,i.name),di(e.paths,i.name),El(e.paths,i.name),UA(e.paths,i.name),hg(o)]);return $v({change:i.name,archiveConfirmation:r?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:n?.schema==="comet.native.workspace.v3"?{schema:n.schema,isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function KA(e,t){let i=O(e,t.name),n=await We(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 ho(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 nt(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function YA(e,t){let i=await KA(e,t);return{committed:i,latest:rv(i),history:nv(i)}}async function pg(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await YA(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 aF=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function XA(e){return(await Rm(e))?.change??null}function QA(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 ZA(e,t){let i=O(e,t.name),n=[...(await Pl(i,t.brief)).findings,...(await rm(e,t)).findings,...await Pm(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await co(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 Pp(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 Vi({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 Ui(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 Al(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 xu(e,t,i){let n=await XA(e)===t,r;try{let w=await Cl(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 _v({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await pg(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 Vi({changeDir:O(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),v=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let E=await Pr(e,r.name,r.verification_evidence);for(let I of E.acceptanceTrace.entries)v.set(I.acceptanceId,I.status==="failed"?"failed":I.status==="missing"?"missing":"satisfied")}c=dm({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:v,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(w){if(i.acceptanceCursor)throw w;c=void 0}let l=[];if(i?.includeConflictFindings!==!1)try{let w=await Bo(e,r.name,{tolerateInvalidSiblings:!0});l.push(...w.findingCodes.map(v=>({code:v,message:`Native change overlap is visible in the current root: ${v}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let w=await Dt(e,r.name);if(w)if(w.schema==="comet.native.workspace.v3"){let v=await wo({paths:e,identity:w});v.state==="drifted"&&v.code&&u.push({code:v.code,message:v.message??"Native workspace binding is no longer valid"})}else{let v=await go({paths:e,identity:w});u.push(...v.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${v.driftComponents.join(", ")||"no-component"})`})))}}catch{u.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let d=[],f=!1;if(r.phase==="verify"){let w=await dg({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.findingCodes.map(v=>({code:v,message:`Native Verify implementation scope is not current: ${v}`})))}let p=null,m=[];if(r.phase==="archive")try{p=await Au({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 ZA(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,v,E)=>E.findIndex(I=>I.code===w.code&&I.path===w.path)===v),g=kv({paths:e,state:r,findings:h}),S=g.filter(w=>!Li(w.code)),N=r.phase==="archive"&&p?.ready===!0&&S.length===0,k=f||r.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),C=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=g.find(w=>w.severity==="error");return{name:r.name,phase:r.phase,revision:r.revision,approval:r.approval,verificationResult:r.verification_result,specChanges:r.spec_changes.length,selected:n,nextCommand:b||C?null:QA(r,N,k,i?.clarificationMode),archiveReady:N,inspection:a.inspection,findingSummary:Sv(g),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:Nv({state:r,findings:g,archiveReady:N,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:g.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Fo,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}import{promises as mg}from"fs";import vg from"path";var gg=fi.maxSpecs*4;async function Tu(e){try{return await Kn(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function wg(e,t){let i=vg.join(O(e,t),"specs"),n;try{n=await Qa({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await mg.opendir(i);try{for await(let s of o){if(a+=1,a>gg)throw new Error(`Native proposed specs directory exceeds ${gg} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;dt(s.name);let c=vg.join(i,s.name,"spec.md");await $(e.nativeRoot,c);let l;try{l=await mg.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>fi.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function ex(e,t){let i=await wg(e,t.name),n=[];for(let r of i){if(t.spec_changes.find(c=>c.capability===r)?.operation==="remove")throw new Error(`Capability ${r} has both a proposed spec and a remove intent`);let o=Bt(e,r);await $(e.nativeRoot,o);let s=await Tu(o);n.push({capability:r,operation:s===null?"create":"replace",source:`specs/${r}/spec.md`,base_hash:s})}for(let r of t.spec_changes){if(r.operation!=="remove"||i.includes(r.capability))continue;let a=Bt(e,r.capability);await $(e.nativeRoot,a);let o=await Tu(a);o!==null&&n.push({...r,base_hash:o})}return n.sort((r,a)=>r.capability.localeCompare(a.capability))}async function yg(e){dt(e.name);let t=Ce(e.summary);return Nr(t,"Spec rebase summary"),qe(e.paths,`rebase specs for ${e.name}`,()=>Ki(e.paths,e.name,`rebase specs for ${e.name}`,async()=>{await Ar(e.paths,e.name);let i=await me(e.paths,e.name);if(i.phase==="shape")throw new Error("Shape spec metadata is refreshed by the next command");if(i.archived)throw new Error(`Native change ${i.name} is already archived`);let n=O(e.paths,e.name),r=await We(n);if(!r||r.runId!==i.run_id||r.currentStep!==i.phase||r.pending)throw new Error(`Native Run state is missing or inconsistent for ${i.name}`);let a=await ex(e.paths,i),o={...i,revision:i.revision+1,phase:"build",spec_changes:a,verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},s={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},c=W(JSON.stringify({operation:"spec-rebase",change:i.name,summary:t,specChanges:a}));await wv({paths:e.paths,previousState:i,nextState:o,previousRun:r,nextRun:s,evidenceHash:c,eventData:{previousPhase:i.phase,nextPhase:"build",evidenceHash:c,summary:t,artifacts:[],noCodeReason:null,verificationResult:null},operation:"spec-rebase",now:e.now,transitionId:e.transitionId});let l=await Sr(e.paths,e.name);if(!l)throw new Error("Native spec rebase journal disappeared before completion");return l}))}async function Ng(e,t,i){return dt(t),dt(i),qe(e,`remove spec ${i} from ${t}`,()=>Ki(e,t,`remove spec ${i} from ${t}`,async()=>(await Ar(e,t),tx(e,t,i))))}async function tx(e,t,i){let n=await me(e,t);if(n.phase==="archive"||n.archived)throw new Error(`Native change ${t} no longer accepts spec changes`);if((await wg(e,t)).includes(i))throw new Error(`Capability ${i} has both a proposed spec and a remove intent`);if(n.spec_changes.find(l=>l.capability===i)?.operation==="remove")return n;let o=Bt(e,i);await $(e.nativeRoot,o);let s=await Tu(o);if(s===null)throw new Error(`Canonical spec is missing: ${i}`);let c={...n,spec_changes:[...n.spec_changes.filter(l=>l.capability!==i),{capability:i,operation:"remove",base_hash:s}].sort((l,u)=>l.capability.localeCompare(u.capability))};return await Bi(e,c,n.revision),c}import rx from"path";var OF={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var VF=16*1024*1024,WF=256*1024,zF=16*1024;var xD=16*1024*1024,Vo=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"},Wo=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var LD=10*1024*1024,Ue=class extends Error{};function bg(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new Ue(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function zo(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ue(`${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 Ue(`${t} requires a value`);return e.splice(n,2),r}function Iu(e){if(e.length>0)throw new Ue(`Unexpected argument: ${e[0]}`)}function Ir(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new Ue(`${t} is required`);return i}async function kg(e){return e?rx.resolve(e):za(process.cwd())}async function _u(e){let t=await Fh({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function ju(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
175
+ `}}function Sg(e,t){if(t instanceof Ue)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Vo)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Wo)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof sr)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 yo)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 No)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 Gt)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Tr)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 Eg(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}})+`
176
+ `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Cg(e,t){let i=Ir(e,"spec subcommand");if(i==="remove"){let n=Ir(e,"change name"),r=Ir(e,"capability");Iu(e);let{config:a,paths:o}=await _u(t),s=await Ng(o,n,r),c=await xu(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return ju("spec remove",{...s,continuation:c.continuation},`Marked Native capability ${r} for removal in ${n}
177
+ `)}if(i==="rebase"){let n=Ir(e,"change name"),r=zo(e,"--summary");if(!r)throw new Ue("--summary is required");Iu(e);let{config:a,paths:o}=await _u(t),s=await yg({paths:o,name:n,summary:r}),c=await xu(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return ju("spec rebase",{...s,continuation:c.continuation},`Rebased Native specs for ${n}
178
+ `)}throw new Ue(`Unknown spec command: ${i}`)}function ax(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}})+`
179
+ `}}async function Rg(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{bg(r,"--json"),s=zo(r,"--project-root");let u=[...r,...a],d=await kg(s);c=await t(u,d)}catch(u){c=Sg(e,u)}let l=o?ax(c):Eg(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
180
180
  `)?"":`
181
- `)),l.exitCode}process.exitCode=await hg("spec",fg);
181
+ `)),l.exitCode}process.exitCode=await Rg("spec",Cg);