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

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 (446) hide show
  1. package/README.md +66 -26
  2. package/assets/manifest.json +4 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +120 -120
  4. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +79 -79
  5. package/assets/skills/comet/scripts/comet-guard.mjs +134 -134
  6. package/assets/skills/comet/scripts/comet-handoff.mjs +106 -106
  7. package/assets/skills/comet/scripts/comet-hook-guard.mjs +130 -130
  8. package/assets/skills/comet/scripts/comet-hook-router.mjs +115 -115
  9. package/assets/skills/comet/scripts/comet-intent.mjs +6 -6
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +78 -78
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +194 -193
  12. package/assets/skills/comet/scripts/comet-state.mjs +117 -117
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +96 -96
  14. package/assets/skills/comet-build/SKILL.md +36 -62
  15. package/assets/skills/comet-classic/SKILL.md +14 -8
  16. package/assets/skills/comet-classic/reference/comet-yaml-fields.md +1 -1
  17. package/assets/skills/comet-classic/reference/scripts.md +3 -1
  18. package/assets/skills/comet-classic/reference/workspace.md +23 -0
  19. package/assets/skills/comet-design/SKILL.md +2 -2
  20. package/assets/skills/comet-native/SKILL.md +18 -15
  21. package/assets/skills/comet-native/reference/artifacts.md +5 -4
  22. package/assets/skills/comet-native/reference/clarification.md +1 -1
  23. package/assets/skills/comet-native/reference/commands.md +4 -4
  24. package/assets/skills/comet-native/reference/recovery.md +1 -1
  25. package/assets/skills/comet-native/reference/workspace.md +4 -4
  26. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +116 -115
  27. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +148 -148
  28. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +100 -100
  29. package/assets/skills/comet-native/scripts/comet-native-init.mjs +118 -118
  30. package/assets/skills/comet-native/scripts/comet-native-new.mjs +118 -118
  31. package/assets/skills/comet-native/scripts/comet-native-next.mjs +121 -121
  32. package/assets/skills/comet-native/scripts/comet-native-root.mjs +108 -108
  33. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +157 -156
  34. package/assets/skills/comet-native/scripts/comet-native-select.mjs +133 -133
  35. package/assets/skills/comet-native/scripts/comet-native-show.mjs +109 -109
  36. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +89 -89
  37. package/assets/skills/comet-native/scripts/comet-native-status.mjs +109 -109
  38. package/assets/skills/comet-open/SKILL.md +24 -5
  39. package/assets/skills/comet-review/SKILL.md +121 -0
  40. package/assets/skills/comet-review/agents/openai.yaml +5 -0
  41. package/assets/skills-zh/comet-build/SKILL.md +36 -62
  42. package/assets/skills-zh/comet-classic/SKILL.md +14 -8
  43. package/assets/skills-zh/comet-classic/reference/comet-yaml-fields.md +1 -1
  44. package/assets/skills-zh/comet-classic/reference/scripts.md +3 -1
  45. package/assets/skills-zh/comet-classic/reference/workspace.md +23 -0
  46. package/assets/skills-zh/comet-design/SKILL.md +2 -2
  47. package/assets/skills-zh/comet-native/SKILL.md +18 -15
  48. package/assets/skills-zh/comet-native/reference/artifacts.md +5 -4
  49. package/assets/skills-zh/comet-native/reference/clarification.md +1 -1
  50. package/assets/skills-zh/comet-native/reference/commands.md +4 -4
  51. package/assets/skills-zh/comet-native/reference/recovery.md +1 -1
  52. package/assets/skills-zh/comet-native/reference/workspace.md +4 -4
  53. package/assets/skills-zh/comet-open/SKILL.md +24 -5
  54. package/assets/skills-zh/comet-review/SKILL.md +121 -0
  55. package/assets/skills-zh/comet-review/agents/openai.yaml +5 -0
  56. package/dist/app/cli/index.js +20 -1
  57. package/dist/app/cli/index.js.map +1 -1
  58. package/dist/app/commands/classic.d.ts.map +1 -1
  59. package/dist/app/commands/classic.js +2 -0
  60. package/dist/app/commands/classic.js.map +1 -1
  61. package/dist/app/commands/eval.d.ts +9 -2
  62. package/dist/app/commands/eval.d.ts.map +1 -1
  63. package/dist/app/commands/eval.js +293 -48
  64. package/dist/app/commands/eval.js.map +1 -1
  65. package/dist/app/commands/init.d.ts.map +1 -1
  66. package/dist/app/commands/init.js +5 -8
  67. package/dist/app/commands/init.js.map +1 -1
  68. package/dist/app/commands/update.d.ts.map +1 -1
  69. package/dist/app/commands/update.js +5 -6
  70. package/dist/app/commands/update.js.map +1 -1
  71. package/dist/domains/comet-classic/classic-cli.d.ts +1 -1
  72. package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
  73. package/dist/domains/comet-classic/classic-cli.js +3 -0
  74. package/dist/domains/comet-classic/classic-cli.js.map +1 -1
  75. package/dist/domains/comet-classic/classic-command-context.d.ts +9 -0
  76. package/dist/domains/comet-classic/classic-command-context.d.ts.map +1 -1
  77. package/dist/domains/comet-classic/classic-command-context.js +10 -0
  78. package/dist/domains/comet-classic/classic-command-context.js.map +1 -1
  79. package/dist/domains/comet-classic/classic-current-change.d.ts.map +1 -1
  80. package/dist/domains/comet-classic/classic-current-change.js +29 -3
  81. package/dist/domains/comet-classic/classic-current-change.js.map +1 -1
  82. package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
  83. package/dist/domains/comet-classic/classic-guard.js +4 -4
  84. package/dist/domains/comet-classic/classic-guard.js.map +1 -1
  85. package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
  86. package/dist/domains/comet-classic/classic-handoff.js +44 -6
  87. package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
  88. package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
  89. package/dist/domains/comet-classic/classic-hook-guard.js +16 -2
  90. package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
  91. package/dist/domains/comet-classic/classic-intent-command.d.ts.map +1 -1
  92. package/dist/domains/comet-classic/classic-intent-command.js +2 -1
  93. package/dist/domains/comet-classic/classic-intent-command.js.map +1 -1
  94. package/dist/domains/comet-classic/classic-resume-probe-command.d.ts.map +1 -1
  95. package/dist/domains/comet-classic/classic-resume-probe-command.js +4 -3
  96. package/dist/domains/comet-classic/classic-resume-probe-command.js.map +1 -1
  97. package/dist/domains/comet-classic/classic-runtime-run.d.ts +6 -0
  98. package/dist/domains/comet-classic/classic-runtime-run.d.ts.map +1 -1
  99. package/dist/domains/comet-classic/classic-runtime-run.js +58 -9
  100. package/dist/domains/comet-classic/classic-runtime-run.js.map +1 -1
  101. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  102. package/dist/domains/comet-classic/classic-state-command.js +39 -13
  103. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  104. package/dist/domains/comet-classic/classic-validate-command.d.ts.map +1 -1
  105. package/dist/domains/comet-classic/classic-validate-command.js +2 -2
  106. package/dist/domains/comet-classic/classic-validate-command.js.map +1 -1
  107. package/dist/domains/comet-classic/classic-workspace-command.d.ts +3 -0
  108. package/dist/domains/comet-classic/classic-workspace-command.d.ts.map +1 -0
  109. package/dist/domains/comet-classic/classic-workspace-command.js +45 -0
  110. package/dist/domains/comet-classic/classic-workspace-command.js.map +1 -0
  111. package/dist/domains/comet-classic/classic-workspace.d.ts +38 -0
  112. package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -0
  113. package/dist/domains/comet-classic/classic-workspace.js +315 -0
  114. package/dist/domains/comet-classic/classic-workspace.js.map +1 -0
  115. package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
  116. package/dist/domains/comet-entry/hook-adapter.js +5 -1
  117. package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
  118. package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -0
  119. package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
  120. package/dist/domains/comet-entry/hook-router-entry.js +21 -1
  121. package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
  122. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  123. package/dist/domains/comet-entry/init-workflow.js +13 -5
  124. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  125. package/dist/domains/comet-native/index.d.ts +1 -0
  126. package/dist/domains/comet-native/index.d.ts.map +1 -1
  127. package/dist/domains/comet-native/index.js +1 -0
  128. package/dist/domains/comet-native/index.js.map +1 -1
  129. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  130. package/dist/domains/comet-native/native-archive-command.js +2 -0
  131. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  132. package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
  133. package/dist/domains/comet-native/native-atomic-file.js +17 -10
  134. package/dist/domains/comet-native/native-atomic-file.js.map +1 -1
  135. package/dist/domains/comet-native/native-children.d.ts +65 -0
  136. package/dist/domains/comet-native/native-children.d.ts.map +1 -0
  137. package/dist/domains/comet-native/native-children.js +453 -0
  138. package/dist/domains/comet-native/native-children.js.map +1 -0
  139. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  140. package/dist/domains/comet-native/native-cli-help.js +13 -7
  141. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  142. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  143. package/dist/domains/comet-native/native-cli-shared.js +18 -5
  144. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  145. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  146. package/dist/domains/comet-native/native-doctor-command.js +10 -5
  147. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  148. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  149. package/dist/domains/comet-native/native-hook-guard.js +56 -4
  150. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  151. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  152. package/dist/domains/comet-native/native-next-command.js +179 -20
  153. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  154. package/dist/domains/comet-native/native-portable-continuation.d.ts +22 -9
  155. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  156. package/dist/domains/comet-native/native-portable-continuation.js +178 -73
  157. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  158. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -1
  159. package/dist/domains/comet-native/native-portable-migration-runtime.js +9 -4
  160. package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -1
  161. package/dist/domains/comet-native/native-portable-runtime.d.ts +19 -1
  162. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  163. package/dist/domains/comet-native/native-portable-runtime.js +168 -4
  164. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  165. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  166. package/dist/domains/comet-native/native-portable-state.js +13 -0
  167. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  168. package/dist/domains/comet-native/native-portable-status.d.ts +3 -0
  169. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
  170. package/dist/domains/comet-native/native-portable-status.js +9 -1
  171. package/dist/domains/comet-native/native-portable-status.js.map +1 -1
  172. package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
  173. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  174. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  175. package/dist/domains/comet-native/native-pull-request-finish.d.ts +35 -0
  176. package/dist/domains/comet-native/native-pull-request-finish.d.ts.map +1 -0
  177. package/dist/domains/comet-native/native-pull-request-finish.js +282 -0
  178. package/dist/domains/comet-native/native-pull-request-finish.js.map +1 -0
  179. package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
  180. package/dist/domains/comet-native/native-show-command.js +2 -1
  181. package/dist/domains/comet-native/native-show-command.js.map +1 -1
  182. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -1
  183. package/dist/domains/comet-native/native-status-discovery.js +24 -6
  184. package/dist/domains/comet-native/native-status-discovery.js.map +1 -1
  185. package/dist/domains/comet-native/native-workspace-finish.d.ts +6 -0
  186. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
  187. package/dist/domains/comet-native/native-workspace-finish.js +86 -35
  188. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
  189. package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -1
  190. package/dist/domains/comet-native/native-workspace-preparation.js +192 -133
  191. package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -1
  192. package/dist/domains/dashboard/collector.d.ts +1 -1
  193. package/dist/domains/dashboard/collector.d.ts.map +1 -1
  194. package/dist/domains/dashboard/collector.js +102 -87
  195. package/dist/domains/dashboard/collector.js.map +1 -1
  196. package/dist/domains/dashboard/native-adapter.d.ts +20 -0
  197. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  198. package/dist/domains/dashboard/native-adapter.js +11 -0
  199. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  200. package/dist/domains/dashboard/native-collector.d.ts +1 -0
  201. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  202. package/dist/domains/dashboard/native-collector.js +304 -55
  203. package/dist/domains/dashboard/native-collector.js.map +1 -1
  204. package/dist/domains/dashboard/native-legacy-adapter.d.ts +12 -5
  205. package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -1
  206. package/dist/domains/dashboard/native-legacy-adapter.js +12 -0
  207. package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -1
  208. package/dist/domains/dashboard/server.d.ts.map +1 -1
  209. package/dist/domains/dashboard/server.js +5 -3
  210. package/dist/domains/dashboard/server.js.map +1 -1
  211. package/dist/domains/dashboard/types.d.ts +5 -0
  212. package/dist/domains/dashboard/types.d.ts.map +1 -1
  213. package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BYya6ofk.js +1 -0
  214. package/dist/domains/dashboard/web/assets/arc-DJbo4TD3.js +1 -0
  215. package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-D8uZ2IB-.js +36 -0
  216. package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-B16BVj-r.js +132 -0
  217. package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-BL17BIb8.js → c4Diagram-5PPSVZJV-ayV208_D.js} +1 -1
  218. package/dist/domains/dashboard/web/assets/channel-CEsrvmig.js +1 -0
  219. package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-XWLMOyd4.js → chunk-2GRJ4B5K-Bn5o8p3H.js} +1 -1
  220. package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-4drjXzHQ.js → chunk-2Q5K7J3B-BnF1SI6B.js} +1 -1
  221. package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-ETnma053.js +231 -0
  222. package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-CQXqBSqQ.js → chunk-5VM5RSS4-Cuvy639H.js} +1 -1
  223. package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-DOXBzl73.js +88 -0
  224. package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-pMreYMW7.js → chunk-GF5L2VYU-CfREXlEl.js} +5 -5
  225. package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-vQyyh3eG.js → chunk-JWPE2WC7-DWIdpYTb.js} +1 -1
  226. package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-B_DDS2IK.js → chunk-KBJHAD2P-BnqPcfZB.js} +1 -1
  227. package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-DdJ00fZz.js +1 -0
  228. package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-Cug8J1Qa.js → chunk-XXDRQBXY-BVDhdJyW.js} +1 -1
  229. package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CKFe0hg4.js +1 -0
  230. package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CKFe0hg4.js +1 -0
  231. package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-IQKP-hgj.js → cose-bilkent-JH36ORCC-C-nglwHC.js} +1 -1
  232. package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-CvvRO4J2.js → cynefin-VYW2F7L2-C8TMmrbP.js} +2 -2
  233. package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-C3pnQnjg.js +62 -0
  234. package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-DY7UWiPI.js +4 -0
  235. package/dist/domains/dashboard/web/assets/{demo-CeIDHUFJ.js → demo-BfLsKrIL.js} +26 -5
  236. package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-voTyDkQ5.js +30 -0
  237. package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-CN_LYqvT.js → diagram-B4RE2ZJO-B3VkUMck.js} +3 -3
  238. package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-BdJzPkv8.js +24 -0
  239. package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-Bsq0anZx.js +24 -0
  240. package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-CBaKRbcu.js +41 -0
  241. package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-Bl9Bm5wa.js +1 -0
  242. package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-DjOZzfKI.js +85 -0
  243. package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-C21e4siK.js +156 -0
  244. package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-Bs62uy6-.js +292 -0
  245. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-CaWEk3PM.js → gitGraphDiagram-DS77QQ5N-DQY_Ba00.js} +3 -3
  246. package/dist/domains/dashboard/web/assets/{graph--OzhPTMs.js → graph-DOmOIIwC.js} +1 -1
  247. package/dist/domains/dashboard/web/assets/{index-BNyOfAhu.js → index-BLv71GRj.js} +1 -1
  248. package/dist/domains/dashboard/web/assets/index-Be4r99N4.js +257 -0
  249. package/dist/domains/dashboard/web/assets/index-ByVYiA6g.css +1 -0
  250. package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-BK07mNG0.js → infoDiagram-6WML65LV-CNgNNG9l.js} +1 -1
  251. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js → ishikawaDiagram-WSZJBQD7-D9k1fTO1.js} +4 -4
  252. package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-BPy-P7xx.js → journeyDiagram-NVQOT4AX-CHijUnPl.js} +1 -1
  253. package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-3Jq9c_lo.js → kanban-definition-27J2QSJJ-DfWlntDq.js} +7 -7
  254. package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +1 -0
  255. package/dist/domains/dashboard/web/assets/{linear-kQyEW-4G.js → linear-o6hemX-z.js} +1 -1
  256. package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +1 -0
  257. package/dist/domains/dashboard/web/assets/mermaid.core-B1DoOsPD.js +306 -0
  258. package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-CyyurUpv.js → mindmap-definition-FAOFIHXS-COMQF9Yy.js} +1 -1
  259. package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-C_21n7Ps.js +1 -0
  260. package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-D3EmoYDY.js +39 -0
  261. package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +3 -0
  262. package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-CpayUMjH.js → quadrantDiagram-CIZ2JOQS-C3fGdiMa.js} +4 -4
  263. package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-mIsjemD-.js +1 -0
  264. package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-Bi8YpfnA.js → requirementDiagram-LRYGKXZP-D_UMpS5e.js} +1 -1
  265. package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-D1MwyMF6.js +40 -0
  266. package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-B8jp1RxX.js +162 -0
  267. package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-BKioI1Ql.js +1 -0
  268. package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-B7l8_CDo.js +1 -0
  269. package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-BIxuwbeV.js +1 -0
  270. package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-951PRLYp.js +2 -0
  271. package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-CEo6cGsy.js +8 -0
  272. package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-aHrrtV-b.js → timeline-definition-Z64GVDOM-CeyA2KbI.js} +4 -4
  273. package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BHe0TZJV.js +34 -0
  274. package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-RVQbcySh.js → wardleyDiagram-T6FBY63Y-CWqdSzJ-.js} +3 -3
  275. package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DCKiZVPV.js +7 -0
  276. package/dist/domains/dashboard/web/index.html +2 -2
  277. package/dist/domains/dashboard/workspace.d.ts +27 -0
  278. package/dist/domains/dashboard/workspace.d.ts.map +1 -0
  279. package/dist/domains/dashboard/workspace.js +108 -0
  280. package/dist/domains/dashboard/workspace.js.map +1 -0
  281. package/dist/domains/eval/index.d.ts +3 -0
  282. package/dist/domains/eval/index.d.ts.map +1 -1
  283. package/dist/domains/eval/index.js +3 -0
  284. package/dist/domains/eval/index.js.map +1 -1
  285. package/dist/domains/eval/standalone-context.d.ts +19 -0
  286. package/dist/domains/eval/standalone-context.d.ts.map +1 -0
  287. package/dist/domains/eval/standalone-context.js +107 -0
  288. package/dist/domains/eval/standalone-context.js.map +1 -0
  289. package/dist/domains/eval/standalone-static-collect.d.ts +22 -0
  290. package/dist/domains/eval/standalone-static-collect.d.ts.map +1 -0
  291. package/dist/domains/eval/standalone-static-collect.js +779 -0
  292. package/dist/domains/eval/standalone-static-collect.js.map +1 -0
  293. package/dist/domains/eval/user-environment.d.ts +6 -0
  294. package/dist/domains/eval/user-environment.d.ts.map +1 -0
  295. package/dist/domains/eval/user-environment.js +73 -0
  296. package/dist/domains/eval/user-environment.js.map +1 -0
  297. package/dist/domains/integrations/openspec.d.ts +1 -1
  298. package/dist/domains/integrations/openspec.d.ts.map +1 -1
  299. package/dist/domains/integrations/openspec.js +87 -44
  300. package/dist/domains/integrations/openspec.js.map +1 -1
  301. package/dist/domains/integrations/superpowers.d.ts +14 -1
  302. package/dist/domains/integrations/superpowers.d.ts.map +1 -1
  303. package/dist/domains/integrations/superpowers.js +93 -5
  304. package/dist/domains/integrations/superpowers.js.map +1 -1
  305. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  306. package/dist/domains/skill/platform-inspect.js +3 -3
  307. package/dist/domains/skill/platform-inspect.js.map +1 -1
  308. package/dist/domains/skill/platform-install.d.ts +4 -2
  309. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  310. package/dist/domains/skill/platform-install.js +16 -10
  311. package/dist/domains/skill/platform-install.js.map +1 -1
  312. package/dist/domains/skill/project-instructions.d.ts.map +1 -1
  313. package/dist/domains/skill/project-instructions.js +11 -3
  314. package/dist/domains/skill/project-instructions.js.map +1 -1
  315. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  316. package/dist/domains/skill/uninstall.js +39 -29
  317. package/dist/domains/skill/uninstall.js.map +1 -1
  318. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  319. package/dist/domains/workflow-contract/contained-atomic-write.js +18 -10
  320. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  321. package/dist/domains/workflow-contract/hook-write-policy.d.ts +9 -0
  322. package/dist/domains/workflow-contract/hook-write-policy.d.ts.map +1 -0
  323. package/dist/domains/workflow-contract/hook-write-policy.js +52 -0
  324. package/dist/domains/workflow-contract/hook-write-policy.js.map +1 -0
  325. package/dist/domains/workflow-contract/index.d.ts +2 -0
  326. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  327. package/dist/domains/workflow-contract/index.js +1 -0
  328. package/dist/domains/workflow-contract/index.js.map +1 -1
  329. package/dist/domains/workflow-contract/project-config.d.ts +4 -2
  330. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  331. package/dist/domains/workflow-contract/project-config.js +174 -2
  332. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  333. package/dist/domains/workflow-contract/protected-project-path.d.ts +13 -0
  334. package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
  335. package/dist/domains/workflow-contract/protected-project-path.js +83 -0
  336. package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
  337. package/dist/domains/workflow-contract/types.d.ts +13 -0
  338. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  339. package/dist/platform/fs/strip-bom.d.ts +10 -0
  340. package/dist/platform/fs/strip-bom.d.ts.map +1 -0
  341. package/dist/platform/fs/strip-bom.js +12 -0
  342. package/dist/platform/fs/strip-bom.js.map +1 -0
  343. package/dist/platform/install/platforms.d.ts +11 -0
  344. package/dist/platform/install/platforms.d.ts.map +1 -1
  345. package/dist/platform/install/platforms.js +49 -2
  346. package/dist/platform/install/platforms.js.map +1 -1
  347. package/dist/platform/paths/git-worktree.d.ts +7 -1
  348. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  349. package/dist/platform/paths/git-worktree.js +28 -7
  350. package/dist/platform/paths/git-worktree.js.map +1 -1
  351. package/dist/platform/process/external-command.d.ts +1 -0
  352. package/dist/platform/process/external-command.d.ts.map +1 -1
  353. package/dist/platform/process/external-command.js +2 -1
  354. package/dist/platform/process/external-command.js.map +1 -1
  355. package/eval/.env.example +115 -0
  356. package/eval/README.md +237 -14
  357. package/eval/langfuse/.env.example +9 -0
  358. package/eval/langfuse/tests/conftest.py +146 -0
  359. package/eval/langfuse/tests/tasks/test_tasks.py +109 -0
  360. package/eval/langfuse/tests/test_adapter.py +272 -0
  361. package/eval/langsmith/.env.example +16 -0
  362. package/eval/langsmith/tests/conftest.py +10 -1
  363. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +4 -2
  364. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +2 -2
  365. package/eval/local/tests/conftest.py +719 -83
  366. package/eval/local/tests/scaffold/fixtures/custom-agent/adapter.yaml +19 -0
  367. package/eval/local/tests/scaffold/test_agents.py +76 -0
  368. package/eval/local/tests/scaffold/test_aligned_comparison.py +70 -0
  369. package/eval/local/tests/scaffold/test_auto_tasks.py +350 -0
  370. package/eval/local/tests/scaffold/test_conftest_helpers.py +324 -18
  371. package/eval/local/tests/scaffold/test_custom_agents.py +174 -0
  372. package/eval/local/tests/scaffold/test_eval_context.py +217 -0
  373. package/eval/local/tests/scaffold/test_execution.py +364 -0
  374. package/eval/local/tests/scaffold/test_inline_tasks.py +56 -0
  375. package/eval/local/tests/scaffold/test_langfuse_trajectory.py +263 -0
  376. package/eval/local/tests/scaffold/test_langsmith_conftest.py +63 -0
  377. package/eval/local/tests/scaffold/test_logging.py +162 -0
  378. package/eval/local/tests/scaffold/test_manifest_tasks.py +76 -0
  379. package/eval/local/tests/scaffold/test_manifests.py +396 -0
  380. package/eval/local/tests/scaffold/test_native_aligned_eval.py +17 -0
  381. package/eval/local/tests/scaffold/test_profiles.py +64 -6
  382. package/eval/local/tests/scaffold/test_task_resolution.py +212 -0
  383. package/eval/local/tests/scaffold/test_utils.py +480 -4
  384. package/eval/local/tests/tasks/test_tasks.py +216 -14
  385. package/eval/pyproject.toml +5 -0
  386. package/eval/scaffold/__init__.py +6 -0
  387. package/eval/scaffold/docker/agent-overlay.Dockerfile +41 -0
  388. package/eval/scaffold/python/__init__.py +128 -20
  389. package/eval/scaffold/python/agents.py +239 -0
  390. package/eval/scaffold/python/aligned_comparison.py +156 -27
  391. package/eval/scaffold/python/auto_tasks.py +700 -0
  392. package/eval/scaffold/python/custom_agents.py +172 -0
  393. package/eval/scaffold/python/eval_context.py +236 -0
  394. package/eval/scaffold/python/eval_schema.py +135 -0
  395. package/eval/scaffold/python/execution.py +544 -0
  396. package/eval/scaffold/python/generated_task_cache.py +230 -0
  397. package/eval/scaffold/python/generic_llm_judge.py +41 -14
  398. package/eval/scaffold/python/inline_tasks.py +118 -0
  399. package/eval/scaffold/python/judge_config.py +158 -37
  400. package/eval/scaffold/python/langfuse_adapter.py +1023 -0
  401. package/eval/scaffold/python/llm_judge.py +68 -11
  402. package/eval/scaffold/python/logging.py +157 -17
  403. package/eval/scaffold/python/manifest_tasks.py +69 -0
  404. package/eval/scaffold/python/manifests.py +443 -22
  405. package/eval/scaffold/python/paths.py +11 -1
  406. package/eval/scaffold/python/task_resolution.py +176 -0
  407. package/eval/scaffold/python/tasks.py +17 -4
  408. package/eval/scaffold/python/utils.py +167 -11
  409. package/eval/scaffold/python/validation/core.py +48 -2
  410. package/eval/scaffold/python/validation/generic_rubric.py +9 -0
  411. package/eval/scaffold/python/validation/native_workflow.py +6 -1
  412. package/eval/scaffold/python/validation/rubric.py +16 -1
  413. package/eval/scaffold/shell/agent-runtime-config.sh +88 -0
  414. package/eval/scaffold/shell/docker.sh +534 -33
  415. package/eval/scaffold/shell/run-agent-runtime.sh +49 -0
  416. package/eval/scaffold/shell/run-claude-loop.sh +153 -14
  417. package/eval/schemas/comet.eval/v1alpha1.schema.json +244 -0
  418. package/package.json +18 -28
  419. package/dist/domains/dashboard/web/assets/arc-CkuYweSh.js +0 -1
  420. package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR--tTGrKam.js +0 -36
  421. package/dist/domains/dashboard/web/assets/blockDiagram-GPEHLZMM-DLKYOixs.js +0 -132
  422. package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +0 -1
  423. package/dist/domains/dashboard/web/assets/chunk-AQP2D5EJ-BUkV_rb7.js +0 -231
  424. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +0 -1
  425. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +0 -1
  426. package/dist/domains/dashboard/web/assets/dagre-BM42HDAG-DeOQo7bP.js +0 -4
  427. package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-IQd_jQwB.js +0 -43
  428. package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-Dllkdt0m.js +0 -10
  429. package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-DK36WkNN.js +0 -24
  430. package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-iqUnMYEh.js +0 -24
  431. package/dist/domains/dashboard/web/assets/erDiagram-TEJ5UH35-Bc64lzy8.js +0 -85
  432. package/dist/domains/dashboard/web/assets/flowDiagram-I6XJVG4X-UfOqef9j.js +0 -162
  433. package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-D-u6Aauc.js +0 -292
  434. package/dist/domains/dashboard/web/assets/index-BFwKBVTJ.css +0 -1
  435. package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +0 -257
  436. package/dist/domains/dashboard/web/assets/layout-SsrduOYp.js +0 -1
  437. package/dist/domains/dashboard/web/assets/mermaid.core-COBBjtVH.js +0 -301
  438. package/dist/domains/dashboard/web/assets/pieDiagram-4H26LBE5-CJro_XKk.js +0 -30
  439. package/dist/domains/dashboard/web/assets/purify.es-VaSPOPhr.js +0 -3
  440. package/dist/domains/dashboard/web/assets/sankeyDiagram-5OEKKPKP-Wx60WwHe.js +0 -40
  441. package/dist/domains/dashboard/web/assets/sequenceDiagram-3UESZ5HK-BiMsRFbc.js +0 -162
  442. package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-BrURMY0R.js +0 -1
  443. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +0 -1
  444. package/dist/domains/dashboard/web/assets/vennDiagram-CIIHVFJN-DGB16bvR.js +0 -34
  445. package/dist/domains/dashboard/web/assets/xychartDiagram-2RQKCTM6-DMzzwDVX.js +0 -7
  446. package/eval/local/tasks/comet-native-interrupted-transition/environment/.comet/config.yaml +0 -6
@@ -1,206 +1,206 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var xS=Object.create;var Yp=Object.defineProperty;var CS=Object.getOwnPropertyDescriptor;var AS=Object.getOwnPropertyNames;var _S=Object.getPrototypeOf,TS=Object.prototype.hasOwnProperty;var ks=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var IS=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of AS(t))!TS.call(e,n)&&n!==i&&Yp(e,n,{get:()=>t[n],enumerable:!(r=CS(t,n))||r.enumerable});return e};var xa=(e,t,i)=>(i=e!=null?xS(_S(e)):{},IS(t||!e||!e.__esModule?Yp(i,"default",{value:e,enumerable:!0}):i,e));var J=x(Ce=>{"use strict";var $u=Symbol.for("yaml.alias"),im=Symbol.for("yaml.document"),Ss=Symbol.for("yaml.map"),rm=Symbol.for("yaml.pair"),Ou=Symbol.for("yaml.scalar"),Es=Symbol.for("yaml.seq"),yi=Symbol.for("yaml.node.type"),HS=e=>!!e&&typeof e=="object"&&e[yi]===$u,DS=e=>!!e&&typeof e=="object"&&e[yi]===im,FS=e=>!!e&&typeof e=="object"&&e[yi]===Ss,MS=e=>!!e&&typeof e=="object"&&e[yi]===rm,nm=e=>!!e&&typeof e=="object"&&e[yi]===Ou,LS=e=>!!e&&typeof e=="object"&&e[yi]===Es;function am(e){if(e&&typeof e=="object")switch(e[yi]){case Ss:case Es:return!0}return!1}function BS(e){if(e&&typeof e=="object")switch(e[yi]){case $u:case Ss:case Ou:case Es:return!0}return!1}var qS=e=>(nm(e)||am(e))&&!!e.anchor;Ce.ALIAS=$u;Ce.DOC=im;Ce.MAP=Ss;Ce.NODE_TYPE=yi;Ce.PAIR=rm;Ce.SCALAR=Ou;Ce.SEQ=Es;Ce.hasAnchor=qS;Ce.isAlias=HS;Ce.isCollection=am;Ce.isDocument=DS;Ce.isMap=FS;Ce.isNode=BS;Ce.isPair=MS;Ce.isScalar=nm;Ce.isSeq=LS});var Ca=x(Hu=>{"use strict";var Se=J(),Ze=Symbol("break visit"),om=Symbol("skip children"),Zt=Symbol("remove node");function Ps(e,t){let i=sm(t);Se.isDocument(e)?fn(null,e.contents,i,Object.freeze([e]))===Zt&&(e.contents=null):fn(null,e,i,Object.freeze([]))}Ps.BREAK=Ze;Ps.SKIP=om;Ps.REMOVE=Zt;function fn(e,t,i,r){let n=cm(e,t,i,r);if(Se.isNode(n)||Se.isPair(n))return lm(e,r,n),fn(e,n,i,r);if(typeof n!="symbol"){if(Se.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=fn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===Ze)return Ze;o===Zt&&(t.items.splice(a,1),a-=1)}}}else if(Se.isPair(t)){r=Object.freeze(r.concat(t));let a=fn("key",t.key,i,r);if(a===Ze)return Ze;a===Zt&&(t.key=null);let o=fn("value",t.value,i,r);if(o===Ze)return Ze;o===Zt&&(t.value=null)}}return n}async function Rs(e,t){let i=sm(t);Se.isDocument(e)?await hn(null,e.contents,i,Object.freeze([e]))===Zt&&(e.contents=null):await hn(null,e,i,Object.freeze([]))}Rs.BREAK=Ze;Rs.SKIP=om;Rs.REMOVE=Zt;async function hn(e,t,i,r){let n=await cm(e,t,i,r);if(Se.isNode(n)||Se.isPair(n))return lm(e,r,n),hn(e,n,i,r);if(typeof n!="symbol"){if(Se.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await hn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===Ze)return Ze;o===Zt&&(t.items.splice(a,1),a-=1)}}}else if(Se.isPair(t)){r=Object.freeze(r.concat(t));let a=await hn("key",t.key,i,r);if(a===Ze)return Ze;a===Zt&&(t.key=null);let o=await hn("value",t.value,i,r);if(o===Ze)return Ze;o===Zt&&(t.value=null)}}return n}function sm(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 cm(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(Se.isMap(t))return i.Map?.(e,t,r);if(Se.isSeq(t))return i.Seq?.(e,t,r);if(Se.isPair(t))return i.Pair?.(e,t,r);if(Se.isScalar(t))return i.Scalar?.(e,t,r);if(Se.isAlias(t))return i.Alias?.(e,t,r)}function lm(e,t,i){let r=t[t.length-1];if(Se.isCollection(r))r.items[e]=i;else if(Se.isPair(r))e==="key"?r.key=i:r.value=i;else if(Se.isDocument(r))r.contents=i;else{let n=Se.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Hu.visit=Ps;Hu.visitAsync=Rs});var Du=x(dm=>{"use strict";var um=J(),VS=Ca(),WS={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},zS=e=>e.replace(/[!,[\]{}]/g,t=>WS[t]),Aa=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+zS(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&um.isNode(t.contents)){let a={};VS.visit(t.contents,(o,s)=>{um.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
- `)}};Aa.defaultYaml={explicit:!1,version:"1.2"};Aa.defaultTags={"!!":"tag:yaml.org,2002:"};dm.Directives=Aa});var xs=x(_a=>{"use strict";var fm=J(),JS=Ca();function GS(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 hm(e){let t=new Set;return JS.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function pm(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function US(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=hm(e));let o=pm(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(fm.isScalar(o.node)||fm.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}_a.anchorIsValid=GS;_a.anchorNames=hm;_a.createNodeAnchors=US;_a.findNewAnchor=pm});var Fu=x(mm=>{"use strict";function Ta(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Ta(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Ta(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Ta(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Ta(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}mm.applyReviver=Ta});var Di=x(gm=>{"use strict";var KS=J();function vm(e,t,i){if(Array.isArray(e))return e.map((r,n)=>vm(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!KS.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}gm.toJS=vm});var Cs=x(ym=>{"use strict";var YS=Fu(),wm=J(),XS=Di(),Mu=class{constructor(t){Object.defineProperty(this,wm.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!wm.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=XS.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?YS.applyReviver(a,{"":s},"",s):s}};ym.NodeBase=Mu});var Ia=x(Nm=>{"use strict";var QS=xs(),ZS=Ca(),pn=J(),eE=Cs(),tE=Di(),Lu=class extends eE.NodeBase{constructor(t){super(pn.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],ZS.visit(t,{Node:(a,o)=>{(pn.isAlias(o)||pn.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(tE.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=As(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(QS.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function As(e,t,i){if(pn.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(pn.isCollection(t)){let r=0;for(let n of t.items){let a=As(e,n,i);a>r&&(r=a)}return r}else if(pn.isPair(t)){let r=As(e,t.key,i),n=As(e,t.value,i);return Math.max(r,n)}return 1}Nm.Alias=Lu});var ye=x(Bu=>{"use strict";var iE=J(),rE=Cs(),nE=Di(),aE=e=>!e||typeof e!="function"&&typeof e!="object",Fi=class extends rE.NodeBase{constructor(t){super(iE.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:nE.toJS(this.value,t,i)}toString(){return String(this.value)}};Fi.BLOCK_FOLDED="BLOCK_FOLDED";Fi.BLOCK_LITERAL="BLOCK_LITERAL";Fi.PLAIN="PLAIN";Fi.QUOTE_DOUBLE="QUOTE_DOUBLE";Fi.QUOTE_SINGLE="QUOTE_SINGLE";Bu.Scalar=Fi;Bu.isScalarValue=aE});var ja=x(km=>{"use strict";var oE=Ia(),$r=J(),bm=ye(),sE="tag:yaml.org,2002:";function cE(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function lE(e,t,i){if($r.isDocument(e)&&(e=e.contents),$r.isNode(e))return e;if($r.isPair(e)){let d=i.schema[$r.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new oE.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=sE+t.slice(2));let l=cE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new bm.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[$r.MAP]:Symbol.iterator in Object(e)?o[$r.SEQ]:o[$r.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new bm.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}km.createNode=lE});var Ts=x(_s=>{"use strict";var uE=ja(),ei=J(),dE=Cs();function qu(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return uE.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Sm=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Vu=class extends dE.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>ei.isNode(r)||ei.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Sm(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(ei.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,qu(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(ei.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&ei.isScalar(a)?a.value:a:ei.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!ei.isPair(i))return!1;let r=i.value;return r==null||t&&ei.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return ei.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(ei.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,qu(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};_s.Collection=Vu;_s.collectionFromPath=qu;_s.isEmptyPath=Sm});var $a=x(Is=>{"use strict";var fE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Wu(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var hE=(e,t,i)=>e.endsWith(`
6
- `)?Wu(i,t):i.includes(`
4
+ var tE=Object.create;var gm=Object.defineProperty;var iE=Object.getOwnPropertyDescriptor;var rE=Object.getOwnPropertyNames;var nE=Object.getPrototypeOf,aE=Object.prototype.hasOwnProperty;var Cs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var oE=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of rE(t))!aE.call(e,n)&&n!==i&&gm(e,n,{get:()=>t[n],enumerable:!(r=iE(t,n))||r.enumerable});return e};var mn=(e,t,i)=>(i=e!=null?tE(nE(e)):{},oE(t||!e||!e.__esModule?gm(i,"default",{value:e,enumerable:!0}):i,e));var J=x(Ce=>{"use strict";var Ju=Symbol.for("yaml.alias"),Sm=Symbol.for("yaml.document"),As=Symbol.for("yaml.map"),Em=Symbol.for("yaml.pair"),Gu=Symbol.for("yaml.scalar"),_s=Symbol.for("yaml.seq"),Ni=Symbol.for("yaml.node.type"),uE=e=>!!e&&typeof e=="object"&&e[Ni]===Ju,dE=e=>!!e&&typeof e=="object"&&e[Ni]===Sm,fE=e=>!!e&&typeof e=="object"&&e[Ni]===As,hE=e=>!!e&&typeof e=="object"&&e[Ni]===Em,Pm=e=>!!e&&typeof e=="object"&&e[Ni]===Gu,pE=e=>!!e&&typeof e=="object"&&e[Ni]===_s;function Rm(e){if(e&&typeof e=="object")switch(e[Ni]){case As:case _s:return!0}return!1}function mE(e){if(e&&typeof e=="object")switch(e[Ni]){case Ju:case As:case Gu:case _s:return!0}return!1}var vE=e=>(Pm(e)||Rm(e))&&!!e.anchor;Ce.ALIAS=Ju;Ce.DOC=Sm;Ce.MAP=As;Ce.NODE_TYPE=Ni;Ce.PAIR=Em;Ce.SCALAR=Gu;Ce.SEQ=_s;Ce.hasAnchor=vE;Ce.isAlias=uE;Ce.isCollection=Rm;Ce.isDocument=dE;Ce.isMap=fE;Ce.isNode=mE;Ce.isPair=hE;Ce.isScalar=Pm;Ce.isSeq=pE});var ja=x(Uu=>{"use strict";var Ee=J(),et=Symbol("break visit"),xm=Symbol("skip children"),ei=Symbol("remove node");function Ts(e,t){let i=Cm(t);Ee.isDocument(e)?vn(null,e.contents,i,Object.freeze([e]))===ei&&(e.contents=null):vn(null,e,i,Object.freeze([]))}Ts.BREAK=et;Ts.SKIP=xm;Ts.REMOVE=ei;function vn(e,t,i,r){let n=Am(e,t,i,r);if(Ee.isNode(n)||Ee.isPair(n))return _m(e,r,n),vn(e,n,i,r);if(typeof n!="symbol"){if(Ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=vn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===et)return et;o===ei&&(t.items.splice(a,1),a-=1)}}}else if(Ee.isPair(t)){r=Object.freeze(r.concat(t));let a=vn("key",t.key,i,r);if(a===et)return et;a===ei&&(t.key=null);let o=vn("value",t.value,i,r);if(o===et)return et;o===ei&&(t.value=null)}}return n}async function Is(e,t){let i=Cm(t);Ee.isDocument(e)?await gn(null,e.contents,i,Object.freeze([e]))===ei&&(e.contents=null):await gn(null,e,i,Object.freeze([]))}Is.BREAK=et;Is.SKIP=xm;Is.REMOVE=ei;async function gn(e,t,i,r){let n=await Am(e,t,i,r);if(Ee.isNode(n)||Ee.isPair(n))return _m(e,r,n),gn(e,n,i,r);if(typeof n!="symbol"){if(Ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await gn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===et)return et;o===ei&&(t.items.splice(a,1),a-=1)}}}else if(Ee.isPair(t)){r=Object.freeze(r.concat(t));let a=await gn("key",t.key,i,r);if(a===et)return et;a===ei&&(t.key=null);let o=await gn("value",t.value,i,r);if(o===et)return et;o===ei&&(t.value=null)}}return n}function Cm(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 Am(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(Ee.isMap(t))return i.Map?.(e,t,r);if(Ee.isSeq(t))return i.Seq?.(e,t,r);if(Ee.isPair(t))return i.Pair?.(e,t,r);if(Ee.isScalar(t))return i.Scalar?.(e,t,r);if(Ee.isAlias(t))return i.Alias?.(e,t,r)}function _m(e,t,i){let r=t[t.length-1];if(Ee.isCollection(r))r.items[e]=i;else if(Ee.isPair(r))e==="key"?r.key=i:r.value=i;else if(Ee.isDocument(r))r.contents=i;else{let n=Ee.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Uu.visit=Ts;Uu.visitAsync=Is});var Ku=x(Im=>{"use strict";var Tm=J(),gE=ja(),wE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},yE=e=>e.replace(/[!,[\]{}]/g,t=>wE[t]),$a=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+yE(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&Tm.isNode(t.contents)){let a={};gE.visit(t.contents,(o,s)=>{Tm.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
5
+ `)}};$a.defaultYaml={explicit:!1,version:"1.2"};$a.defaultTags={"!!":"tag:yaml.org,2002:"};Im.Directives=$a});var js=x(Oa=>{"use strict";var jm=J(),NE=ja();function bE(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 $m(e){let t=new Set;return NE.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Om(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function kE(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=$m(e));let o=Om(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(jm.isScalar(o.node)||jm.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Oa.anchorIsValid=bE;Oa.anchorNames=$m;Oa.createNodeAnchors=kE;Oa.findNewAnchor=Om});var Yu=x(Hm=>{"use strict";function Ha(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Ha(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Ha(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Ha(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Ha(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Hm.applyReviver=Ha});var Fi=x(Mm=>{"use strict";var SE=J();function Dm(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Dm(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!SE.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}Mm.toJS=Dm});var $s=x(Lm=>{"use strict";var EE=Yu(),Fm=J(),PE=Fi(),Xu=class{constructor(t){Object.defineProperty(this,Fm.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!Fm.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=PE.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?EE.applyReviver(a,{"":s},"",s):s}};Lm.NodeBase=Xu});var Da=x(Bm=>{"use strict";var RE=js(),xE=ja(),wn=J(),CE=$s(),AE=Fi(),Qu=class extends CE.NodeBase{constructor(t){super(wn.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],xE.visit(t,{Node:(a,o)=>{(wn.isAlias(o)||wn.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(AE.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Os(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(RE.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Os(e,t,i){if(wn.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(wn.isCollection(t)){let r=0;for(let n of t.items){let a=Os(e,n,i);a>r&&(r=a)}return r}else if(wn.isPair(t)){let r=Os(e,t.key,i),n=Os(e,t.value,i);return Math.max(r,n)}return 1}Bm.Alias=Qu});var ye=x(Zu=>{"use strict";var _E=J(),TE=$s(),IE=Fi(),jE=e=>!e||typeof e!="function"&&typeof e!="object",Li=class extends TE.NodeBase{constructor(t){super(_E.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:IE.toJS(this.value,t,i)}toString(){return String(this.value)}};Li.BLOCK_FOLDED="BLOCK_FOLDED";Li.BLOCK_LITERAL="BLOCK_LITERAL";Li.PLAIN="PLAIN";Li.QUOTE_DOUBLE="QUOTE_DOUBLE";Li.QUOTE_SINGLE="QUOTE_SINGLE";Zu.Scalar=Li;Zu.isScalarValue=jE});var Ma=x(Vm=>{"use strict";var $E=Da(),Hr=J(),qm=ye(),OE="tag:yaml.org,2002:";function HE(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function DE(e,t,i){if(Hr.isDocument(e)&&(e=e.contents),Hr.isNode(e))return e;if(Hr.isPair(e)){let d=i.schema[Hr.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new $E.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=OE+t.slice(2));let l=HE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new qm.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Hr.MAP]:Symbol.iterator in Object(e)?o[Hr.SEQ]:o[Hr.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 qm.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Vm.createNode=DE});var Ds=x(Hs=>{"use strict";var ME=Ma(),ti=J(),FE=$s();function ed(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return ME.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Wm=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,td=class extends FE.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>ti.isNode(r)||ti.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Wm(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(ti.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,ed(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(ti.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&ti.isScalar(a)?a.value:a:ti.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!ti.isPair(i))return!1;let r=i.value;return r==null||t&&ti.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return ti.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(ti.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,ed(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};Hs.Collection=td;Hs.collectionFromPath=ed;Hs.isEmptyPath=Wm});var Fa=x(Ms=>{"use strict";var LE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function id(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var BE=(e,t,i)=>e.endsWith(`
6
+ `)?id(i,t):i.includes(`
7
7
  `)?`
8
- `+Wu(i,t):(e.endsWith(" ")?"":" ")+i;Is.indentComment=Wu;Is.lineComment=hE;Is.stringifyComment=fE});var Pm=x(Oa=>{"use strict";var pE="flow",zu="block",js="quoted";function mE(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,v=!1,p=-1,m=-1,b=-1;i===zu&&(p=Em(e,p,t.length),p!==-1&&(d=p+c));for(let P;P=e[p+=1];){if(i===js&&P==="\\"){switch(m=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}b=p}if(P===`
9
- `)i===zu&&(p=Em(e,p,t.length)),d=p+t.length+c,f=void 0;else{if(P===" "&&h&&h!==" "&&h!==`
10
- `&&h!==" "){let S=e[p+1];S&&S!==" "&&S!==`
11
- `&&S!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===js){for(;h===" "||h===" ";)h=P,P=e[p+=1],v=!0;let S=p>b+1?p-2:m-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+c,f=void 0}else v=!0}h=P}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let P=0;P<l.length;++P){let S=l[P],k=l[P+1]||e.length;S===0?y=`
12
- ${t}${e.slice(0,k)}`:(i===js&&u[S]&&(y+=`${e[S]}\\`),y+=`
13
- ${t}${e.slice(S+1,k)}`)}return y}function Em(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);r=t,n=t+1,a=e[n]}return r}Oa.FOLD_BLOCK=zu;Oa.FOLD_FLOW=pE;Oa.FOLD_QUOTED=js;Oa.foldFlowLines=mE});var Da=x(Rm=>{"use strict";var Ht=ye(),Mi=Pm(),Os=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Hs=e=>/^(%|---|\.\.\.)/m.test(e);function vE(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
- `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Ha(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Hs(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
8
+ `+id(i,t):(e.endsWith(" ")?"":" ")+i;Ms.indentComment=id;Ms.lineComment=BE;Ms.stringifyComment=LE});var Jm=x(La=>{"use strict";var qE="flow",rd="block",Fs="quoted";function VE(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,N=-1;i===rd&&(h=zm(e,h,t.length),h!==-1&&(d=h+c));for(let E;E=e[h+=1];){if(i===Fs&&E==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}N=h}if(E===`
9
+ `)i===rd&&(h=zm(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(E===" "&&p&&p!==" "&&p!==`
10
+ `&&p!==" "){let S=e[h+1];S&&S!==" "&&S!==`
11
+ `&&S!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===Fs){for(;p===" "||p===" ";)p=E,E=e[h+=1],v=!0;let S=h>N+1?h-2:m-1;if(u[S])return e;l.push(S),u[S]=!0,d=S+c,f=void 0}else v=!0}p=E}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let E=0;E<l.length;++E){let S=l[E],k=l[E+1]||e.length;S===0?y=`
12
+ ${t}${e.slice(0,k)}`:(i===Fs&&u[S]&&(y+=`${e[S]}\\`),y+=`
13
+ ${t}${e.slice(S+1,k)}`)}return y}function zm(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);r=t,n=t+1,a=e[n]}return r}La.FOLD_BLOCK=rd;La.FOLD_FLOW=qE;La.FOLD_QUOTED=Fs;La.foldFlowLines=VE});var qa=x(Gm=>{"use strict";var Mt=ye(),Bi=Jm(),Bs=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),qs=e=>/^(%|---|\.\.\.)/m.test(e);function WE(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Ba(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(qs(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
16
16
 
17
17
  `;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Mi.foldFlowLines(o,a,Mi.FOLD_QUOTED,Os(t,!1))}function Ju(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Ha(e,t);let i=t.indent||(Hs(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?r:Mi.foldFlowLines(r,i,Mi.FOLD_FLOW,Os(t,!1))}function mn(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Ha;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Ju:a&&!n?r=Ha:r=i?Ju:Ha}return r(e,t)}var Gu;try{Gu=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Bi.foldFlowLines(o,a,Bi.FOLD_QUOTED,Bs(t,!1))}function nd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Ba(e,t);let i=t.indent||(qs(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?r:Bi.foldFlowLines(r,i,Bi.FOLD_FLOW,Bs(t,!1))}function yn(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Ba;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=nd:a&&!n?r=Ba:r=i?nd:Ba}return r(e,t)}var ad;try{ad=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Gu=/\n+(?!\n|$)/g}function $s({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return mn(i,r);let l=r.indent||(r.forceBlockIndent||Hs(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ht.Scalar.BLOCK_FOLDED?!1:t===Ht.Scalar.BLOCK_LITERAL?!0:!vE(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{ad=/\n+(?!\n|$)/g}function Ls({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return yn(i,r);let l=r.indent||(r.forceBlockIndent||qs(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Mt.Scalar.BLOCK_FOLDED?!1:t===Mt.Scalar.BLOCK_LITERAL?!0:!WE(i,c,l.length);if(!i)return u?`|
24
24
  `:`>
25
25
  `;let d,f;for(f=i.length;f>0;--f){let k=i[f-1];if(k!==`
26
- `&&k!==" "&&k!==" ")break}let h=i.substring(f),v=h.indexOf(`
27
- `);v===-1?d="-":i===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(i=i.slice(0,-h.length),h[h.length-1]===`
28
- `&&(h=h.slice(0,-1)),h=h.replace(Gu,`$&${l}`));let p=!1,m,b=-1;for(m=0;m<i.length;++m){let k=i[m];if(k===" ")p=!0;else if(k===`
29
- `)b=m;else break}let y=i.substring(0,b<m?b+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let S=(p?l?"2":"1":"")+d;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=i.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),N=!1,R=Os(r,!0);o!=="folded"&&t!==Ht.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{N=!0});let w=Mi.foldFlowLines(`${y}${k}${h}`,l,Mi.FOLD_BLOCK,R);if(!N)return`>${S}
26
+ `&&k!==" "&&k!==" ")break}let p=i.substring(f),v=p.indexOf(`
27
+ `);v===-1?d="-":i===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
28
+ `&&(p=p.slice(0,-1)),p=p.replace(ad,`$&${l}`));let h=!1,m,N=-1;for(m=0;m<i.length;++m){let k=i[m];if(k===" ")h=!0;else if(k===`
29
+ `)N=m;else break}let y=i.substring(0,N<m?N+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let S=(h?l?"2":"1":"")+d;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=i.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,R=Bs(r,!0);o!=="folded"&&t!==Mt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{b=!0});let w=Bi.foldFlowLines(`${y}${k}${p}`,l,Bi.FOLD_BLOCK,R);if(!b)return`>${S}
31
31
  ${l}${w}`}return i=i.replace(/\n+/g,`$&${l}`),`|${S}
32
- ${l}${y}${i}${h}`}function gE(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
- `)||u&&/[[\]{},]/.test(a))return mn(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?mn(a,t):$s(e,t,i,r);if(!s&&!u&&n!==Ht.Scalar.PLAIN&&a.includes(`
35
- `))return $s(e,t,i,r);if(Hs(a)){if(c==="")return t.forceBlockIndent=!0,$s(e,t,i,r);if(s&&c===l)return mn(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return mn(a,t)}return s?d:Mi.foldFlowLines(d,c,Mi.FOLD_FLOW,Os(t,!1))}function wE(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Ht.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ht.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ht.Scalar.BLOCK_FOLDED:case Ht.Scalar.BLOCK_LITERAL:return n||a?mn(o.value,t):$s(o,t,i,r);case Ht.Scalar.QUOTE_DOUBLE:return Ha(o.value,t);case Ht.Scalar.QUOTE_SINGLE:return Ju(o.value,t);case Ht.Scalar.PLAIN:return gE(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Rm.stringifyString=wE});var Fa=x(Uu=>{"use strict";var yE=xs(),Li=J(),NE=$a(),bE=Da();function kE(e,t){let i=Object.assign({blockQuote:!0,commentString:NE.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function SE(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Li.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function EE(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Li.isScalar(e)||Li.isCollection(e))&&e.anchor;a&&yE.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function PE(e,t,i,r){if(Li.isPair(e))return e.toString(t,i,r);if(Li.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Li.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=SE(t.doc.schema.tags,a));let o=EE(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Li.isScalar(a)?bE.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Li.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Uu.createStringifyContext=kE;Uu.stringify=PE});var _m=x(Am=>{"use strict";var Ni=J(),xm=ye(),Cm=Fa(),Ma=$a();function RE({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=Ni.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ni.isCollection(e)||!Ni.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||Ni.isCollection(e)||(Ni.isScalar(e)?e.type===xm.Scalar.BLOCK_FOLDED||e.type===xm.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,p=!1,m=Cm.stringify(e,i,()=>v=!0,()=>p=!0);if(!h&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":h?`? ${m}`:m}else if(a&&!d||t==null&&h)return m=`? ${m}`,f&&!v?m+=Ma.lineComment(m,i.indent,l(f)):p&&n&&n(),m;v&&(f=null),h?(f&&(m+=Ma.lineComment(m,i.indent,l(f))),m=`? ${m}
38
- ${s}:`):(m=`${m}:`,f&&(m+=Ma.lineComment(m,i.indent,l(f))));let b,y,P;Ni.isNode(t)?(b=!!t.spaceBefore,y=t.commentBefore,P=t.comment):(b=!1,y=null,P=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&Ni.isScalar(t)&&(i.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!i.inFlow&&!h&&Ni.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Cm.stringify(t,i,()=>S=!0,()=>p=!0),N=" ";if(f||b||y){if(N=b?`
39
- `:"",y){let R=l(y);N+=`
40
- ${Ma.indentComment(R,i.indent)}`}k===""&&!i.inFlow?N===`
41
- `&&P&&(N=`
32
+ ${l}${y}${i}${p}`}function zE(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return yn(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?yn(a,t):Ls(e,t,i,r);if(!s&&!u&&n!==Mt.Scalar.PLAIN&&a.includes(`
35
+ `))return Ls(e,t,i,r);if(qs(a)){if(c==="")return t.forceBlockIndent=!0,Ls(e,t,i,r);if(s&&c===l)return yn(a,t)}let d=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return yn(a,t)}return s?d:Bi.foldFlowLines(d,c,Bi.FOLD_FLOW,Bs(t,!1))}function JE(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Mt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Mt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Mt.Scalar.BLOCK_FOLDED:case Mt.Scalar.BLOCK_LITERAL:return n||a?yn(o.value,t):Ls(o,t,i,r);case Mt.Scalar.QUOTE_DOUBLE:return Ba(o.value,t);case Mt.Scalar.QUOTE_SINGLE:return nd(o.value,t);case Mt.Scalar.PLAIN:return zE(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Gm.stringifyString=JE});var Va=x(od=>{"use strict";var GE=js(),qi=J(),UE=Fa(),KE=qa();function YE(e,t){let i=Object.assign({blockQuote:!0,commentString:UE.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function XE(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(qi.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function QE(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(qi.isScalar(e)||qi.isCollection(e))&&e.anchor;a&&GE.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function ZE(e,t,i,r){if(qi.isPair(e))return e.toString(t,i,r);if(qi.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=qi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=XE(t.doc.schema.tags,a));let o=QE(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):qi.isScalar(a)?KE.stringifyString(a,t,i,r):a.toString(t,i,r);return o?qi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}od.createStringifyContext=YE;od.stringify=ZE});var Xm=x(Ym=>{"use strict";var bi=J(),Um=ye(),Km=Va(),Wa=Fa();function eP({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=bi.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(bi.isCollection(e)||!bi.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||bi.isCollection(e)||(bi.isScalar(e)?e.type===Um.Scalar.BLOCK_FOLDED||e.type===Um.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=Km.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Wa.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Wa.lineComment(m,i.indent,l(f))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,f&&(m+=Wa.lineComment(m,i.indent,l(f))));let N,y,E;bi.isNode(t)?(N=!!t.spaceBefore,y=t.commentBefore,E=t.comment):(N=!1,y=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&bi.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&bi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let S=!1,k=Km.stringify(t,i,()=>S=!0,()=>h=!0),b=" ";if(f||N||y){if(b=N?`
39
+ `:"",y){let R=l(y);b+=`
40
+ ${Wa.indentComment(R,i.indent)}`}k===""&&!i.inFlow?b===`
41
+ `&&E&&(b=`
42
42
 
43
- `):N+=`
44
- ${i.indent}`}else if(!h&&Ni.isCollection(t)){let R=k[0],w=k.indexOf(`
45
- `),g=w!==-1,E=i.inFlow??t.flow??t.items.length===0;if(g||!E){let q=!1;if(g&&(R==="&"||R==="!")){let O=k.indexOf(" ");R==="&"&&O!==-1&&O<w&&k[O+1]==="!"&&(O=k.indexOf(" ",O+1)),(O===-1||w<O)&&(q=!0)}q||(N=`
43
+ `):b+=`
44
+ ${i.indent}`}else if(!p&&bi.isCollection(t)){let R=k[0],w=k.indexOf(`
45
+ `),g=w!==-1,P=i.inFlow??t.flow??t.items.length===0;if(g||!P){let D=!1;if(g&&(R==="&"||R==="!")){let O=k.indexOf(" ");R==="&"&&O!==-1&&O<w&&k[O+1]==="!"&&(O=k.indexOf(" ",O+1)),(O===-1||w<O)&&(D=!0)}D||(b=`
46
46
  ${i.indent}`)}}else(k===""||k[0]===`
47
- `)&&(N="");return m+=N+k,i.inFlow?S&&r&&r():P&&!S?m+=Ma.lineComment(m,i.indent,l(P)):p&&n&&n(),m}Am.stringifyPair=RE});var Yu=x(Ku=>{"use strict";var Tm=ks("process");function xE(e,...t){e==="debug"&&console.log(...t)}function CE(e,t){(e==="debug"||e==="warn")&&(typeof Tm.emitWarning=="function"?Tm.emitWarning(t):console.warn(t))}Ku.debug=xE;Ku.warn=CE});var Bs=x(Ls=>{"use strict";var Ms=J(),Im=ye(),Ds="<<",Fs={identify:e=>e===Ds||typeof e=="symbol"&&e.description===Ds,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Im.Scalar(Symbol(Ds)),{addToJSMap:jm}),stringify:()=>Ds},AE=(e,t)=>(Fs.identify(t)||Ms.isScalar(t)&&(!t.type||t.type===Im.Scalar.PLAIN)&&Fs.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Fs.tag&&i.default);function jm(e,t,i){let r=$m(e,i);if(Ms.isSeq(r))for(let n of r.items)Xu(e,t,n);else if(Array.isArray(r))for(let n of r)Xu(e,t,n);else Xu(e,t,r)}function Xu(e,t,i){let r=$m(e,i);if(!Ms.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function $m(e,t){return e&&Ms.isAlias(t)?t.resolve(e.doc,e):t}Ls.addMergeToJSMap=jm;Ls.isMergeKey=AE;Ls.merge=Fs});var Zu=x(Dm=>{"use strict";var _E=Yu(),Om=Bs(),TE=Fa(),Hm=J(),Qu=Di();function IE(e,t,{key:i,value:r}){if(Hm.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Om.isMergeKey(e,i))Om.addMergeToJSMap(e,t,r);else{let n=Qu.toJS(i,"",e);if(t instanceof Map)t.set(n,Qu.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=jE(i,n,e),o=Qu.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function jE(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Hm.isNode(e)&&i?.doc){let r=TE.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),_E.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Dm.addPairToJSMap=IE});var Bi=x(ed=>{"use strict";var Fm=ja(),$E=_m(),OE=Zu(),qs=J();function HE(e,t,i){let r=Fm.createNode(e,void 0,i),n=Fm.createNode(t,void 0,i);return new Vs(r,n)}var Vs=class e{constructor(t,i=null){Object.defineProperty(this,qs.NODE_TYPE,{value:qs.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return qs.isNode(i)&&(i=i.clone(t)),qs.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return OE.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?$E.stringifyPair(this,t,i,r):JSON.stringify(this)}};ed.Pair=Vs;ed.createPair=HE});var td=x(Lm=>{"use strict";var Or=J(),Mm=Fa(),Ws=$a();function DE(e,t,i){return(t.inFlow??e.flow?ME:FE)(e,t,i)}function FE({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if(Or.isNode(p))!d&&p.spaceBefore&&f.push(""),zs(i,f,p.commentBefore,d),p.comment&&(m=p.comment);else if(Or.isPair(p)){let y=Or.isNode(p.key)?p.key:null;y&&(!d&&y.spaceBefore&&f.push(""),zs(i,f,y.commentBefore,d))}d=!1;let b=Mm.stringify(p,u,()=>m=null,()=>d=!0);m&&(b+=Ws.lineComment(b,a,l(m))),d&&m&&(d=!1),f.push(r+b)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let p=f[v];h+=p?`
48
- ${c}${p}`:`
49
- `}}return e?(h+=`
50
- `+Ws.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function ME({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let p=e[v],m=null;if(Or.isNode(p))p.spaceBefore&&d.push(""),zs(t,d,p.commentBefore,!1),p.comment&&(m=p.comment);else if(Or.isPair(p)){let y=Or.isNode(p.key)?p.key:null;y&&(y.spaceBefore&&d.push(""),zs(t,d,y.commentBefore,!1),y.comment&&(l=!0));let P=Or.isNode(p.value)?p.value:null;P?(P.comment&&(m=P.comment),P.commentBefore&&(l=!0)):p.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let b=Mm.stringify(p,c,()=>m=null);l||(l=d.length>u||b.includes(`
51
- `)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,P)=>y+P.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),m&&(b+=Ws.lineComment(b,r,s(m))),d.push(b),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let v=d.reduce((p,m)=>p+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let p of d)v+=p?`
52
- ${a}${n}${p}`:`
47
+ `)&&(b="");return m+=b+k,i.inFlow?S&&r&&r():E&&!S?m+=Wa.lineComment(m,i.indent,l(E)):h&&n&&n(),m}Ym.stringifyPair=eP});var cd=x(sd=>{"use strict";var Qm=Cs("process");function tP(e,...t){e==="debug"&&console.log(...t)}function iP(e,t){(e==="debug"||e==="warn")&&(typeof Qm.emitWarning=="function"?Qm.emitWarning(t):console.warn(t))}sd.debug=tP;sd.warn=iP});var Gs=x(Js=>{"use strict";var zs=J(),Zm=ye(),Vs="<<",Ws={identify:e=>e===Vs||typeof e=="symbol"&&e.description===Vs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Zm.Scalar(Symbol(Vs)),{addToJSMap:ev}),stringify:()=>Vs},rP=(e,t)=>(Ws.identify(t)||zs.isScalar(t)&&(!t.type||t.type===Zm.Scalar.PLAIN)&&Ws.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===Ws.tag&&i.default);function ev(e,t,i){let r=tv(e,i);if(zs.isSeq(r))for(let n of r.items)ld(e,t,n);else if(Array.isArray(r))for(let n of r)ld(e,t,n);else ld(e,t,r)}function ld(e,t,i){let r=tv(e,i);if(!zs.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function tv(e,t){return e&&zs.isAlias(t)?t.resolve(e.doc,e):t}Js.addMergeToJSMap=ev;Js.isMergeKey=rP;Js.merge=Ws});var dd=x(nv=>{"use strict";var nP=cd(),iv=Gs(),aP=Va(),rv=J(),ud=Fi();function oP(e,t,{key:i,value:r}){if(rv.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(iv.isMergeKey(e,i))iv.addMergeToJSMap(e,t,r);else{let n=ud.toJS(i,"",e);if(t instanceof Map)t.set(n,ud.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=sP(i,n,e),o=ud.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function sP(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(rv.isNode(e)&&i?.doc){let r=aP.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),nP.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}nv.addPairToJSMap=oP});var Vi=x(fd=>{"use strict";var av=Ma(),cP=Xm(),lP=dd(),Us=J();function uP(e,t,i){let r=av.createNode(e,void 0,i),n=av.createNode(t,void 0,i);return new Ks(r,n)}var Ks=class e{constructor(t,i=null){Object.defineProperty(this,Us.NODE_TYPE,{value:Us.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return Us.isNode(i)&&(i=i.clone(t)),Us.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return lP.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?cP.stringifyPair(this,t,i,r):JSON.stringify(this)}};fd.Pair=Ks;fd.createPair=uP});var hd=x(sv=>{"use strict";var Dr=J(),ov=Va(),Ys=Fa();function dP(e,t,i){return(t.inFlow??e.flow?hP:fP)(e,t,i)}function fP({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(Dr.isNode(h))!d&&h.spaceBefore&&f.push(""),Xs(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(Dr.isPair(h)){let y=Dr.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Xs(i,f,y.commentBefore,d))}d=!1;let N=ov.stringify(h,u,()=>m=null,()=>d=!0);m&&(N+=Ys.lineComment(N,a,l(m))),d&&m&&(d=!1),f.push(r+N)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
48
+ ${c}${h}`:`
49
+ `}}return e?(p+=`
50
+ `+Ys.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function hP({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(Dr.isNode(h))h.spaceBefore&&d.push(""),Xs(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(Dr.isPair(h)){let y=Dr.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Xs(t,d,y.commentBefore,!1),y.comment&&(l=!0));let E=Dr.isNode(h.value)?h.value:null;E?(E.comment&&(m=E.comment),E.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let N=ov.stringify(h,c,()=>m=null);l||(l=d.length>u||N.includes(`
51
+ `)),v<e.length-1?N+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,E)=>y+E.length+2,2)+(N.length+2)>t.options.lineWidth)),l&&(N+=",")),m&&(N+=Ys.lineComment(N,r,s(m))),d.push(N),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?`
52
+ ${a}${n}${h}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function zs({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Ws.indentComment(t(r),e);i.push(a.trimStart())}}Lm.stringifyCollection=DE});var Vi=x(rd=>{"use strict";var LE=td(),BE=Zu(),qE=Ts(),qi=J(),Js=Bi(),VE=ye();function La(e,t){let i=qi.isScalar(t)?t.value:t;for(let r of e)if(qi.isPair(r)&&(r.key===t||r.key===i||qi.isScalar(r.key)&&r.key.value===i))return r}var id=class extends qE.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(qi.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Js.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;qi.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Js.Pair(t,t?.value):r=new Js.Pair(t.key,t.value);let n=La(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);qi.isScalar(n.value)&&VE.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=La(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=La(this.items,t)?.value;return(!i&&qi.isScalar(n)?n.value:n)??void 0}has(t){return!!La(this.items,t)}set(t,i){this.add(new Js.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)BE.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!qi.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),LE.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};rd.YAMLMap=id;rd.findPair=La});var vn=x(qm=>{"use strict";var WE=J(),Bm=Vi(),zE={collection:"map",default:!0,nodeClass:Bm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return WE.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Bm.YAMLMap.from(e,t,i)};qm.map=zE});var Wi=x(Vm=>{"use strict";var JE=ja(),GE=td(),UE=Ts(),Us=J(),KE=ye(),YE=Di(),nd=class extends UE.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Us.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Gs(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Gs(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Us.isScalar(n)?n.value:n}has(t){let i=Gs(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Gs(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Us.isScalar(n)&&KE.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(YE.toJS(a,String(n++),i));return r}toString(t,i,r){return t?GE.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(JE.createNode(s,void 0,r))}}return a}};function Gs(e){let t=Us.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Vm.YAMLSeq=nd});var gn=x(zm=>{"use strict";var XE=J(),Wm=Wi(),QE={collection:"seq",default:!0,nodeClass:Wm.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return XE.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Wm.YAMLSeq.from(e,t,i)};zm.seq=QE});var Ba=x(Jm=>{"use strict";var ZE=Da(),eP={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),ZE.stringifyString(e,t,i,r)}};Jm.string=eP});var Ks=x(Km=>{"use strict";var Gm=ye(),Um={identify:e=>e==null,createNode:()=>new Gm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Gm.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Um.test.test(e)?e:t.options.nullStr};Km.nullTag=Um});var ad=x(Xm=>{"use strict";var tP=ye(),Ym={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new tP.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Ym.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Xm.boolTag=Ym});var wn=x(Qm=>{"use strict";function iP({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Qm.stringifyNumber=iP});var sd=x(Ys=>{"use strict";var rP=ye(),od=wn(),nP={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:od.stringifyNumber},aP={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():od.stringifyNumber(e)}},oP={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 rP.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:od.stringifyNumber};Ys.float=oP;Ys.floatExp=aP;Ys.floatNaN=nP});var ld=x(Qs=>{"use strict";var Zm=wn(),Xs=e=>typeof e=="bigint"||Number.isInteger(e),cd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function ev(e,t,i){let{value:r}=e;return Xs(r)&&r>=0?i+r.toString(t):Zm.stringifyNumber(e)}var sP={identify:e=>Xs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>cd(e,2,8,i),stringify:e=>ev(e,8,"0o")},cP={identify:Xs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>cd(e,0,10,i),stringify:Zm.stringifyNumber},lP={identify:e=>Xs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>cd(e,2,16,i),stringify:e=>ev(e,16,"0x")};Qs.int=cP;Qs.intHex=lP;Qs.intOct=sP});var iv=x(tv=>{"use strict";var uP=vn(),dP=Ks(),fP=gn(),hP=Ba(),pP=ad(),ud=sd(),dd=ld(),mP=[uP.map,fP.seq,hP.string,dP.nullTag,pP.boolTag,dd.intOct,dd.int,dd.intHex,ud.floatNaN,ud.floatExp,ud.float];tv.schema=mP});var av=x(nv=>{"use strict";var vP=ye(),gP=vn(),wP=gn();function rv(e){return typeof e=="bigint"||Number.isInteger(e)}var Zs=({value:e})=>JSON.stringify(e),yP=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Zs},{identify:e=>e==null,createNode:()=>new vP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Zs},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Zs},{identify:rv,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})=>rv(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:Zs}],NP={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},bP=[gP.map,wP.seq].concat(yP,NP);nv.schema=bP});var hd=x(ov=>{"use strict";var qa=ks("buffer"),fd=ye(),kP=Da(),SP={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof qa.Buffer=="function")return qa.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof qa.Buffer=="function")s=o instanceof qa.Buffer?o.toString("base64"):qa.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=fd.Scalar.BLOCK_LITERAL),t!==fd.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===fd.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return kP.stringifyString({comment:e,type:t,value:s},r,n,a)}};ov.binary=SP});var ic=x(tc=>{"use strict";var ec=J(),pd=Bi(),EP=ye(),PP=Wi();function sv(e,t){if(ec.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!ec.isPair(r)){if(ec.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new pd.Pair(new EP.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
54
+ ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Xs({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Ys.indentComment(t(r),e);i.push(a.trimStart())}}sv.stringifyCollection=dP});var zi=x(md=>{"use strict";var pP=hd(),mP=dd(),vP=Ds(),Wi=J(),Qs=Vi(),gP=ye();function za(e,t){let i=Wi.isScalar(t)?t.value:t;for(let r of e)if(Wi.isPair(r)&&(r.key===t||r.key===i||Wi.isScalar(r.key)&&r.key.value===i))return r}var pd=class extends vP.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Wi.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Qs.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Wi.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Qs.Pair(t,t?.value):r=new Qs.Pair(t.key,t.value);let n=za(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Wi.isScalar(n.value)&&gP.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=za(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=za(this.items,t)?.value;return(!i&&Wi.isScalar(n)?n.value:n)??void 0}has(t){return!!za(this.items,t)}set(t,i){this.add(new Qs.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)mP.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Wi.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),pP.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};md.YAMLMap=pd;md.findPair=za});var Nn=x(lv=>{"use strict";var wP=J(),cv=zi(),yP={collection:"map",default:!0,nodeClass:cv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return wP.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>cv.YAMLMap.from(e,t,i)};lv.map=yP});var Ji=x(uv=>{"use strict";var NP=Ma(),bP=hd(),kP=Ds(),ec=J(),SP=ye(),EP=Fi(),vd=class extends kP.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ec.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Zs(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Zs(t);if(typeof r!="number")return;let n=this.items[r];return!i&&ec.isScalar(n)?n.value:n}has(t){let i=Zs(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Zs(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];ec.isScalar(n)&&SP.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(EP.toJS(a,String(n++),i));return r}toString(t,i,r){return t?bP.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(NP.createNode(s,void 0,r))}}return a}};function Zs(e){let t=ec.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}uv.YAMLSeq=vd});var bn=x(fv=>{"use strict";var PP=J(),dv=Ji(),RP={collection:"seq",default:!0,nodeClass:dv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return PP.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>dv.YAMLSeq.from(e,t,i)};fv.seq=RP});var Ja=x(hv=>{"use strict";var xP=qa(),CP={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),xP.stringifyString(e,t,i,r)}};hv.string=CP});var tc=x(vv=>{"use strict";var pv=ye(),mv={identify:e=>e==null,createNode:()=>new pv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new pv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&mv.test.test(e)?e:t.options.nullStr};vv.nullTag=mv});var gd=x(wv=>{"use strict";var AP=ye(),gv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new AP.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&gv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};wv.boolTag=gv});var kn=x(yv=>{"use strict";function _P({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}yv.stringifyNumber=_P});var yd=x(ic=>{"use strict";var TP=ye(),wd=kn(),IP={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:wd.stringifyNumber},jP={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():wd.stringifyNumber(e)}},$P={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 TP.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:wd.stringifyNumber};ic.float=$P;ic.floatExp=jP;ic.floatNaN=IP});var bd=x(nc=>{"use strict";var Nv=kn(),rc=e=>typeof e=="bigint"||Number.isInteger(e),Nd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function bv(e,t,i){let{value:r}=e;return rc(r)&&r>=0?i+r.toString(t):Nv.stringifyNumber(e)}var OP={identify:e=>rc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Nd(e,2,8,i),stringify:e=>bv(e,8,"0o")},HP={identify:rc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Nd(e,0,10,i),stringify:Nv.stringifyNumber},DP={identify:e=>rc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Nd(e,2,16,i),stringify:e=>bv(e,16,"0x")};nc.int=HP;nc.intHex=DP;nc.intOct=OP});var Sv=x(kv=>{"use strict";var MP=Nn(),FP=tc(),LP=bn(),BP=Ja(),qP=gd(),kd=yd(),Sd=bd(),VP=[MP.map,LP.seq,BP.string,FP.nullTag,qP.boolTag,Sd.intOct,Sd.int,Sd.intHex,kd.floatNaN,kd.floatExp,kd.float];kv.schema=VP});var Rv=x(Pv=>{"use strict";var WP=ye(),zP=Nn(),JP=bn();function Ev(e){return typeof e=="bigint"||Number.isInteger(e)}var ac=({value:e})=>JSON.stringify(e),GP=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ac},{identify:e=>e==null,createNode:()=>new WP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ac},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ac},{identify:Ev,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})=>Ev(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:ac}],UP={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},KP=[zP.map,JP.seq].concat(GP,UP);Pv.schema=KP});var Pd=x(xv=>{"use strict";var Ga=Cs("buffer"),Ed=ye(),YP=qa(),XP={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Ga.Buffer=="function")return Ga.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof Ga.Buffer=="function")s=o instanceof Ga.Buffer?o.toString("base64"):Ga.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=Ed.Scalar.BLOCK_LITERAL),t!==Ed.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Ed.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return YP.stringifyString({comment:e,type:t,value:s},r,n,a)}};xv.binary=XP});var cc=x(sc=>{"use strict";var oc=J(),Rd=Vi(),QP=ye(),ZP=Ji();function Cv(e,t){if(oc.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!oc.isPair(r)){if(oc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Rd.Pair(new QP.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
56
56
  ${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
57
- ${a.comment}`:r.comment}r=n}e.items[i]=ec.isPair(r)?r:new pd.Pair(r)}}else t("Expected a sequence for this tag");return e}function cv(e,t,i){let{replacer:r}=i,n=new PP.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(pd.createPair(s,c,i))}return n}var RP={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:sv,createNode:cv};tc.createPairs=cv;tc.pairs=RP;tc.resolvePairs=sv});var gd=x(vd=>{"use strict";var lv=J(),md=Di(),Va=Vi(),xP=Wi(),uv=ic(),Hr=class e extends xP.YAMLSeq{constructor(){super(),this.add=Va.YAMLMap.prototype.add.bind(this),this.delete=Va.YAMLMap.prototype.delete.bind(this),this.get=Va.YAMLMap.prototype.get.bind(this),this.has=Va.YAMLMap.prototype.has.bind(this),this.set=Va.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(lv.isPair(n)?(a=md.toJS(n.key,"",i),o=md.toJS(n.value,a,i)):a=md.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=uv.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Hr.tag="tag:yaml.org,2002:omap";var CP={collection:"seq",identify:e=>e instanceof Map,nodeClass:Hr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=uv.resolvePairs(e,t),r=[];for(let{key:n}of i.items)lv.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Hr,i)},createNode:(e,t,i)=>Hr.from(e,t,i)};vd.YAMLOMap=Hr;vd.omap=CP});var mv=x(wd=>{"use strict";var dv=ye();function fv({value:e,source:t},i){return t&&(e?hv:pv).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var hv={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 dv.Scalar(!0),stringify:fv},pv={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new dv.Scalar(!1),stringify:fv};wd.falseTag=pv;wd.trueTag=hv});var vv=x(rc=>{"use strict";var AP=ye(),yd=wn(),_P={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:yd.stringifyNumber},TP={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():yd.stringifyNumber(e)}},IP={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new AP.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:yd.stringifyNumber};rc.float=IP;rc.floatExp=TP;rc.floatNaN=_P});var wv=x(za=>{"use strict";var gv=wn(),Wa=e=>typeof e=="bigint"||Number.isInteger(e);function nc(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Nd(e,t,i){let{value:r}=e;if(Wa(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return gv.stringifyNumber(e)}var jP={identify:Wa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>nc(e,2,2,i),stringify:e=>Nd(e,2,"0b")},$P={identify:Wa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>nc(e,1,8,i),stringify:e=>Nd(e,8,"0")},OP={identify:Wa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>nc(e,0,10,i),stringify:gv.stringifyNumber},HP={identify:Wa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>nc(e,2,16,i),stringify:e=>Nd(e,16,"0x")};za.int=OP;za.intBin=jP;za.intHex=HP;za.intOct=$P});var kd=x(bd=>{"use strict";var sc=J(),ac=Bi(),oc=Vi(),Dr=class e extends oc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;sc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new ac.Pair(t.key,null):i=new ac.Pair(t,null),oc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=oc.findPair(this.items,t);return!i&&sc.isPair(r)?sc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=oc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new ac.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(ac.createPair(o,null,r));return a}};Dr.tag="tag:yaml.org,2002:set";var DP={collection:"map",identify:e=>e instanceof Set,nodeClass:Dr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Dr.from(e,t,i),resolve(e,t){if(sc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Dr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};bd.YAMLSet=Dr;bd.set=DP});var Ed=x(cc=>{"use strict";var FP=wn();function Sd(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function yv(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return FP.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var MP={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})=>Sd(e,i),stringify:yv},LP={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=>Sd(e,!1),stringify:yv},Nv={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(Nv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Sd(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$/,"")??""};cc.floatTime=LP;cc.intTime=MP;cc.timestamp=Nv});var Sv=x(kv=>{"use strict";var BP=vn(),qP=Ks(),VP=gn(),WP=Ba(),zP=hd(),bv=mv(),Pd=vv(),lc=wv(),JP=Bs(),GP=gd(),UP=ic(),KP=kd(),Rd=Ed(),YP=[BP.map,VP.seq,WP.string,qP.nullTag,bv.trueTag,bv.falseTag,lc.intBin,lc.intOct,lc.int,lc.intHex,Pd.floatNaN,Pd.floatExp,Pd.float,zP.binary,JP.merge,GP.omap,UP.pairs,KP.set,Rd.intTime,Rd.floatTime,Rd.timestamp];kv.schema=YP});var jv=x(Ad=>{"use strict";var xv=vn(),XP=Ks(),Cv=gn(),QP=Ba(),ZP=ad(),xd=sd(),Cd=ld(),eR=iv(),tR=av(),Av=hd(),Ja=Bs(),_v=gd(),Tv=ic(),Ev=Sv(),Iv=kd(),uc=Ed(),Pv=new Map([["core",eR.schema],["failsafe",[xv.map,Cv.seq,QP.string]],["json",tR.schema],["yaml11",Ev.schema],["yaml-1.1",Ev.schema]]),Rv={binary:Av.binary,bool:ZP.boolTag,float:xd.float,floatExp:xd.floatExp,floatNaN:xd.floatNaN,floatTime:uc.floatTime,int:Cd.int,intHex:Cd.intHex,intOct:Cd.intOct,intTime:uc.intTime,map:xv.map,merge:Ja.merge,null:XP.nullTag,omap:_v.omap,pairs:Tv.pairs,seq:Cv.seq,set:Iv.set,timestamp:uc.timestamp},iR={"tag:yaml.org,2002:binary":Av.binary,"tag:yaml.org,2002:merge":Ja.merge,"tag:yaml.org,2002:omap":_v.omap,"tag:yaml.org,2002:pairs":Tv.pairs,"tag:yaml.org,2002:set":Iv.set,"tag:yaml.org,2002:timestamp":uc.timestamp};function rR(e,t,i){let r=Pv.get(t);if(r&&!e)return i&&!r.includes(Ja.merge)?r.concat(Ja.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Pv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Ja.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Rv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Rv).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},[])}Ad.coreKnownTags=iR;Ad.getTags=rR});var Id=x($v=>{"use strict";var _d=J(),nR=vn(),aR=gn(),oR=Ba(),dc=jv(),sR=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Td=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?dc.getTags(t,"compat"):t?dc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?dc.coreKnownTags:{},this.tags=dc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,_d.MAP,{value:nR.map}),Object.defineProperty(this,_d.SCALAR,{value:oR.string}),Object.defineProperty(this,_d.SEQ,{value:aR.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?sR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};$v.Schema=Td});var Hv=x(Ov=>{"use strict";var cR=J(),jd=Fa(),Ga=$a();function lR(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=jd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Ga.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(cR.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Ga.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=jd.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ga.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(jd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(Ga.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(Ga.indentComment(a(c),"")))}return i.join(`
57
+ ${a.comment}`:r.comment}r=n}e.items[i]=oc.isPair(r)?r:new Rd.Pair(r)}}else t("Expected a sequence for this tag");return e}function Av(e,t,i){let{replacer:r}=i,n=new ZP.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Rd.createPair(s,c,i))}return n}var eR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Cv,createNode:Av};sc.createPairs=Av;sc.pairs=eR;sc.resolvePairs=Cv});var Ad=x(Cd=>{"use strict";var _v=J(),xd=Fi(),Ua=zi(),tR=Ji(),Tv=cc(),Mr=class e extends tR.YAMLSeq{constructor(){super(),this.add=Ua.YAMLMap.prototype.add.bind(this),this.delete=Ua.YAMLMap.prototype.delete.bind(this),this.get=Ua.YAMLMap.prototype.get.bind(this),this.has=Ua.YAMLMap.prototype.has.bind(this),this.set=Ua.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(_v.isPair(n)?(a=xd.toJS(n.key,"",i),o=xd.toJS(n.value,a,i)):a=xd.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=Tv.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Mr.tag="tag:yaml.org,2002:omap";var iR={collection:"seq",identify:e=>e instanceof Map,nodeClass:Mr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Tv.resolvePairs(e,t),r=[];for(let{key:n}of i.items)_v.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Mr,i)},createNode:(e,t,i)=>Mr.from(e,t,i)};Cd.YAMLOMap=Mr;Cd.omap=iR});var Hv=x(_d=>{"use strict";var Iv=ye();function jv({value:e,source:t},i){return t&&(e?$v:Ov).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var $v={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 Iv.Scalar(!0),stringify:jv},Ov={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 Iv.Scalar(!1),stringify:jv};_d.falseTag=Ov;_d.trueTag=$v});var Dv=x(lc=>{"use strict";var rR=ye(),Td=kn(),nR={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:Td.stringifyNumber},aR={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():Td.stringifyNumber(e)}},oR={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 rR.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Td.stringifyNumber};lc.float=oR;lc.floatExp=aR;lc.floatNaN=nR});var Fv=x(Ya=>{"use strict";var Mv=kn(),Ka=e=>typeof e=="bigint"||Number.isInteger(e);function uc(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Id(e,t,i){let{value:r}=e;if(Ka(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Mv.stringifyNumber(e)}var sR={identify:Ka,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>uc(e,2,2,i),stringify:e=>Id(e,2,"0b")},cR={identify:Ka,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>uc(e,1,8,i),stringify:e=>Id(e,8,"0")},lR={identify:Ka,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>uc(e,0,10,i),stringify:Mv.stringifyNumber},uR={identify:Ka,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>uc(e,2,16,i),stringify:e=>Id(e,16,"0x")};Ya.int=lR;Ya.intBin=sR;Ya.intHex=uR;Ya.intOct=cR});var $d=x(jd=>{"use strict";var hc=J(),dc=Vi(),fc=zi(),Fr=class e extends fc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;hc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new dc.Pair(t.key,null):i=new dc.Pair(t,null),fc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=fc.findPair(this.items,t);return!i&&hc.isPair(r)?hc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=fc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new dc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(dc.createPair(o,null,r));return a}};Fr.tag="tag:yaml.org,2002:set";var dR={collection:"map",identify:e=>e instanceof Set,nodeClass:Fr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Fr.from(e,t,i),resolve(e,t){if(hc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Fr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};jd.YAMLSet=Fr;jd.set=dR});var Hd=x(pc=>{"use strict";var fR=kn();function Od(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function Lv(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return fR.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var hR={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})=>Od(e,i),stringify:Lv},pR={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=>Od(e,!1),stringify:Lv},Bv={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(Bv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Od(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$/,"")??""};pc.floatTime=pR;pc.intTime=hR;pc.timestamp=Bv});var Wv=x(Vv=>{"use strict";var mR=Nn(),vR=tc(),gR=bn(),wR=Ja(),yR=Pd(),qv=Hv(),Dd=Dv(),mc=Fv(),NR=Gs(),bR=Ad(),kR=cc(),SR=$d(),Md=Hd(),ER=[mR.map,gR.seq,wR.string,vR.nullTag,qv.trueTag,qv.falseTag,mc.intBin,mc.intOct,mc.int,mc.intHex,Dd.floatNaN,Dd.floatExp,Dd.float,yR.binary,NR.merge,bR.omap,kR.pairs,SR.set,Md.intTime,Md.floatTime,Md.timestamp];Vv.schema=ER});var eg=x(Bd=>{"use strict";var Uv=Nn(),PR=tc(),Kv=bn(),RR=Ja(),xR=gd(),Fd=yd(),Ld=bd(),CR=Sv(),AR=Rv(),Yv=Pd(),Xa=Gs(),Xv=Ad(),Qv=cc(),zv=Wv(),Zv=$d(),vc=Hd(),Jv=new Map([["core",CR.schema],["failsafe",[Uv.map,Kv.seq,RR.string]],["json",AR.schema],["yaml11",zv.schema],["yaml-1.1",zv.schema]]),Gv={binary:Yv.binary,bool:xR.boolTag,float:Fd.float,floatExp:Fd.floatExp,floatNaN:Fd.floatNaN,floatTime:vc.floatTime,int:Ld.int,intHex:Ld.intHex,intOct:Ld.intOct,intTime:vc.intTime,map:Uv.map,merge:Xa.merge,null:PR.nullTag,omap:Xv.omap,pairs:Qv.pairs,seq:Kv.seq,set:Zv.set,timestamp:vc.timestamp},_R={"tag:yaml.org,2002:binary":Yv.binary,"tag:yaml.org,2002:merge":Xa.merge,"tag:yaml.org,2002:omap":Xv.omap,"tag:yaml.org,2002:pairs":Qv.pairs,"tag:yaml.org,2002:set":Zv.set,"tag:yaml.org,2002:timestamp":vc.timestamp};function TR(e,t,i){let r=Jv.get(t);if(r&&!e)return i&&!r.includes(Xa.merge)?r.concat(Xa.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Jv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(Xa.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Gv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Gv).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},[])}Bd.coreKnownTags=_R;Bd.getTags=TR});var Wd=x(tg=>{"use strict";var qd=J(),IR=Nn(),jR=bn(),$R=Ja(),gc=eg(),OR=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Vd=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?gc.getTags(t,"compat"):t?gc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?gc.coreKnownTags:{},this.tags=gc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,qd.MAP,{value:IR.map}),Object.defineProperty(this,qd.SCALAR,{value:$R.string}),Object.defineProperty(this,qd.SEQ,{value:jR.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?OR:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};tg.Schema=Vd});var rg=x(ig=>{"use strict";var HR=J(),zd=Va(),Qa=Fa();function DR(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=zd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Qa.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(HR.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Qa.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=zd.stringify(e.contents,n,()=>s=null,c);s&&(l+=Qa.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(zd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(Qa.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(Qa.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}Ov.stringifyDocument=lR});var Ua=x(Dv=>{"use strict";var uR=Ia(),yn=Ts(),Nt=J(),dR=Bi(),fR=Di(),hR=Id(),pR=Hv(),$d=xs(),mR=Fu(),vR=ja(),Od=Du(),Hd=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Nt.NODE_TYPE,{value:Nt.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Od.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[Nt.NODE_TYPE]:{value:Nt.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=Nt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Nn(this.contents)&&this.contents.add(t)}addIn(t,i){Nn(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=$d.anchorNames(this);t.anchor=!i||r.has(i)?$d.findNewAnchor(i||"a",r):i}return new uR.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,b=i.filter(m).map(String);b.length>0&&(i=i.concat(b)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=$d.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=vR.createNode(t,u,v);return s&&Nt.isCollection(p)&&(p.flow=!0),f(),p}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new dR.Pair(n,a)}delete(t){return Nn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return yn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Nn(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Nt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return yn.isEmptyPath(t)?!i&&Nt.isScalar(this.contents)?this.contents.value:this.contents:Nt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Nt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return yn.isEmptyPath(t)?this.contents!==void 0:Nt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=yn.collectionFromPath(this.schema,[t],i):Nn(this.contents)&&this.contents.set(t,i)}setIn(t,i){yn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=yn.collectionFromPath(this.schema,Array.from(t),i):Nn(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Od.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Od.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new hR.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=fR.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"?mR.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 pR.stringifyDocument(this,t)}};function Nn(e){if(Nt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Dv.Document=Hd});var Xa=x(Ya=>{"use strict";var Ka=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Dd=class extends Ka{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Fd=class extends Ka{constructor(t,i,r){super("YAMLWarning",t,i,r)}},gR=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}ig.stringifyDocument=DR});var Za=x(ng=>{"use strict";var MR=Da(),Sn=Ds(),kt=J(),FR=Vi(),LR=Fi(),BR=Wd(),qR=rg(),Jd=js(),VR=Yu(),WR=Ma(),Gd=Ku(),Ud=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,kt.NODE_TYPE,{value:kt.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Gd.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[kt.NODE_TYPE]:{value:kt.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=kt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){En(this.contents)&&this.contents.add(t)}addIn(t,i){En(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Jd.anchorNames(this);t.anchor=!i||r.has(i)?Jd.findNewAnchor(i||"a",r):i}return new MR.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,N=i.filter(m).map(String);N.length>0&&(i=i.concat(N)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Jd.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=WR.createNode(t,u,v);return s&&kt.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new FR.Pair(n,a)}delete(t){return En(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Sn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):En(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return kt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Sn.isEmptyPath(t)?!i&&kt.isScalar(this.contents)?this.contents.value:this.contents:kt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return kt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Sn.isEmptyPath(t)?this.contents!==void 0:kt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Sn.collectionFromPath(this.schema,[t],i):En(this.contents)&&this.contents.set(t,i)}setIn(t,i){Sn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Sn.collectionFromPath(this.schema,Array.from(t),i):En(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Gd.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Gd.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new BR.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=LR.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"?VR.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 qR.stringifyDocument(this,t)}};function En(e){if(kt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ng.Document=Ud});var io=x(to=>{"use strict";var eo=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Kd=class extends eo{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Yd=class extends eo{constructor(t,i,r){super("YAMLWarning",t,i,r)}},zR=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};Ya.YAMLError=Ka;Ya.YAMLParseError=Dd;Ya.YAMLWarning=Fd;Ya.prettifyError=gR});var Qa=x(Fv=>{"use strict";function wR(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,v=!1,p=null,m=null,b=null,y=null,P=null,S=null,k=null;for(let w of e)switch(v&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&a(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),p&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(p=w),u=!0;break;case"comment":{u||a(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let g=w.source.substring(1)||" ";d?d+=f+g:d=g,f="",l=!1;break}case"newline":l?d?d+=w.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,h=!0,(m||b)&&(y=w),u=!0;break;case"anchor":m&&a(w,"MULTIPLE_ANCHORS","A node can have at most one anchor"),w.source.endsWith(":")&&a(w.offset+w.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=w,k??(k=w.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),b=w,k??(k=w.offset),l=!1,u=!1,v=!0;break}case i:(m||b)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),S&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),S=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){P&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),P=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let N=e[e.length-1],R=N?N.offset+N.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:P,found:S,spaceBefore:c,comment:d,hasNewline:h,anchor:m,tag:b,newlineAfterProp:y,end:R,start:k??R}}Fv.resolveProps=wR});var fc=x(Mv=>{"use strict";function Md(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(Md(t.key)||Md(t.value))return!0}return!1;default:return!0}}Mv.containsNewline=Md});var Ld=x(Lv=>{"use strict";var yR=fc();function NR(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&yR.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Lv.flowIndentCheck=NR});var Bd=x(qv=>{"use strict";var Bv=J();function bR(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Bv.isScalar(a)&&Bv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}qv.mapIncludes=bR});var Uv=x(Gv=>{"use strict";var Vv=Bi(),kR=Vi(),Wv=Qa(),SR=fc(),zv=Ld(),ER=Bd(),Jv="All mapping items must start at the same column";function PR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??kR.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:h,value:v}=u,p=Wv.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Jv)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
67
- `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||SR.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==r.indent&&n(c,"BAD_INDENT",Jv);i.atKey=!0;let b=p.end,y=f?e(i,f,p,n):t(i,b,d,null,p,n);i.schema.compat&&zv.flowIndentCheck(r.indent,f,n),i.atKey=!1,ER.mapIncludes(i,s.items,y)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let P=Wv.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=P.end,P.found){m&&(v?.type==="block-map"&&!P.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&p.start<P.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?e(i,v,P,n):t(i,c,h,null,P,n);i.schema.compat&&zv.flowIndentCheck(r.indent,v,n),c=S.range[2];let k=new Vv.Pair(y,S);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),P.comment&&(y.comment?y.comment+=`
68
- `+P.comment:y.comment=P.comment);let S=new Vv.Pair(y);i.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Gv.resolveBlockMap=PR});var Yv=x(Kv=>{"use strict";var RR=Wi(),xR=Qa(),CR=Ld();function AR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??RR.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=xR.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&CR.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Kv.resolveBlockSeq=AR});var bn=x(Xv=>{"use strict";function _R(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Xv.resolveEnd=_R});var tg=x(eg=>{"use strict";var TR=J(),IR=Bi(),Qv=Vi(),jR=Wi(),$R=bn(),Zv=Qa(),OR=fc(),HR=Bd(),qd="Block collections are not allowed within flow collections",Vd=e=>e&&(e.type==="block-map"||e.type==="block-seq");function DR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Qv.YAMLMap:jR.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let b=r.items[m],{start:y,key:P,sep:S,value:k}=b,N=Zv.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:P??S?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!S&&!k){m===0&&N.comma?n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),N.comment&&(l.comment?l.comment+=`
69
- `+N.comment:l.comment=N.comment),d=N.end;continue}!o&&i.options.strict&&OR.containsNewline(P)&&n(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)N.comma&&n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(N.comma||n(N.start,"MISSING_CHAR",`Missing , between ${s} items`),N.comment){let R="";e:for(let w of y)switch(w.type){case"comma":case"space":break;case"comment":R=w.source.substring(1);break e;default:break e}if(R){let w=l.items[l.items.length-1];TR.isPair(w)&&(w=w.value??w.key),w.comment?w.comment+=`
70
- `+R:w.comment=R,N.comment=N.comment.substring(R.length+1)}}if(!o&&!S&&!N.found){let R=k?e(i,k,N,n):t(i,N.end,S,null,N,n);l.items.push(R),d=R.range[2],Vd(k)&&n(R.range,"BLOCK_IN_FLOW",qd)}else{i.atKey=!0;let R=N.end,w=P?e(i,P,N,n):t(i,R,y,null,N,n);Vd(P)&&n(w.range,"BLOCK_IN_FLOW",qd),i.atKey=!1;let g=Zv.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:k,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(g.found){if(!o&&!N.found&&i.options.strict){if(S)for(let O of S){if(O===g.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<g.found.offset-1024&&n(g.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(g.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let E=k?e(i,k,g,n):g.found?t(i,g.end,S,null,g,n):null;E?Vd(k)&&n(E.range,"BLOCK_IN_FLOW",qd):g.comment&&(w.comment?w.comment+=`
71
- `+g.comment:w.comment=g.comment);let q=new IR.Pair(w,E);if(i.options.keepSourceTokens&&(q.srcToken=b),o){let O=l;HR.mapIncludes(i,O.items,w)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(q)}else{let O=new Qv.YAMLMap(i.schema);O.flow=!0,O.items.push(q);let He=(E??w).range;O.range=[w.range[0],He[1],He[2]],l.items.push(O)}d=E?E.range[2]:g.end}}let f=o?"}":"]",[h,...v]=r.end,p=d;if(h?.source===f)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),b=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",b),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=$R.resolveEnd(v,p,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
- `+m.comment:l.comment=m.comment),l.range=[r.offset,p,m.offset]}else l.range=[r.offset,p,p];return l}eg.resolveFlowCollection=DR});var rg=x(ig=>{"use strict";var FR=J(),MR=ye(),LR=Vi(),BR=Wi(),qR=Uv(),VR=Yv(),WR=tg();function Wd(e,t,i,r,n,a){let o=i.type==="block-map"?qR.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?VR.resolveBlockSeq(e,t,i,r,a):WR.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function zR(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===LR.YAMLMap.tagName&&s==="map"||o===BR.YAMLSeq.tagName&&s==="seq")return Wd(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Wd(e,t,i,n,o)}let l=Wd(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=FR.isNode(u)?u:new MR.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ig.composeCollection=zR});var Jd=x(ng=>{"use strict";var zd=ye();function JR(e,t,i){let r=t.offset,n=GR(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?zd.Scalar.BLOCK_FOLDED:zd.Scalar.BLOCK_LITERAL,o=t.source?UR(t.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:p,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let p=0;p<s;++p){let[m,b]=o[p];if(b===""||b==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=p,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+b.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let d="",f="",h=!1;for(let p=0;p<u;++p)d+=o[p][0].slice(c)+`
74
- `;for(let p=u;p<s;++p){let[m,b]=o[p];l+=m.length+b.length+1;let y=b[b.length-1]==="\r";if(y&&(b=b.slice(0,-1)),b&&m.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(y?2:1),"BAD_INDENT",S),m=""}a===zd.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+b,f=`
75
- `):m.length>c||b[0]===" "?(f===" "?f=`
76
- `:!h&&f===`
65
+ `}};to.YAMLError=eo;to.YAMLParseError=Kd;to.YAMLWarning=Yd;to.prettifyError=zR});var ro=x(ag=>{"use strict";function JR(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,N=null,y=null,E=null,S=null,k=null;for(let w of e)switch(v&&(w.type!=="space"&&w.type!=="newline"&&w.type!=="comma"&&a(w.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&w.type!=="comment"&&w.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),w.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&w.source.includes(" ")&&(h=w),u=!0;break;case"comment":{u||a(w,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let g=w.source.substring(1)||" ";d?d+=f+g:d=g,f="",l=!1;break}case"newline":l?d?d+=w.source:(!S||i!=="seq-item-ind")&&(c=!0):f+=w.source,l=!0,p=!0,(m||N)&&(y=w),u=!0;break;case"anchor":m&&a(w,"MULTIPLE_ANCHORS","A node can have at most one anchor"),w.source.endsWith(":")&&a(w.offset+w.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=w,k??(k=w.offset),l=!1,u=!1,v=!0;break;case"tag":{N&&a(w,"MULTIPLE_TAGS","A node can have at most one tag"),N=w,k??(k=w.offset),l=!1,u=!1,v=!0;break}case i:(m||N)&&a(w,"BAD_PROP_ORDER",`Anchors and tags must be after the ${w.source} indicator`),S&&a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.source} in ${t??"collection"}`),S=w,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){E&&a(w,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),E=w,l=!1,u=!1;break}default:a(w,"UNEXPECTED_TOKEN",`Unexpected ${w.type} token`),l=!1,u=!1}let b=e[e.length-1],R=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:E,found:S,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:N,newlineAfterProp:y,end:R,start:k??R}}ag.resolveProps=JR});var wc=x(og=>{"use strict";function Xd(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(Xd(t.key)||Xd(t.value))return!0}return!1;default:return!0}}og.containsNewline=Xd});var Qd=x(sg=>{"use strict";var GR=wc();function UR(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&GR.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}sg.flowIndentCheck=UR});var Zd=x(lg=>{"use strict";var cg=J();function KR(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||cg.isScalar(a)&&cg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}lg.mapIncludes=KR});var mg=x(pg=>{"use strict";var ug=Vi(),YR=zi(),dg=ro(),XR=wc(),fg=Qd(),QR=Zd(),hg="All mapping items must start at the same column";function ZR({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??YR.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:v}=u,h=dg.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",hg)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||XR.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",hg);i.atKey=!0;let N=h.end,y=f?e(i,f,h,n):t(i,N,d,null,h,n);i.schema.compat&&fg.flowIndentCheck(r.indent,f,n),i.atKey=!1,QR.mapIncludes(i,s.items,y)&&n(N,"DUPLICATE_KEY","Map keys must be unique");let E=dg.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=E.end,E.found){m&&(v?.type==="block-map"&&!E.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<E.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?e(i,v,E,n):t(i,c,p,null,E,n);i.schema.compat&&fg.flowIndentCheck(r.indent,v,n),c=S.range[2];let k=new ug.Pair(y,S);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),E.comment&&(y.comment?y.comment+=`
68
+ `+E.comment:y.comment=E.comment);let S=new ug.Pair(y);i.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}pg.resolveBlockMap=ZR});var gg=x(vg=>{"use strict";var ex=Ji(),tx=ro(),ix=Qd();function rx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??ex.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=tx.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&ix.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}vg.resolveBlockSeq=rx});var Pn=x(wg=>{"use strict";function nx(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}wg.resolveEnd=nx});var kg=x(bg=>{"use strict";var ax=J(),ox=Vi(),yg=zi(),sx=Ji(),cx=Pn(),Ng=ro(),lx=wc(),ux=Zd(),ef="Block collections are not allowed within flow collections",tf=e=>e&&(e.type==="block-map"||e.type==="block-seq");function dx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?yg.YAMLMap:sx.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let N=r.items[m],{start:y,key:E,sep:S,value:k}=N,b=Ng.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:E??S?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!S&&!k){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
69
+ `+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&lx.containsNewline(E)&&n(E,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let R="";e:for(let w of y)switch(w.type){case"comma":case"space":break;case"comment":R=w.source.substring(1);break e;default:break e}if(R){let w=l.items[l.items.length-1];ax.isPair(w)&&(w=w.value??w.key),w.comment?w.comment+=`
70
+ `+R:w.comment=R,b.comment=b.comment.substring(R.length+1)}}if(!o&&!S&&!b.found){let R=k?e(i,k,b,n):t(i,b.end,S,null,b,n);l.items.push(R),d=R.range[2],tf(k)&&n(R.range,"BLOCK_IN_FLOW",ef)}else{i.atKey=!0;let R=b.end,w=E?e(i,E,b,n):t(i,R,y,null,b,n);tf(E)&&n(w.range,"BLOCK_IN_FLOW",ef),i.atKey=!1;let g=Ng.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:k,offset:w.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(g.found){if(!o&&!b.found&&i.options.strict){if(S)for(let O of S){if(O===g.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<g.found.offset-1024&&n(g.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(g.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,g,n):g.found?t(i,g.end,S,null,g,n):null;P?tf(k)&&n(P.range,"BLOCK_IN_FLOW",ef):g.comment&&(w.comment?w.comment+=`
71
+ `+g.comment:w.comment=g.comment);let D=new ox.Pair(w,P);if(i.options.keepSourceTokens&&(D.srcToken=N),o){let O=l;ux.mapIncludes(i,O.items,w)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(D)}else{let O=new yg.YAMLMap(i.schema);O.flow=!0,O.items.push(D);let De=(P??w).range;O.range=[w.range[0],De[1],De[2]],l.items.push(O)}d=P?P.range[2]:g.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),N=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",N),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=cx.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
+ `+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}bg.resolveFlowCollection=dx});var Eg=x(Sg=>{"use strict";var fx=J(),hx=ye(),px=zi(),mx=Ji(),vx=mg(),gx=gg(),wx=kg();function rf(e,t,i,r,n,a){let o=i.type==="block-map"?vx.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?gx.resolveBlockSeq(e,t,i,r,a):wx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function yx(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===px.YAMLMap.tagName&&s==="map"||o===mx.YAMLSeq.tagName&&s==="seq")return rf(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),rf(e,t,i,n,o)}let l=rf(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=fx.isNode(u)?u:new hx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Sg.composeCollection=yx});var af=x(Pg=>{"use strict";var nf=ye();function Nx(e,t,i){let r=t.offset,n=bx(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?nf.Scalar.BLOCK_FOLDED:nf.Scalar.BLOCK_LITERAL,o=t.source?kx(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,N]=o[h];if(N===""||N==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+N.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
74
+ `;for(let h=u;h<s;++h){let[m,N]=o[h];l+=m.length+N.length+1;let y=N[N.length-1]==="\r";if(y&&(N=N.slice(0,-1)),N&&m.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-N.length-(y?2:1),"BAD_INDENT",S),m=""}a===nf.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+N,f=`
75
+ `):m.length>c||N[0]===" "?(f===" "?f=`
76
+ `:!p&&f===`
77
77
  `&&(f=`
78
78
 
79
- `),d+=f+m.slice(c)+b,f=`
80
- `,h=!0):b===""?f===`
79
+ `),d+=f+m.slice(c)+N,f=`
80
+ `,p=!0):N===""?f===`
81
81
  `?d+=`
82
82
  `:f=`
83
- `:(d+=f+b,f=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let p=s;p<o.length;++p)d+=`
84
- `+o[p][0].slice(c);d[d.length-1]!==`
83
+ `:(d+=f+N,f=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
84
+ `+o[h][0].slice(c);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function GR({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function UR(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}ng.resolveBlockScalar=JR});var Ud=x(og=>{"use strict";var Gd=ye(),KR=bn();function YR(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=Gd.Scalar.PLAIN,c=XR(a,l);break;case"single-quoted-scalar":s=Gd.Scalar.QUOTE_SINGLE,c=QR(a,l);break;case"double-quoted-scalar":s=Gd.Scalar.QUOTE_DOUBLE,c=ZR(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=KR.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function XR(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}`),ag(e)}function QR(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),ag(e.slice(1,-1)).replace(/''/g,"'")}function ag(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function bx({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function kx(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Pg.resolveBlockScalar=Nx});var sf=x(xg=>{"use strict";var of=ye(),Sx=Pn();function Ex(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=of.Scalar.PLAIN,c=Px(a,l);break;case"single-quoted-scalar":s=of.Scalar.QUOTE_SINGLE,c=Rx(a,l);break;case"double-quoted-scalar":s=of.Scalar.QUOTE_DOUBLE,c=xx(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Sx.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Px(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}`),Rg(e)}function Rx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Rg(e.slice(1,-1)).replace(/''/g,"'")}function Rg(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 r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function ZR(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
91
+ `:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function xx(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=ex(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=tx[a];if(o)i+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=Cx(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Ax[a];if(o)i+=o;else if(a===`
94
94
  `)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
95
- `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=ix(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
95
+ `)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=_x(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
96
96
  `&&!(o==="\r"&&e[r+2]===`
97
- `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function ex(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
97
+ `)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Cx(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
98
98
  `||r==="\r")&&!(r==="\r"&&e[t+2]!==`
99
99
  `);)r===`
100
100
  `&&(i+=`
101
- `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var tx={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ix(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}og.resolveFlowScalar=YR});var lg=x(cg=>{"use strict";var Fr=J(),sg=ye(),rx=Jd(),nx=Ud();function ax(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?rx.resolveBlockScalar(e,t,r):nx.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Fr.SCALAR]:c?l=ox(e.schema,n,c,i,r):t.type==="scalar"?l=sx(e,n,t,r):l=e.schema[Fr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Fr.isScalar(d)?d:new sg.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new sg.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function ox(e,t,i,r,n){if(i==="!")return e[Fr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Fr.SCALAR])}function sx({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[Fr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Fr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}cg.composeScalar=ax});var dg=x(ug=>{"use strict";function cx(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}ug.emptyScalarPosition=cx});var pg=x(Yd=>{"use strict";var lx=Ia(),ux=J(),dx=rg(),fg=lg(),fx=bn(),hx=dg(),px={composeNode:hg,composeEmptyNode:Kd};function hg(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=mx(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=fg.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=dx.composeCollection(px,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Kd(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!ux.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Kd(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:hx.emptyScalarPosition(t,i,r),indent:-1,source:""},d=fg.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function mx({options:e},{offset:t,source:i,end:r},n){let a=new lx.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=fx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Yd.composeEmptyNode=Kd;Yd.composeNode=hg});var gg=x(vg=>{"use strict";var vx=Ua(),mg=pg(),gx=bn(),wx=Qa();function yx(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new vx.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=wx.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?mg.composeNode(l,n,u,o):mg.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=gx.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}vg.composeDoc=yx});var Qd=x(Ng=>{"use strict";var Nx=ks("process"),bx=Du(),kx=Ua(),Za=Xa(),wg=J(),Sx=gg(),Ex=bn();function eo(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 yg(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
101
+ `),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Ax={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function _x(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}xg.resolveFlowScalar=Ex});var _g=x(Ag=>{"use strict";var Lr=J(),Cg=ye(),Tx=af(),Ix=sf();function jx(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Tx.resolveBlockScalar(e,t,r):Ix.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Lr.SCALAR]:c?l=$x(e.schema,n,c,i,r):t.type==="scalar"?l=Ox(e,n,t,r):l=e.schema[Lr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Lr.isScalar(d)?d:new Cg.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Cg.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function $x(e,t,i,r,n){if(i==="!")return e[Lr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Lr.SCALAR])}function Ox({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[Lr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Lr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Ag.composeScalar=jx});var Ig=x(Tg=>{"use strict";function Hx(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}Tg.emptyScalarPosition=Hx});var Og=x(lf=>{"use strict";var Dx=Da(),Mx=J(),Fx=Eg(),jg=_g(),Lx=Pn(),Bx=Ig(),qx={composeNode:$g,composeEmptyNode:cf};function $g(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=Vx(e,t,r),(s||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=jg.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Fx.composeCollection(qx,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=cf(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Mx.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function cf(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Bx.emptyScalarPosition(t,i,r),indent:-1,source:""},d=jg.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Vx({options:e},{offset:t,source:i,end:r},n){let a=new Dx.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Lx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}lf.composeEmptyNode=cf;lf.composeNode=$g});var Mg=x(Dg=>{"use strict";var Wx=Za(),Hg=Og(),zx=Pn(),Jx=ro();function Gx(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Wx.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Jx.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?Hg.composeNode(l,n,u,o):Hg.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=zx.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Dg.composeDoc=Gx});var df=x(Bg=>{"use strict";var Ux=Cs("process"),Kx=Ku(),Yx=Za(),no=io(),Fg=J(),Xx=Mg(),Qx=Pn();function ao(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 Lg(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Xd=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=eo(i);a?this.warnings.push(new Za.YAMLWarning(o,r,n)):this.errors.push(new Za.YAMLParseError(o,r,n))},this.directives=new bx.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=yg(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
- ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(wg.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];wg.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
105
+ `)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var uf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=ao(i);a?this.warnings.push(new no.YAMLWarning(o,r,n)):this.errors.push(new no.YAMLParseError(o,r,n))},this.directives=new Kx.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Lg(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
106
+ ${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(Fg.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Fg.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
107
107
  ${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
108
- ${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:yg(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(Nx.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=eo(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=Sx.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new Za.YAMLParseError(eo(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Za.YAMLParseError(eo(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Ex.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
- ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new Za.YAMLParseError(eo(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new kx.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Ng.Composer=Xd});var Sg=x(hc=>{"use strict";var Px=Jd(),Rx=Ud(),xx=Xa(),bg=Da();function Cx(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new xx.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Rx.resolveFlowScalar(e,t,r);case"block-scalar":return Px.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function Ax(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=bg.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
108
+ ${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Lg(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(Ux.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=ao(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=Xx.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new no.YAMLParseError(ao(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new no.YAMLParseError(ao(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=Qx.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
109
+ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new no.YAMLParseError(ao(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new Yx.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};Bg.Composer=uf});var Wg=x(yc=>{"use strict";var Zx=af(),eC=sf(),tC=io(),qg=qa();function iC(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new tC.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return eC.resolveFlowScalar(e,t,r);case"block-scalar":return Zx.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function rC(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=qg.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),u=s.substring(0,l),d=s.substring(l+1)+`
112
- `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return kg(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
113
- `}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function _x(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=bg.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Tx(e,c);break;case'"':Zd(e,c,"double-quoted-scalar");break;case"'":Zd(e,c,"single-quoted-scalar");break;default:Zd(e,c,"scalar")}}function Tx(e,t){let i=t.indexOf(`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return Vg(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function nC(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=qg.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":aC(e,c);break;case'"':ff(e,c,"double-quoted-scalar");break;case"'":ff(e,c,"single-quoted-scalar");break;default:ff(e,c,"scalar")}}function aC(e,t){let i=t.indexOf(`
114
114
  `),r=t.substring(0,i),n=t.substring(i+1)+`
115
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];kg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function kg(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 Zd(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}hc.createScalarToken=Ax;hc.resolveAsScalar=Cx;hc.setScalarValue=_x});var Pg=x(Eg=>{"use strict";var Ix=e=>"type"in e?mc(e):pc(e);function mc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=mc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=pc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=pc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=pc(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 pc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=mc(t)),i)for(let a of i)n+=a.source;return r&&(n+=mc(r)),n}Eg.stringify=Ix});var Ag=x(Cg=>{"use strict";var ef=Symbol("break visit"),jx=Symbol("skip children"),Rg=Symbol("remove item");function Mr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),xg(Object.freeze([]),e,t)}Mr.BREAK=ef;Mr.SKIP=jx;Mr.REMOVE=Rg;Mr.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Mr.parentCollection=(e,t)=>{let i=Mr.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function xg(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=xg(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===ef)return ef;s===Rg&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Cg.visit=Mr});var vc=x(et=>{"use strict";var tf=Sg(),$x=Pg(),Ox=Ag(),rf="\uFEFF",nf="",af="",of="",Hx=e=>!!e&&"items"in e,Dx=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Fx(e){switch(e){case rf:return"<BOM>";case nf:return"<DOC>";case af:return"<FLOW_END>";case of:return"<SCALAR>";default:return JSON.stringify(e)}}function Mx(e){switch(e){case rf:return"byte-order-mark";case nf:return"doc-mode";case af:return"flow-error-end";case of: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=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Vg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Vg(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 ff(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}yc.createScalarToken=rC;yc.resolveAsScalar=iC;yc.setScalarValue=nC});var Jg=x(zg=>{"use strict";var oC=e=>"type"in e?bc(e):Nc(e);function bc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=bc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Nc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Nc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Nc(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 Nc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=bc(t)),i)for(let a of i)n+=a.source;return r&&(n+=bc(r)),n}zg.stringify=oC});var Yg=x(Kg=>{"use strict";var hf=Symbol("break visit"),sC=Symbol("skip children"),Gg=Symbol("remove item");function Br(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Ug(Object.freeze([]),e,t)}Br.BREAK=hf;Br.SKIP=sC;Br.REMOVE=Gg;Br.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Br.parentCollection=(e,t)=>{let i=Br.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Ug(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Ug(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===hf)return hf;s===Gg&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Kg.visit=Br});var kc=x(tt=>{"use strict";var pf=Wg(),cC=Jg(),lC=Yg(),mf="\uFEFF",vf="",gf="",wf="",uC=e=>!!e&&"items"in e,dC=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function fC(e){switch(e){case mf:return"<BOM>";case vf:return"<DOC>";case gf:return"<FLOW_END>";case wf:return"<SCALAR>";default:return JSON.stringify(e)}}function hC(e){switch(e){case mf:return"byte-order-mark";case vf:return"doc-mode";case gf:return"flow-error-end";case wf: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}et.createScalarToken=tf.createScalarToken;et.resolveAsScalar=tf.resolveAsScalar;et.setScalarValue=tf.setScalarValue;et.stringify=$x.stringify;et.visit=Ox.visit;et.BOM=rf;et.DOCUMENT=nf;et.FLOW_END=af;et.SCALAR=of;et.isCollection=Hx;et.isScalar=Dx;et.prettyToken=Fx;et.tokenType=Mx});var lf=x(Tg=>{"use strict";var to=vc();function Dt(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var _g=new Set("0123456789ABCDEFabcdef"),Lx=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),gc=new Set(",[]{}"),Bx=new Set(` ,[]{}
121
- \r `),sf=e=>!e||Bx.has(e),cf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
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}tt.createScalarToken=pf.createScalarToken;tt.resolveAsScalar=pf.resolveAsScalar;tt.setScalarValue=pf.setScalarValue;tt.stringify=cC.stringify;tt.visit=lC.visit;tt.BOM=mf;tt.DOCUMENT=vf;tt.FLOW_END=gf;tt.SCALAR=wf;tt.isCollection=uC;tt.isScalar=dC;tt.prettyToken=fC;tt.tokenType=hC});var bf=x(Qg=>{"use strict";var oo=kc();function Ft(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Xg=new Set("0123456789ABCDEFabcdef"),pC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Sc=new Set(",[]{}"),mC=new Set(` ,[]{}
121
+ \r `),yf=e=>!e||mC.has(e),Nf=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,i=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
122
122
  `?!0:i==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+r+1}return i===`
125
- `||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Dt(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]===to.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield to.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==="...")&&Dt(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&&!Dt(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===":")&&Dt(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(sf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&Dt(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield to.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(sf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Dt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
125
+ `||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Ft(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===oo.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield oo.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let i=this.peek(3);if((i==="---"||i==="...")&&Ft(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ft(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ft(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(yf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&Ft(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield oo.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(yf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ft(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
128
- `,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Dt(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
128
+ `,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>Ft(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
129
129
  `:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
130
  `)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
131
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
132
132
  `;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield to.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Dt(a)||t&&gc.has(a))break;i=r}else if(Dt(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield oo.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(Ft(a)||t&&Sc.has(a))break;i=r}else if(Ft(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
134
134
  `?(r+=1,n=`
135
- `,a=this.buffer[r+1]):i=r),a==="#"||t&&gc.has(a))break;if(n===`
136
- `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&gc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield to.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(sf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Dt(r)||i&&gc.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Dt(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(Lx.has(i))i=this.buffer[++t];else if(i==="%"&&_g.has(this.buffer[t+1])&&_g.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[r+1]):i=r),a==="#"||t&&Sc.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&Sc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield oo.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(yf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ft(r)||i&&Sc.has(r)){i?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,i=this.buffer[t];for(;!Ft(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(pC.has(i))i=this.buffer[++t];else if(i==="%"&&Xg.has(this.buffer[t+1])&&Xg.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,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Tg.Lexer=cf});var df=x(Ig=>{"use strict";var uf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Ig.LineCounter=uf});var hf=x(Dg=>{"use strict";var qx=ks("process"),jg=vc(),Vx=lf();function zi(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function $g(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 Hg(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 wc(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 kn(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 yc(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 Og(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!zi(t.start,"explicit-key-ind")&&!zi(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Hg(t.value)?t.value.end?yc(t.value.end,t.sep):t.value.end=t.sep:yc(t.start,t.sep),delete t.sep)}var ff=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 Vx.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,qx.env.LOG_TOKENS&&console.log("|",jg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=jg.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&Og(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&$g(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{$g(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=wc(this.peek(2)),r=kn(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Qg.Lexer=Nf});var Sf=x(Zg=>{"use strict";var kf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};Zg.LineCounter=kf});var Pf=x(nw=>{"use strict";var vC=Cs("process"),ew=kc(),gC=bf();function Gi(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function tw(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 rw(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 Ec(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 Rn(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 Pc(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 iw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Gi(t.start,"explicit-key-ind")&&!Gi(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,rw(t.value)?t.value.end?Pc(t.value.end,t.sep):t.value.end=t.sep:Pc(t.start,t.sep),delete t.sep)}var Ef=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 gC.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,vC.env.LOG_TOKENS&&console.log("|",ew.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=ew.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&iw(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&tw(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{tw(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=Ec(this.peek(2)),r=Rn(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
139
139
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
140
- `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){yc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(zi(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(Hg(i.key)&&!zi(i.sep,"newline")){let o=kn(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(zi(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=kn(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):zi(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!zi(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){yc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||zi(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=wc(r),a=kn(n);Og(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
140
+ `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Pc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Gi(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(rw(i.key)&&!Gi(i.sep,"newline")){let o=Rn(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(Gi(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Rn(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Gi(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!Gi(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Pc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||Gi(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Ec(r),a=Rn(n);iw(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=wc(t),r=kn(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=wc(t),r=kn(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Dg.Parser=ff});var qg=x(ro=>{"use strict";var Fg=Qd(),Wx=Ua(),io=Xa(),zx=Yu(),Jx=J(),Gx=df(),Mg=hf();function Lg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Gx.LineCounter||null,prettyErrors:t}}function Ux(e,t={}){let{lineCounter:i,prettyErrors:r}=Lg(t),n=new Mg.Parser(i?.addNewLine),a=new Fg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(io.prettifyError(e,i)),s.warnings.forEach(io.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Bg(e,t={}){let{lineCounter:i,prettyErrors:r}=Lg(t),n=new Mg.Parser(i?.addNewLine),a=new Fg.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new io.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(io.prettifyError(e,i)),o.warnings.forEach(io.prettifyError(e,i))),o}function Kx(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Bg(e,i);if(!n)return null;if(n.warnings.forEach(a=>zx.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function Yx(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return Jx.isDocument(e)&&!r?e.toString(i):new Wx.Document(e,r,i).toString(i)}ro.parse=Kx;ro.parseAllDocuments=Ux;ro.parseDocument=Bg;ro.stringify=Yx});var Sn=x(Y=>{"use strict";var Xx=Qd(),Qx=Ua(),Zx=Id(),pf=Xa(),eC=Ia(),Ji=J(),tC=Bi(),iC=ye(),rC=Vi(),nC=Wi(),aC=vc(),oC=lf(),sC=df(),cC=hf(),Nc=qg(),Vg=Ca();Y.Composer=Xx.Composer;Y.Document=Qx.Document;Y.Schema=Zx.Schema;Y.YAMLError=pf.YAMLError;Y.YAMLParseError=pf.YAMLParseError;Y.YAMLWarning=pf.YAMLWarning;Y.Alias=eC.Alias;Y.isAlias=Ji.isAlias;Y.isCollection=Ji.isCollection;Y.isDocument=Ji.isDocument;Y.isMap=Ji.isMap;Y.isNode=Ji.isNode;Y.isPair=Ji.isPair;Y.isScalar=Ji.isScalar;Y.isSeq=Ji.isSeq;Y.Pair=tC.Pair;Y.Scalar=iC.Scalar;Y.YAMLMap=rC.YAMLMap;Y.YAMLSeq=nC.YAMLSeq;Y.CST=aC;Y.Lexer=oC.Lexer;Y.LineCounter=sC.LineCounter;Y.Parser=cC.Parser;Y.parse=Nc.parse;Y.parseAllDocuments=Nc.parseAllDocuments;Y.parseDocument=Nc.parseDocument;Y.stringify=Nc.stringify;Y.visit=Vg.visit;Y.visitAsync=Vg.visitAsync});import{promises as ES}from"node:fs";import _u from"node:path";import{promises as Su}from"fs";import xe from"path";import{promises as wk}from"fs";import wa from"path";import{isDeepStrictEqual as x0}from"util";import{createHash as jS}from"crypto";function Xp(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Qp(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Qp(e[t]);return Object.freeze(e)}function Hi(e){return Qp(structuredClone(e))}function Iu(e,t,i,r){return e.resolveStep({pkg:Hi(t),state:Hi(i),context:Hi(r)})}function Zp(e,t,i,r,n,a){return e.resolveNext({pkg:Hi(t),state:Hi(i),step:Hi(r),outcome:Hi(n),context:Hi(a)})}function $S(e,t,i){return jS("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function ju(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function em(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Iu(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=ju(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:$S(s.runId,s.iteration,o.id),stepId:o.id};return OS(e,s,c,i)}function OS(e,t,i,r){let n=Xp(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function tm(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Iu(r,e,t,n):void 0,o=a?ju(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Zp(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!ju(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as kh}from"fs";import oN from"path";var kl=xa(Sn(),1);import{promises as Yy}from"fs";import ci from"path";import{execFileSync as lC}from"child_process";import no from"path";function En(e,t){return lC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function uC(e,t){let i=no.normalize(e),r=no.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ae(e){try{let t=no.resolve(En(e,["rev-parse","--show-toplevel"])),r=En(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?no.resolve(r.slice(9)):t,a=null;try{a=En(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!uC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function bc(e){try{En(e,["rev-parse","--is-inside-work-tree"])}catch{return[]}return En(e,["worktree","list","--porcelain","-z"]).split("\0").filter(i=>i.startsWith("worktree ")).map(i=>no.resolve(i.slice(9)))}function mf(e,t){try{let i=En(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as pC}from"node:crypto";import{promises as Ft}from"node:fs";import bt from"node:path";import{TextDecoder as mC}from"node:util";import vf from"path";var dC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),fC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function hC(e){return e.toLowerCase().startsWith(".env")}function ti(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>hC(r))?"environment-file":i.some(r=>fC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>dC.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function gf(e,t){let i=ti(t);if(i)return i;let r=vf.resolve(e.projectRoot,...t.split("/")),n=vf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===vf.resolve(e.configFile)?"native-runtime":null}function Gi(e){return e!==0&&e!==0n&&e!=="0"}function Fe(e,t){return Gi(e.dev)&&Gi(t.dev)&&Gi(e.ino)&&Gi(t.ino)}function W(e,t){let i=Gi(e.dev)&&Gi(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Gi(e.ino)&&Gi(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var ao=1024*1024;function wf(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function vC(e){let t=bt.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||bt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ti(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function gC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function wC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function kc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Wg(e){let t=await Ft.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ft.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function yC(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!wf(i,r))throw new Error("Native artifact path is outside its root");let n=[await Wg(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s=await Wg(a);if(!wf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function zg(e){for(let t of e){let i=await Ft.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!wC(t,i)||await Ft.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ee(e){let t=vC(e.ref),i=e.maxBytes===null?null:gC(e.maxBytes??ao),r=bt.resolve(e.root,...t.split("/")),n=await yC(e.root,bt.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ft.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Ft.realpath(r);if(!wf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ft.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ft.lstat(r),Ft.realpath(r)]);if(await zg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!kc(a,c)||!kc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let P=i===null?h.length:i+1-f,S=await s.read(h,0,Math.min(h.length,P),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),Ft.lstat(r),Ft.realpath(r)]);if(await zg(n),!p.isFile()||p.isSymbolicLink()||m!==o||!kc(c,v)||!kc(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),y;try{y=new mC("utf-8",{fatal:!0}).decode(b)}catch(P){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:P})}return{ref:t,size:f,hash:e.includeHash===!1?null:pC("sha256").update(b).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as NC}from"crypto";import{promises as Me}from"fs";import Mt from"path";function Nf(e,t){let i=Mt.relative(e,t);return i===""||!Mt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Mt.sep}`)}function bC(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yf(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Jg(e){let t=await Me.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 Me.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function oo(e){for(let t of e){let i=await Me.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!bC(t,i)||await Me.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function kC(e,t){let i=Mt.resolve(e),r=Mt.resolve(t);if(!Nf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Jg(i)],a=Mt.relative(i,r).split(Mt.sep).filter(Boolean),o=i;for(let s of a){await oo(n),o=Mt.join(o,s);try{await Me.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Jg(o);if(!Nf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await oo(n),n}async function SC(e){let t;try{t=await Me.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function Gg(e,t,i={}){let r=Mt.dirname(e),n=i.containedRoot?await kC(i.containedRoot,r):null;n||await Me.mkdir(r,{recursive:!0});let a=Mt.join(r,`.${Mt.basename(e)}.${NC()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Me.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([Me.lstat(a),Me.realpath(a)]);if(await oo(n),!c.isFile()||c.isSymbolicLink()||!yf(s,c)||!Nf(n[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!yf(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await oo(n);let c=await Me.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!yf(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Me.link(a,e),await Me.unlink(a)):await Me.rename(a,e),await SC(r)}catch(c){if(await o?.close(),!n)await Me.rm(a,{force:!0});else try{await oo(n),await Me.rm(a,{force:!0})}catch{}throw c}}async function ue(e,t,i={}){await Gg(e,t,i)}async function Ug(e,t,i={}){await Gg(e,t,i)}async function te(e,t,i={}){await ue(e,JSON.stringify(t,null,2)+`
143
- `,i)}import zC from"path";var lo=xa(Sn(),1);import Ec from"path";var uo=64*1024,Pc=1024,Rc=64,Yg=5,EC=[".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/**"],PC=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],RC=[...EC,...PC].sort((e,t)=>e.localeCompare(t,"en"));var Lt={include:["**/*"],exclude:[...RC],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Sc={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
- # ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
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=Ec(t),r=Rn(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Ec(t),r=Rn(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};nw.Parser=Ef});var lw=x(co=>{"use strict";var aw=df(),wC=Za(),so=io(),yC=cd(),NC=J(),bC=Sf(),ow=Pf();function sw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new bC.LineCounter||null,prettyErrors:t}}function kC(e,t={}){let{lineCounter:i,prettyErrors:r}=sw(t),n=new ow.Parser(i?.addNewLine),a=new aw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(so.prettifyError(e,i)),s.warnings.forEach(so.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function cw(e,t={}){let{lineCounter:i,prettyErrors:r}=sw(t),n=new ow.Parser(i?.addNewLine),a=new aw.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new so.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(so.prettifyError(e,i)),o.warnings.forEach(so.prettifyError(e,i))),o}function SC(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=cw(e,i);if(!n)return null;if(n.warnings.forEach(a=>yC.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function EC(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return NC.isDocument(e)&&!r?e.toString(i):new wC.Document(e,r,i).toString(i)}co.parse=SC;co.parseAllDocuments=kC;co.parseDocument=cw;co.stringify=EC});var qr=x(Y=>{"use strict";var PC=df(),RC=Za(),xC=Wd(),Rf=io(),CC=Da(),Ui=J(),AC=Vi(),_C=ye(),TC=zi(),IC=Ji(),jC=kc(),$C=bf(),OC=Sf(),HC=Pf(),Rc=lw(),uw=ja();Y.Composer=PC.Composer;Y.Document=RC.Document;Y.Schema=xC.Schema;Y.YAMLError=Rf.YAMLError;Y.YAMLParseError=Rf.YAMLParseError;Y.YAMLWarning=Rf.YAMLWarning;Y.Alias=CC.Alias;Y.isAlias=Ui.isAlias;Y.isCollection=Ui.isCollection;Y.isDocument=Ui.isDocument;Y.isMap=Ui.isMap;Y.isNode=Ui.isNode;Y.isPair=Ui.isPair;Y.isScalar=Ui.isScalar;Y.isSeq=Ui.isSeq;Y.Pair=AC.Pair;Y.Scalar=_C.Scalar;Y.YAMLMap=TC.YAMLMap;Y.YAMLSeq=IC.YAMLSeq;Y.CST=jC;Y.Lexer=$C.Lexer;Y.LineCounter=OC.LineCounter;Y.Parser=HC.Parser;Y.parse=Rc.parse;Y.parseAllDocuments=Rc.parseAllDocuments;Y.parseDocument=Rc.parseDocument;Y.stringify=Rc.stringify;Y.visit=uw.visit;Y.visitAsync=uw.visitAsync});import{promises as QS}from"node:fs";import qu from"node:path";import{promises as Tu}from"fs";import xe from"path";import{promises as Gk}from"fs";import Ea from"path";import{isDeepStrictEqual as RH}from"util";import{createHash as sE}from"crypto";function wm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function ym(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))ym(e[t]);return Object.freeze(e)}function Mi(e){return ym(structuredClone(e))}function Wu(e,t,i,r){return e.resolveStep({pkg:Mi(t),state:Mi(i),context:Mi(r)})}function Nm(e,t,i,r,n,a){return e.resolveNext({pkg:Mi(t),state:Mi(i),step:Mi(r),outcome:Mi(n),context:Mi(a)})}function cE(e,t,i){return sE("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function zu(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function bm(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Wu(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=zu(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:cE(s.runId,s.iteration,o.id),stepId:o.id};return lE(e,s,c,i)}function lE(e,t,i,r){let n=wm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function km(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?Wu(r,e,t,n):void 0,o=a?zu(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Nm(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!zu(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as jh}from"fs";import _N from"path";var Cl=mn(qr(),1);import{promises as NN}from"fs";import li from"path";import{execFileSync as DC}from"child_process";import lo from"path";function xn(e,t){return DC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function MC(e,t){let i=lo.normalize(e),r=lo.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ae(e){try{let t=lo.resolve(xn(e,["rev-parse","--show-toplevel"])),r=xn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?lo.resolve(r.slice(9)):t,a=null;try{a=xn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!MC(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function dw(e){try{xn(e,["rev-parse","--is-inside-work-tree"]);let t=xn(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:lo.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Cn(e){return dw(e).map(t=>t.root)}function xf(e,t){try{let i=xn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as qC}from"node:crypto";import{promises as Lt}from"node:fs";import St from"node:path";import{TextDecoder as VC}from"node:util";import Cf from"path";var FC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),LC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function BC(e){return e.toLowerCase().startsWith(".env")}function ii(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>BC(r))?"environment-file":i.some(r=>LC.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>FC.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Af(e,t){let i=ii(t);if(i)return i;let r=Cf.resolve(e.projectRoot,...t.split("/")),n=Cf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Cf.resolve(e.configFile)?"native-runtime":null}function Ki(e){return e!==0&&e!==0n&&e!=="0"}function ht(e,t){return Ki(e.dev)&&Ki(t.dev)&&Ki(e.ino)&&Ki(t.ino)}function z(e,t){let i=Ki(e.dev)&&Ki(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ki(e.ino)&&Ki(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var uo=1024*1024;function _f(e,t){let i=St.relative(e,t);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}function WC(e){let t=St.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||St.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ii(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function zC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function JC(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ht(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function fw(e){let t=await Lt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Lt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function GC(e,t){let i=St.resolve(e),r=St.resolve(t);if(!_f(i,r))throw new Error("Native artifact path is outside its root");let n=[await fw(i)],a=i;for(let o of St.relative(i,r).split(St.sep).filter(Boolean)){a=St.join(a,o);let s=await fw(a);if(!_f(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function hw(e){for(let t of e){let i=await Lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!JC(t,i)||await Lt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Q(e){let t=WC(e.ref),i=e.maxBytes===null?null:zC(e.maxBytes??uo),r=St.resolve(e.root,...t.split("/")),n=await GC(e.root,St.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Lt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Lt.realpath(r);if(!_f(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Lt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await hw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!xc(a,c)||!xc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let E=i===null?p.length:i+1-f,S=await s.read(p,0,Math.min(p.length,E),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Lt.lstat(r),Lt.realpath(r)]);if(await hw(n),!h.isFile()||h.isSymbolicLink()||m!==o||!xc(c,v)||!xc(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let N=Buffer.concat(d,f),y;try{y=new VC("utf-8",{fatal:!0}).decode(N)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:qC("sha256").update(N).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as UC}from"crypto";import{promises as Fe}from"fs";import Bt from"path";function Tf(e,t){let i=Bt.relative(e,t);return i===""||!Bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Bt.sep}`)}function KC(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function If(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function YC(e,t){return If(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pw(e){let t=await Fe.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 Fe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function fo(e){for(let t of e){let i=await Fe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!KC(t,i)||await Fe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function XC(e,t){let i=Bt.resolve(e),r=Bt.resolve(t);if(!Tf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await pw(i)],a=Bt.relative(i,r).split(Bt.sep).filter(Boolean),o=i;for(let s of a){await fo(n),o=Bt.join(o,s);try{await Fe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await pw(o);if(!Tf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await fo(n),n}async function QC(e){let t;try{t=await Fe.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function mw(e,t,i={}){let r=Bt.dirname(e),n=i.containedRoot?await XC(i.containedRoot,r):null;n||await Fe.mkdir(r,{recursive:!0});let a=Bt.join(r,`.${Bt.basename(e)}.${UC()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await Fe.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Fe.lstat(a),Fe.realpath(a)]);if(await fo(n),!l.isFile()||l.isSymbolicLink()||!If(s,l)||!Tf(n[0].realPath,u))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(),c=await o.stat(),!If(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await fo(n);let l=await Fe.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!YC(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Fe.link(a,e),await Fe.unlink(a)):await Fe.rename(a,e),await QC(r)}catch(l){if(await o?.close(),!n)await Fe.rm(a,{force:!0});else try{await fo(n),await Fe.rm(a,{force:!0})}catch{}throw l}}async function ue(e,t,i={}){await mw(e,t,i)}async function vw(e,t,i={}){await mw(e,t,i)}async function te(e,t,i={}){await ue(e,JSON.stringify(t,null,2)+`
143
+ `,i)}import SA from"path";var ho=mn(qr(),1);import An from"path";var po=64*1024,Ac=1024,_c=64,yw=5,ZC=12e4,gw=6e5,eA=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/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/**"],tA=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],iA=[...eA,...tA].sort((e,t)=>e.localeCompare(t,"en"));var qt={include:["**/*"],exclude:[...iA],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Cc={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
+ # ambient_resume: true | false`,hook:"# Hook write policy shared by Native and Classic. Paths are project-relative.","hook.allow_paths":"# Project-relative directories allowed during guarded phases. Use one path per list item; empty by default.",native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs and changes. Runtime data stays under .comet.","native.language":`# Artifact language used by Native workflow documents.
145
145
  # language: en | zh-CN`,"native.clarification_mode":`# Controls how Native asks clarifying questions: batch asks every currently answerable question per round (default), sequential asks one at a time.
146
146
  # clarification_mode: batch | sequential`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
147
- # archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.snapshot":"# Controls the auditable project scope and bounded work used by Native content snapshots.","native.snapshot.include":"# Selects the project-relative paths included in Native snapshots. Patterns use / and support *, **, and ?.","native.snapshot.exclude":"# Removes paths from the included scope. Exclusions are bound into each new change baseline.","native.snapshot.max_files":"# Bounds the number of files captured by one snapshot. Increase it for large monorepos.","native.snapshot.max_total_bytes":"# Bounds the total file content hashed by one snapshot. Content is streamed and does not depend on Git hashes.","native.snapshot.max_duration_ms":"# Bounds snapshot capture time in milliseconds. Increase it together with the byte budget on slower or larger repositories.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
147
+ # archive_confirmation: automatic | required`,"native.max_verify_failures":"# Maximum failed Verify outcomes allowed for one confirmed acceptance target before Native stops the completion loop.","native.finish":"# Optional repository-owned finish providers. Native keeps commit, push, generic remote verification, and recovery ownership.","native.snapshot":"# Controls the auditable project scope and bounded work used by Native content snapshots.","native.snapshot.include":"# Selects the project-relative paths included in Native snapshots. Patterns use / and support *, **, and ?.","native.snapshot.exclude":"# Removes paths from the included scope. Exclusions are bound into each new change baseline.","native.snapshot.max_files":"# Bounds the number of files captured by one snapshot. Increase it for large monorepos.","native.snapshot.max_total_bytes":"# Bounds the total file content hashed by one snapshot. Content is streamed and does not depend on Git hashes.","native.snapshot.max_duration_ms":"# Bounds snapshot capture time in milliseconds. Increase it together with the byte budget on slower or larger repositories.",classic:"# Classic workflow settings. They do not change Native state or behavior.","classic.artifact_layout":`# Selects the Classic artifact layout. The default is docs; update preserves detected root-level legacy artifacts.
148
148
  # artifact_layout: legacy | docs`,"classic.language":`# Artifact language used by Classic workflow documents.
149
149
  # language: en | zh-CN`,"classic.context_compression":`# Controls beta context compression for new Classic changes.
150
150
  # context_compression: off | beta`,"classic.review_mode":`# Sets the default review depth for new Classic changes.
151
151
  # review_mode: off | standard | thorough`,"classic.auto_transition":`# Automatically enters the next Classic phase after a phase passes.
152
152
  # auto_transition: true | false`},"zh-CN":{schema:"# Comet 使用的配置格式版本,请勿修改此值。",default_workflow:"# `/comet` 默认进入的工作流;该值也必须出现在 workflows 中。",workflows:"# 此项目启用的工作流,可填写 native、classic 或同时启用两者。",ambient_resume:`# 是否启用只读的环境感知恢复探针,同时作用于 Native 和 Classic;设为 false 可关闭自动工作流恢复。
153
- # ambient_resume: true | false`,native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
153
+ # ambient_resume: true | false`,hook:"# Native 和 Classic 共享的 Hook 写入策略;路径必须是项目相对路径。","hook.allow_paths":"# 在受保护阶段允许写入的项目相对目录;每项填写一个目录,默认为空。",native:"# Native 工作流配置,不会改变 Classic 的状态或行为。","native.artifact_root":"# Native 规格和 change 的存放根目录;运行时数据始终位于 .comet。","native.language":`# Native 工作流文档使用的产物语言。
154
154
  # 可选值:en | zh-CN`,"native.clarification_mode":`# Native 提问澄清问题的方式:batch 每轮一次提出当前所有可回答的问题(默认),sequential 每轮只问一个。
155
155
  # 可选值:batch | sequential`,"native.archive_confirmation":`# Native 归档检查成功后自动归档,或等待用户明确确认。
156
- # 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.snapshot":"# Native 内容快照使用的可审计项目范围与有界工作预算。","native.snapshot.include":"# Native 快照纳入的项目相对路径;模式使用 /,支持 *、** 和 ?。","native.snapshot.exclude":"# 从纳入范围中排除路径;新 change 会把排除策略绑定到 baseline。","native.snapshot.max_files":"# 单次快照最多捕获的文件数;大型 monorepo 可按需提高。","native.snapshot.max_total_bytes":"# 单次快照最多哈希的文件内容总字节数;内容采用流式读取,不依赖 Git hash。","native.snapshot.max_duration_ms":"# 单次快照的最长执行时间(毫秒);较慢或更大的仓库应与字节预算一并提高。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
156
+ # 可选值:automatic | required`,"native.max_verify_failures":"# 同一个已确认验收目标最多允许的 Verify 失败次数;达到上限后停止完成循环。","native.finish":"# 可选的仓库自有收尾 provider;提交、推送、通用远端核验和恢复仍由 Native 负责。","native.snapshot":"# Native 内容快照使用的可审计项目范围与有界工作预算。","native.snapshot.include":"# Native 快照纳入的项目相对路径;模式使用 /,支持 *、** 和 ?。","native.snapshot.exclude":"# 从纳入范围中排除路径;新 change 会把排除策略绑定到 baseline。","native.snapshot.max_files":"# 单次快照最多捕获的文件数;大型 monorepo 可按需提高。","native.snapshot.max_total_bytes":"# 单次快照最多哈希的文件内容总字节数;内容采用流式读取,不依赖 Git hash。","native.snapshot.max_duration_ms":"# 单次快照的最长执行时间(毫秒);较慢或更大的仓库应与字节预算一并提高。",classic:"# Classic 工作流配置,不会改变 Native 的状态或行为。","classic.artifact_layout":`# Classic 产物布局;默认使用 docs,update 检测到根目录 legacy 产物时予以保留。
157
157
  # 可选值:legacy | docs`,"classic.language":`# Classic 工作流文档使用的产物语言。
158
158
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
159
159
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
160
160
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
161
- # 可选值:true | false`}};function Xg(e,t){return Sc[t][e]}function xC(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Sc.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Sc.en)return o}if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Sc.en)return o}return null}function fo(e,t){let i=[],r=null,n=null;for(let a of(0,lo.stringify)(e).trimEnd().split(`
162
- `)){let o=xC(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of Xg(o,t).split(`
163
- `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
164
- `)}function CC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Ec.posix.isAbsolute(i)||Ec.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Pn(e){let t=CC(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Qg(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 kf(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||Ec.posix.isAbsolute(r)||Ec.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function co(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Zg(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function xc(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>Pc)throw new Error(`${t} exceeds ${Pc} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Rc)throw new Error(`${t} contains more than ${Rc} wildcard tokens`);return e}function Kg(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>xc(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function bf(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function AC(e){if(e===void 0)return{...Lt,include:[...Lt.include],exclude:[...Lt.exclude]};let t=co(e,"native.snapshot");return{include:Kg(t.include,"native.snapshot.include",Lt.include),exclude:Kg(t.exclude,"native.snapshot.exclude",Lt.exclude),max_files:bf(t.max_files,Lt.max_files,"native.snapshot.max_files"),max_total_bytes:bf(t.max_total_bytes,Lt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:bf(t.max_duration_ms,Lt.max_duration_ms,"native.snapshot.max_duration_ms")}}function _C(e){if(e===void 0)return;let t=co(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=co(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:Pn(r),toArtifactRoot:Pn(n),stage:a,...o?{cleanup:o}:{}}}function TC(e,t={}){let i=co(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Yg;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=_C(i.pending_root_move);return{artifact_root:Pn(r),language:Zg(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:AC(i.snapshot),...s?{pending_root_move:s}:{}}}function IC(e){let t=co(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Qg(t.artifact_layout),language:Zg(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function jC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function $C(e,t,i,r,n){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!n.allowPartialProject&&e.native!==void 0)||n.allowPartialProject&&!a)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=e.workflows??[e.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:r,...t?{native:t}:{},...i?{classic:i}:{}}}function Rn(e,t={}){let i=(0,lo.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=jC(n.ambient_resume),o=n.native===void 0?void 0:TC(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=n.classic===void 0?void 0:IC(n.classic),c=$C(n,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function ew(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function tw(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.pending_root_move?{pending_root_move:ew(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function so(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ho(e,t){let i=tw(t),r=Rn((0,lo.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.native){let a=so(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(delete o.snapshot,r.native.pending_root_move){let s=so(a.pending_root_move),c=ew(r.native.pending_root_move),l=so(s.cleanup),u=so(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...so(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as HC}from"crypto";import{promises as _c}from"fs";import Ui from"path";import{constants as Cc,promises as Lr}from"fs";var Bt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Sf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function iw(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function po(e){return{dev:e.dev,ino:e.ino,birthtime:Sf(e)}}function Ac(e,t){let i=po(e),r=po(t);return Fe(i,r)?W(i,r):W(i,r)&&Sf(e)===Sf(t)&&iw(e)===iw(t)&&e.size===t.size}async function Br(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Lr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Bt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Bt("too-large",`${r} exceeds ${t} bytes`);let o=await Lr.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:po(a)});let s=process.platform==="win32"?Cc.O_RDONLY:Cc.O_RDONLY|Cc.O_NOFOLLOW|Cc.O_NONBLOCK,c;try{c=await Lr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Bt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Lr.lstat(e,{bigint:n}),Lr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ac(a,l)||!Ac(a,u))throw new Bt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:po(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:P}=await c.read(v,0,Math.min(v.length,y),null);if(P===0)break;if(h+=P,h>t)throw new Bt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,P)))}await i.hooks?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([c.stat({bigint:n}),Lr.lstat(e,{bigint:n}),Lr.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||b!==o||!Ac(a,p)||!Ac(a,m))throw new Bt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:po(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:b}}finally{await c.close()}}function OC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ef(e,t){let i=Ui.relative(e,t);return i===""||!Ui.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ui.sep}`)}async function rw(e,t){let i=Ui.resolve(e),r=await _c.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return _c.realpath(i)}async function nw(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Ui.join(n,i[a]);let o;try{o=await _c.lstat(n)}catch(u){if(OC(u))return{exists:!1,kind:"missing"};throw u}let s=Ui.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await _c.realpath(n);if(!Ef(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function xn(e,t,i){let r=kf(t,i.label),n=Ui.resolve(e),a=await rw(n,i.label),o=r.split("/"),s=Ui.resolve(n,...o);if(!Ef(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await nw(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Ki(e,t,i,r){let n=await xn(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await rw(n.projectRoot,r.label);return Br(n.target,i,{...r,verify:async(o,s)=>{if(!Ef(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await nw(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var mo=".comet/config.yaml";function Pf(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function DC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Rf(e,t={}){return(await vo(e,t)).document}async function aw(e){try{return(await Ki(e,mo,uo,{label:mo})).bytes}catch(t){if(DC(t))return null;throw t}}function ow(e){return e?{exists:!0,sha256:HC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Tc(e){return ow(await aw(e))}async function vo(e,t={}){let i=await aw(e);return{document:i?Rn(i.toString("utf8"),t):null,identity:ow(i)}}var JM=16*1024;async function xf(e,t){if(!t)return;let i=await Tc(e);if(!Pf(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as sw,promises as Yi}from"fs";import U from"path";import BC from"os";var Ic=".comet/config.yaml",qC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Cf(e){try{return await Yi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function VC(e){try{let t=await Yi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(e,t){let i=U.relative(e,t);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}async function Cn(e){let t=[],i=e;for(;!await Cf(i);){let n=U.dirname(i);if(n===i)break;t.push(U.basename(i)),i=n}let r=await Yi.realpath(i);return U.resolve(r,...t.reverse())}async function Af(e){try{return(await Yi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _f(e){let t=U.resolve(e);try{(await Yi.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=U.resolve(BC.homedir());for(;;){if(!(t===r&&i!==r)){let o=U.join(t,...Ic.split("/")),s=t===i||await VC(o);if(await Cf(o)&&s)return t}if(await Cf(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return i;t=a}}function jc(e){return Pn(e)}async function WC(e,t){let i=jc(t),r=U.resolve(e,...i.split("/")),n=await Yi.realpath(e),a=await Cn(r);if(!An(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function dt(e,t){let i=jc(t),r=await WC(e,i),n=U.join(r,"comet");if(await Af(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Cn(r),Cn(n)]);if(!An(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await Af(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Yi.realpath(s),Cn(c)]);if(!An(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Ic.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function lw(e){if(!qC.test(e))throw new Error(`Invalid Native change name: ${e}`)}function tt(e,t){lw(t);let i=U.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function qr(e,t){lw(t);let i=U.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=tt(e,t);if(sw(i))return i;let r=qr(e,t);return sw(r)?r:i}async function cw(e){try{let t=await Yi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function wo(e,t){let i=tt(e,t),r=qr(e,t),[n,a]=await Promise.all([cw(i),cw(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function Xi(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=U.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=U.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return An(U.resolve(e),U.resolve(t))}async function T(e,t){let i=U.resolve(e),r=U.resolve(t);if(!An(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Af(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Cn(i),Cn(r)]);if(!An(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var Tf=Lt;var $c=xc;async function Pe(e){let t=(await Rf(e))?.config??null;return t?.native?t:null}async function _n(e){let t=await Pe(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 Qi(e,t,i={}){let r=await vo(e,{allowPartialProject:!0}),n=ho(r.document?.value??{},t),a=zC.join(e,...Ic.split("/"));await ue(a,fo(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await xf(e,r.identity)}})}import{promises as L_}from"fs";import B_ from"path";import{AsyncLocalStorage as JC}from"async_hooks";import{randomUUID as hw}from"crypto";import{promises as kt}from"fs";import pw from"os";import de from"path";var dw=16*1024,If=".coordinator",GC=5e3,fw=new JC,Oc=new Map;function UC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function KC(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 mw(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 jf(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Fe(i,r)?W(i,r):W(i,r)&&e.size===t.size}function Hc(e,t){return jf(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function YC(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Hc(e.identity,t.identity)}async function ii(e){let t,i;try{let r=await Br(e,dw,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Bt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${dw} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:KC(JSON.parse(t.toString("utf8")),e),identity:mw(i)}}async function XC(e){return(await ii(e))?.owner??null}function $f(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==pw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=rA(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function QC(e,t){try{await kt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await kt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Dc(e,t){let i=await ii(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Hc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await kt.mkdir(t,{recursive:!0});let r=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${hw()}.removed`);try{await kt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ii(r);if(!n||n.owner.id!==e.owner.id||!jf(n.identity,e.identity))throw await QC(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await kt.rm(r,{force:!0}),"removed"}function vw(e){return{id:hw(),pid:process.pid,hostname:pw.hostname(),createdAt:new Date().toISOString(),operation:e}}async function gw(e,t){let i;try{i=await kt.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await XC(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
165
- `,"utf8"),await i.sync(),mw(await i.stat({bigint:!0}))}finally{await i.close()}}async function ZC(e,t){let i=await T(e.runtimeDir,e.locksDir);await kt.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,de.join(i,If));await kt.mkdir(r,{recursive:!0});let n=vw(t),a=de.join(r,`.${n.id}.tmp`),o=de.join(r,`${n.id}.claim`);try{let s=await gw(a,n);await kt.rename(a,o);let c=await ii(o);if(!c||!jf(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await kt.rm(a,{force:!0})}}async function eA(e){let t=de.dirname(e.file),i=!1,r=de.basename(e.file);for(let n of await kt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=de.join(t,n.name);if(de.resolve(a)!==de.resolve(e.file))try{let o=await ii(a),s=$f(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Dc(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function ww(e){let t=await ii(e.file);if(t){if(t.owner.id!==e.owner.id||!Hc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Dc(t,de.dirname(e.file))}}async function tA(e,t){let i=Date.now()+GC;for(;;){let r=await ZC(e,t);if(!await eA(r))return r;if(await ww(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function iA(e){let t=Oc.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Oc.set(e,n),await t,()=>{i(),Oc.get(e)===n&&Oc.delete(e)}}async function Fc(e,t,i){let r=de.resolve(e.locksDir),n=fw.getStore();if(n?.has(r))return i();let a=await iA(r);try{let o=await tA(e,t),s=new Map(n??[]);return s.set(r,o),await fw.run(s,async()=>{try{return await i()}finally{await ww(o)}})}finally{a()}}async function yo(e,t,i){let r=[...new Map(e.map(a=>[de.resolve(a.locksDir),a])).values()].sort((a,o)=>de.resolve(a.locksDir).localeCompare(de.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?Fc(o,t,()=>n(a+1)):i()};return n(0)}async function Zi(e,t,i){return Fc(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await kt.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,de.join(r,UC(t))),a=vw(i),o=await gw(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function er(e){await ii(e.file)&&await Fc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${de.basename(e.file)}`,async()=>{let t=await ii(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Hc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=de.join(e.locksDir,If);await Dc(t,i)})}function rA(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function No(e){return $f(await ii(e))}async function Of(e,t,i){return Fc(e,`take over ${de.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(de.resolve(de.dirname(n))!==de.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ii(n),o=$f(a);if(o.status==="missing")return{status:"missing"};if(i&&!YC(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=de.join(r,If);return await Dc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as s_}from"node:fs";import Jf from"node:path";import JA from"node:path";import Cw from"node:path";import yw from"node:path";import{createHash as nA}from"crypto";function qt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function aA(e,t){t.has(e)&&qt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||qt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&qt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&qt("symbol properties are not supported"),`[${e.map(r=>Hf(r,t)).join(",")}]`}finally{t.delete(e)}}function oA(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&qt("only plain objects are supported"),t.has(e)&&qt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&qt("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&qt("accessor properties are not supported"),`${JSON.stringify(o)}:${Hf(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Hf(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)||qt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?aA(e,t):oA(e,t);case"bigint":case"function":case"symbol":case"undefined":return qt(`${typeof e} values are not supported`)}return qt("unsupported value type")}function bo(e){return Hf(e,new Set)}function L(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 nA("sha256").update(`${e}
166
- ${bo(t)}`).digest("hex")}var sA="comet.native.acceptance.v1",cA=/^acceptance-[a-f0-9]{64}$/u,lA=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),uA=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,dA=/^[a-f0-9]{64}$/u,fA=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function hA(e,t){return e<t?-1:e>t?1:0}var bi=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),So=Object.freeze({maxCriteria:1024}),Nw="<!-- comet-native:acceptance-evidence:start -->",bw="<!-- comet-native:acceptance-evidence:end -->";function kw(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Sw(e,t){let i=t.toString(36),r=L("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function pA(e){if(!dA.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=fA.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]!==L("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function mA(e,t){let i=kw(e.text,bi.maxTextBytes),r=e.context.slice(0,bi.maxContextItems).map(n=>kw(n,bi.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Pw(e){let t=pA({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(hA),n=r.slice(0,bi.maxFailedCheckIds),a=e.criteria.slice(t,t+bi.maxItems);for(let c of a){let l=[...i,mA(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Sw(e.acceptanceHash,u):null,limits:{...bi}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>bi.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Sw(e.acceptanceHash,o):null,limits:{...bi}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>bi.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Ff(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 Df(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Ew(e){return e.includes("-->")||e.includes("--!>")}function*Tn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
161
+ # 可选值:true | false`}};function Nw(e,t){return Cc[t][e]}function rA(e,t,i){let r=/^(\s*)([a-z_]+):/u.exec(e);if(!r)return null;let n=r[1].length,a=r[2];if(n===0&&a in Cc.en)return a;if(n===2&&t){let o=`${t}.${a}`;if(o in Cc.en)return o}if(n===2&&t===null&&a==="hook")return"hook";if(n===2&&t==="hook"&&a==="allow_paths")return"hook.allow_paths";if(n===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in Cc.en)return o}return null}function mo(e,t){let i=[],r=null,n=null;for(let a of(0,ho.stringify)(e).trimEnd().split(`
162
+ `)){let o=rA(a,r,n);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of Nw(o,t).split(`
163
+ `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?r="native":a.startsWith("classic:")?r="classic":a.startsWith("hook:")?r="hook":r=null,n=null):/^ {2}[a-z_]+:/u.test(a)&&r==="native"&&(n=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
164
+ `)}function nA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||An.posix.isAbsolute(i)||An.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function _n(e){let t=nA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function bw(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 Tc(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||An.posix.isAbsolute(r)||An.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Yi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function kw(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Ic(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>Ac)throw new Error(`${t} exceeds ${Ac} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>_c)throw new Error(`${t} contains more than ${_c} wildcard tokens`);return e}function ww(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Ic(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function jf(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function aA(e){if(e===void 0)return{...qt,include:[...qt.include],exclude:[...qt.exclude]};let t=Yi(e,"native.snapshot");return{include:ww(t.include,"native.snapshot.include",qt.include),exclude:ww(t.exclude,"native.snapshot.exclude",qt.exclude),max_files:jf(t.max_files,qt.max_files,"native.snapshot.max_files"),max_total_bytes:jf(t.max_total_bytes,qt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:jf(t.max_duration_ms,qt.max_duration_ms,"native.snapshot.max_duration_ms")}}function oA(e){if(e===void 0)return;let t=Yi(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Yi(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:_n(r),toArtifactRoot:_n(n),stage:a,...o?{cleanup:o}:{}}}function sA(e){if(e===void 0)return;let t=Yi(e,"native.finish");if(t.pull_request===void 0)return{};let i=Yi(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(An.posix.isAbsolute(r[0])||An.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??ZC;if(!Number.isSafeInteger(n)||n<1||n>gw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${gw}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function cA(e,t={}){let i=Yi(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??yw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=oA(i.pending_root_move),c=sA(i.finish);return{artifact_root:_n(r),language:kw(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:aA(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function lA(e){let t=Yi(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:bw(t.artifact_layout),language:kw(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function uA(e){let i=Yi(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Tc(r,`hook.allow_paths[${n}]`)))]}}function dA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function fA(e,t,i,r,n,a){let o=e.schema!==void 0;if(!(o||e.default_workflow!==void 0||e.workflows!==void 0||!a.allowPartialProject&&e.native!==void 0)||a.allowPartialProject&&!o)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let c=e.workflows??[e.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:l,ambient_resume:n,...t?{hook:t}:{},...i?{native:i}:{},...r?{classic:r}:{}}}function Tn(e,t={}){let i=(0,ho.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=dA(n.ambient_resume),o=n.hook===void 0?void 0:uA(n.hook),s=n.native===void 0?void 0:cA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),c=n.classic===void 0?void 0:lA(n.classic),l=fA(n,o,s,c,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}function Sw(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Ew(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Sw(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function ki(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function vo(e,t){let i=Ew(t),r=Tn((0,ho.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...ki(e.hook),allow_paths:[...r.hook.allow_paths]}),r.native){let a=ki(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(r.native.finish?.pull_request){let s=ki(a.finish);o.finish={...s,pull_request:{...ki(s.pull_request),provider:r.native.finish.pull_request.provider,command:[...r.native.finish.pull_request.command],timeout_ms:r.native.finish.pull_request.timeout_ms}}}else{let s={...ki(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,r.native.pending_root_move){let s=ki(a.pending_root_move),c=Sw(r.native.pending_root_move),l=ki(s.cleanup),u=ki(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...ki(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as pA}from"crypto";import{promises as Oc}from"fs";import Xi from"path";import{constants as jc,promises as Vr}from"fs";var Vt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function $f(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Pw(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function go(e){return{dev:e.dev,ino:e.ino,birthtime:$f(e)}}function $c(e,t){let i=go(e),r=go(t);return ht(i,r)?z(i,r):z(i,r)&&$f(e)===$f(t)&&Pw(e)===Pw(t)&&e.size===t.size}async function Wr(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Vr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Vt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Vt("too-large",`${r} exceeds ${t} bytes`);let o=await Vr.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:go(a)});let s=process.platform==="win32"?jc.O_RDONLY:jc.O_RDONLY|jc.O_NOFOLLOW|jc.O_NONBLOCK,c;try{c=await Vr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Vt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Vr.lstat(e,{bigint:n}),Vr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!$c(a,l)||!$c(a,u))throw new Vt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:go(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:E}=await c.read(v,0,Math.min(v.length,y),null);if(E===0)break;if(p+=E,p>t)throw new Vt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,E)))}await i.hooks?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([c.stat({bigint:n}),Vr.lstat(e,{bigint:n}),Vr.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||N!==o||!$c(a,h)||!$c(a,m))throw new Vt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:go(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:N}}finally{await c.close()}}function hA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Of(e,t){let i=Xi.relative(e,t);return i===""||!Xi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xi.sep}`)}async function Rw(e,t){let i=Xi.resolve(e),r=await Oc.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Oc.realpath(i)}async function xw(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Xi.join(n,i[a]);let o;try{o=await Oc.lstat(n)}catch(u){if(hA(u))return{exists:!1,kind:"missing"};throw u}let s=Xi.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Oc.realpath(n);if(!Of(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function In(e,t,i){let r=Tc(t,i.label),n=Xi.resolve(e),a=await Rw(n,i.label),o=r.split("/"),s=Xi.resolve(n,...o);if(!Of(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await xw(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Qi(e,t,i,r){let n=await In(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await Rw(n.projectRoot,r.label);return Wr(n.target,i,{...r,verify:async(o,s)=>{if(!Of(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await xw(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var wo=".comet/config.yaml";function Hf(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function mA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Hc(e,t={}){return(await yo(e,t)).document}async function Cw(e){try{return(await Qi(e,wo,po,{label:wo})).bytes}catch(t){if(mA(t))return null;throw t}}function Aw(e){return e?{exists:!0,sha256:pA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Dc(e){return Aw(await Cw(e))}async function yo(e,t={}){let i=await Cw(e);return{document:i?Tn(i.toString("utf8"),t):null,identity:Aw(i)}}async function Df(e){return(await Hc(e))?.config??null}var UL=16*1024;async function Mf(e,t){if(!t)return;let i=await Dc(e);if(!Hf(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as _w,promises as Zi}from"fs";import U from"path";import yA from"os";var Mc=".comet/config.yaml",NA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Ff(e){try{return await Zi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bA(e){try{let t=await Zi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function $n(e,t){let i=U.relative(e,t);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}async function jn(e){let t=[],i=e;for(;!await Ff(i);){let n=U.dirname(i);if(n===i)break;t.push(U.basename(i)),i=n}let r=await Zi.realpath(i);return U.resolve(r,...t.reverse())}async function Lf(e){try{return(await Zi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bf(e){let t=U.resolve(e);try{(await Zi.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=U.resolve(yA.homedir());for(;;){if(!(t===r&&i!==r)){let o=U.join(t,...Mc.split("/")),s=t===i||await bA(o);if(await Ff(o)&&s)return t}if(await Ff(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return i;t=a}}function Fc(e){return _n(e)}async function kA(e,t){let i=Fc(t),r=U.resolve(e,...i.split("/")),n=await Zi.realpath(e),a=await jn(r);if(!$n(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Le(e,t){let i=Fc(t),r=await kA(e,i),n=U.join(r,"comet");if(await Lf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([jn(r),jn(n)]);if(!$n(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await Lf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Zi.realpath(s),jn(c)]);if(!$n(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Mc.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function Iw(e){if(!NA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function it(e,t){Iw(t);let i=U.join(e.changesRuntimeDir,t);if(!$(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function zr(e,t){Iw(t);let i=U.join(e.changesDir,t,"runtime");if(!$(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=it(e,t);if(_w(i))return i;let r=zr(e,t);return _w(r)?r:i}async function Tw(e){try{let t=await Zi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function bo(e,t){let i=it(e,t),r=zr(e,t),[n,a]=await Promise.all([Tw(i),Tw(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function er(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=U.resolve(e,...t.slice(8).split("/"));if(!$(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=U.resolve(t);if($(e.runtimeDir,i))return e.runtimeDir;if($(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function $(e,t){return $n(U.resolve(e),U.resolve(t))}async function T(e,t){let i=U.resolve(e),r=U.resolve(t);if(!$n(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Lf(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([jn(i),jn(r)]);if(!$n(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var qf=qt;var Lc=Ic;async function Ne(e){let t=(await Hc(e))?.config??null;return t?.native?t:null}async function On(e){let t=await Ne(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function tr(e,t,i={}){let r=await yo(e,{allowPartialProject:!0}),n=vo(r.document?.value??{},t),a=SA.join(e,...Mc.split("/"));await ue(a,mo(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Mf(e,r.identity)}})}import{promises as NT}from"fs";import bT from"path";import{AsyncLocalStorage as EA}from"async_hooks";import{randomUUID as Hw}from"crypto";import{promises as Et}from"fs";import Dw from"os";import de from"path";var $w=16*1024,Vf=".coordinator",PA=5e3,Ow=new EA,Bc=new Map;function RA(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function xA(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 Mw(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 Wf(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ht(i,r)?z(i,r):z(i,r)&&e.size===t.size}function qc(e,t){return Wf(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function CA(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&qc(e.identity,t.identity)}async function ri(e){let t,i;try{let r=await Wr(e,$w,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Vt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${$w} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:xA(JSON.parse(t.toString("utf8")),e),identity:Mw(i)}}async function AA(e){return(await ri(e))?.owner??null}function zf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Dw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=OA(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function _A(e,t){try{await Et.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Et.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Vc(e,t){let i=await ri(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!qc(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Et.mkdir(t,{recursive:!0});let r=de.join(t,`${de.basename(e.file)}.${e.owner.id}.${Hw()}.removed`);try{await Et.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ri(r);if(!n||n.owner.id!==e.owner.id||!Wf(n.identity,e.identity))throw await _A(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Et.rm(r,{force:!0}),"removed"}function Fw(e){return{id:Hw(),pid:process.pid,hostname:Dw.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Lw(e,t){let i;try{i=await Et.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await AA(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
165
+ `,"utf8"),await i.sync(),Mw(await i.stat({bigint:!0}))}finally{await i.close()}}async function TA(e,t){let i=await T(e.runtimeDir,e.locksDir);await Et.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,de.join(i,Vf));await Et.mkdir(r,{recursive:!0});let n=Fw(t),a=de.join(r,`.${n.id}.tmp`),o=de.join(r,`${n.id}.claim`);try{let s=await Lw(a,n);await Et.rename(a,o);let c=await ri(o);if(!c||!Wf(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await Et.rm(a,{force:!0})}}async function IA(e){let t=de.dirname(e.file),i=!1,r=de.basename(e.file);for(let n of await Et.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=de.join(t,n.name);if(de.resolve(a)!==de.resolve(e.file))try{let o=await ri(a),s=zf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Vc(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Bw(e){let t=await ri(e.file);if(t){if(t.owner.id!==e.owner.id||!qc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Vc(t,de.dirname(e.file))}}async function jA(e,t){let i=Date.now()+PA;for(;;){let r=await TA(e,t);if(!await IA(r))return r;if(await Bw(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function $A(e){let t=Bc.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Bc.set(e,n),await t,()=>{i(),Bc.get(e)===n&&Bc.delete(e)}}async function Wc(e,t,i){let r=de.resolve(e.locksDir),n=Ow.getStore();if(n?.has(r))return i();let a=await $A(r);try{let o=await jA(e,t),s=new Map(n??[]);return s.set(r,o),await Ow.run(s,async()=>{try{return await i()}finally{await Bw(o)}})}finally{a()}}async function Hn(e,t,i){let r=[...new Map(e.map(a=>[de.resolve(a.locksDir),a])).values()].sort((a,o)=>de.resolve(a.locksDir).localeCompare(de.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?Wc(o,t,()=>n(a+1)):i()};return n(0)}async function ir(e,t,i){return Wc(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await Et.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,de.join(r,RA(t))),a=Fw(i),o=await Lw(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function rr(e){await ri(e.file)&&await Wc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${de.basename(e.file)}`,async()=>{let t=await ri(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!qc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=de.join(e.locksDir,Vf);await Vc(t,i)})}function OA(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function ko(e){return zf(await ri(e))}async function Jf(e,t,i){return Wc(e,`take over ${de.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(de.resolve(de.dirname(n))!==de.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ri(n),o=zf(a);if(o.status==="missing")return{status:"missing"};if(i&&!CA(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=de.join(r,Vf);return await Vc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as B_}from"node:fs";import rh from"node:path";import R_ from"node:path";import Xw from"node:path";import qw from"node:path";import{createHash as HA}from"crypto";function Wt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function DA(e,t){t.has(e)&&Wt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Wt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Wt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Wt("symbol properties are not supported"),`[${e.map(r=>Gf(r,t)).join(",")}]`}finally{t.delete(e)}}function MA(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Wt("only plain objects are supported"),t.has(e)&&Wt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Wt("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Wt("accessor properties are not supported"),`${JSON.stringify(o)}:${Gf(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Gf(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Wt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?DA(e,t):MA(e,t);case"bigint":case"function":case"symbol":case"undefined":return Wt(`${typeof e} values are not supported`)}return Wt("unsupported value type")}function So(e){return Gf(e,new Set)}function M(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return HA("sha256").update(`${e}
166
+ ${So(t)}`).digest("hex")}var FA="comet.native.acceptance.v1",LA=/^acceptance-[a-f0-9]{64}$/u,BA=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),qA=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,VA=/^[a-f0-9]{64}$/u,WA=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function zA(e,t){return e<t?-1:e>t?1:0}var Si=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Po=Object.freeze({maxCriteria:1024}),Vw="<!-- comet-native:acceptance-evidence:start -->",Ww="<!-- comet-native:acceptance-evidence:end -->";function zw(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Jw(e,t){let i=t.toString(36),r=M("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function JA(e){if(!VA.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=WA.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==M("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function GA(e,t){let i=zw(e.text,Si.maxTextBytes),r=e.context.slice(0,Si.maxContextItems).map(n=>zw(n,Si.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function Uw(e){let t=JA({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(zA),n=r.slice(0,Si.maxFailedCheckIds),a=e.criteria.slice(t,t+Si.maxItems);for(let c of a){let l=[...i,GA(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Jw(e.acceptanceHash,u):null,limits:{...Si}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Si.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Jw(e.acceptanceHash,o):null,limits:{...Si}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Si.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Kf(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 Uf(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Gw(e){return e.includes("-->")||e.includes("--!>")}function*Dn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
167
167
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
168
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Df(l,t);else if(i)Ew(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Df(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Ew(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function vA(e){return[...Tn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function ko(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function gA(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Mf(e,t,i,r=[],n="content-hash"){let a=ko(i),o=t.replaceAll("\\","/").trim(),s=r.map(ko);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${L(sA,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Lf(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function wA(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Tn(e)){n=s+1;let c=o?Ff(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function Mc(e,t="brief.md",i=So.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=wA(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Tn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Tn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Lf(o.map(l=>Mf("brief-example",t,l.join(`
169
- `),[],r)),"Brief",r)}function Lc(e,t="spec.md",i=So.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Mf("spec-scenario",t,[o.title,...o.body].join(`
170
- `),o.context,r)),o=null}};for(let{line:c,body:l}of Tn(e)){let u=l?Ff(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=ko(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Lf(n,"Specification",r)}function Bc(e,t="spec.md",i=So.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Mf("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Tn(e)){let f=d?Ff(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||Df(u,null)!==null||h.startsWith("<!--")||h==="-->"||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(p=>p.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(p=>p.text)},c();continue}s===null?s={parts:[h],context:a.map(p=>p.text)}:s.parts.push(h)}return c(),Lf(n,"Specification mandatory requirements",r)}function yA(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||gA(i)||yw.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=yw.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!uA.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function NA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!lA.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Rw(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=NA(i,r),a=n.acceptance_id;if(typeof a!="string"||!cA.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return yA(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function xw(e){let t=vA(e);if(t.some(({line:l,body:u})=>!u&&(l===Nw||l===bw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Nw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===bw?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
171
- `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Rw(o),c=bA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function bA(e){let t=Rw([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var kA=/^A[1-9]\d*$/u;function Aw(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Cw.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Cw.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function SA(e,t){return e.localeCompare(t,"en")}function qc(e){let t=Aw(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>SA(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=Mc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Aw(a.source,`Native spec source for ${a.capability}`);r.push(...Lc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Bc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=ko(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function _w(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!kA.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Tw(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var zc=xa(Sn(),1);import{promises as EA}from"node:fs";var In="comet.native.v4",Eo="comet.native.local-execution.v4";function Bf(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var PA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xA=/^A[1-9][0-9]*$/u,CA=new Set(["schema","name","language","phase","status","state_version","brief","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Wc=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function it(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function rt(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Le(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Vf(e,t){return e===null?null:Le(e,t)}function jn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function fe(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function AA(e,t){return e===null?null:fe(e,t,Number.MIN_SAFE_INTEGER)}function _e(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ri(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Jc(e,t){return ri(e,t,(i,r)=>Le(i,`${t}[${r}]`))}function Vr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function $n(e,t){let i=Le(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Wf(e,t,i=!1){let r=Le(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Vt(e,t){let i=it(e,t);return rt(i,new Set(["text","truncated"]),t),{text:Le(i.text,`${t}.text`,{empty:!0}),truncated:jn(i.truncated,`${t}.truncated`)}}function _A(e,t){let i=`Native spec_changes[${t}]`,r=it(e,i);rt(r,new Set(["capability","operation","source"]),i);let n=Le(r.capability,`${i}.capability`);if(!RA.test(n))throw new Error(`${i}.capability is invalid`);let a=_e(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Wf(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function TA(e){let t="Native workspace",i=it(e,t);rt(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=_e(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Vf(i.change_branch,`${t}.change_branch`),a=Vf(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:_e(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function IA(e){let t="Native loop",i=it(e,t);rt(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Jc(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Vr(r,`${t}.previous_unresolved_ids`),{stage:_e(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:fe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:fe(i.iteration,`${t}.iteration`),attempt:fe(i.attempt,`${t}.attempt`),retry_epoch:fe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:fe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:fe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:fe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Vf(i.next_action,`${t}.next_action`)}}function jA(e,t){let i=`Native acceptance[${t}]`,r=it(e,i);rt(r,new Set(["id","source","text","result","reason"]),i);let n=Le(r.id,`${i}.id`);if(!xA.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Wf(r.source,`${i}.source`),text:Le(r.text,`${i}.text`),result:_e(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Vt(r.reason,`${i}.reason`)}}function $A(e,t){let i=`Native builder_handoff.checks[${t}]`,r=it(e,i);return rt(r,new Set(["name","result","note"]),i),{name:Vt(r.name,`${i}.name`),result:_e(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Vt(r.note,`${i}.note`)}}function OA(e){let t="Native builder_handoff",i=it(e,t);rt(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=Jc(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Vr(r,`${t}.addressed_acceptance_ids`),{candidate_id:Le(i.candidate_id,`${t}.candidate_id`),identity_provider:Le(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Le(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),summary:Vt(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ri(i.checks,`${t}.checks`,$A),checks_truncated:jn(i.checks_truncated,`${t}.checks_truncated`),known_limits:ri(i.known_limits,`${t}.known_limits`,(n,a)=>Vt(n,`${t}.known_limits[${a}]`)),known_limits_truncated:jn(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:$n(i.submitted_at,`${t}.submitted_at`)}}function HA(e,t){let i=`Native blockers[${t}]`,r=it(e,i);rt(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Jc(r.acceptance_ids,`${i}.acceptance_ids`);return Vr(n,`${i}.acceptance_ids`),{owner:_e(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Vt(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:_e(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function DA(e,t){let i=`Native verification.checks[${t}]`,r=it(e,i);return rt(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Le(r.id,`${i}.id`),name:Vt(r.name,`${i}.name`),argv_display:ri(r.argv_display,`${i}.argv_display`,(n,a)=>Vt(n,`${i}.argv_display[${a}]`)),argv_truncated:jn(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Wf(r.cwd_ref,`${i}.cwd_ref`,!0),status:_e(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:AA(r.exit_code,`${i}.exit_code`),duration_ms:fe(r.duration_ms,`${i}.duration_ms`)}}function FA(e){let t="Native verification",i=it(e,t);rt(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ri(i.checks,`${t}.checks`,DA);Vr(r.map(a=>a.id),`${t}.checks IDs`);let n=Le(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Le(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Le(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),attempt:fe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":_e(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:_e(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Vt(i.summary,`${t}.summary`),risks:ri(i.risks,`${t}.risks`,(a,o)=>Vt(a,`${t}.risks[${o}]`)),risks_truncated:jn(i.risks_truncated,`${t}.risks_truncated`),completed_at:$n(i.completed_at,`${t}.completed_at`)}}function Iw(e,t){let i=`Native history[${t}]`,r=it(e,i);rt(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Jc(r.unresolved_ids,`${i}.unresolved_ids`);return Vr(n,`${i}.unresolved_ids`),{goal_cycle:fe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:fe(r.iteration,`${i}.iteration`),attempt:fe(r.attempt,`${i}.attempt`),outcome:_e(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Vt(r.summary,`${i}.summary`),completed_at:$n(r.completed_at,`${i}.completed_at`)}}function MA(e){let t="Native history_overflow.outcome_counts",i=it(e,t),r=["pass","fail","blocked","execution-error","recovery"];return rt(i,new Set(r),t),{pass:fe(i.pass,`${t}.pass`),fail:fe(i.fail,`${t}.fail`),blocked:fe(i.blocked,`${t}.blocked`),"execution-error":fe(i["execution-error"],`${t}.execution-error`),recovery:fe(i.recovery,`${t}.recovery`)}}function LA(e){let t="Native history_overflow",i=it(e,t);rt(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=fe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:$n(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:$n(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=MA(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function BA(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function qA(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function St(e){let t=it(e,"Native portable state");if(rt(t,CA,"Native portable state"),t.schema!==In)throw new Error(`Native portable state schema must be ${In}`);let i=Le(t.name,"Native state name");if(!PA.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ri(t.spec_changes,"Native spec_changes",_A);Vr(r.map(s=>s.capability),"Native spec change capabilities");let n=ri(t.acceptance,"Native acceptance",jA);Vr(n.map(s=>s.id),"Native acceptance IDs");let a=ri(t.history,"Native history",Iw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:In,name:i,language:_e(t.language,["en","zh-CN"],"Native state language"),phase:_e(t.phase,["shape","build","verify","archive"],"Native state phase"),status:_e(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:fe(t.state_version,"Native state_version",1),brief:"brief.md",spec_changes:r,workspace:TA(t.workspace),loop:IA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:OA(t.builder_handoff),blockers:ri(t.blockers,"Native blockers",HA),verification:t.verification===null?null:FA(t.verification),history:a,history_overflow:LA(t.history_overflow),verification_result:_e(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:_e(t.verification_report,["verification.md"],"Native verification_report"),archived:jn(t.archived,"Native archived"),created_at:$n(t.created_at,"Native created_at")};return BA(o),qA(o),o}function On(e,t){let i=St(e),r=Iw(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return St({...i,history:n,history_overflow:a})}function VA(e,t){let i=(0,zc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Et(e){let t=await EA.readFile(e,"utf8");return St(VA(t,"Native portable state"))}async function Gc(e,t,i={}){let r=St(t);await ue(e,(0,zc.stringify)(r),i)}var Vc=new Map;async function WA(e,t){let i=Vc.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Vc.set(e,a),await i;try{return await t()}finally{r(),Vc.get(e)===a&&Vc.delete(e)}}async function Wr(e){return WA(e.file,async()=>{let t=fe(e.expectedStateVersion,"Native expected state version",1),i=St(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Et(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Wc(t,r.state_version);return await Gc(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Et(e.file);if(n.state_version!==t)throw new Wc(t,n.state_version)}}),i})}function zA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function tr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(zA(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var ge="comet.native.v3",we="comet.native.v2",Ge="comet.native.v1",ir="comet.native.transition.v3",ki="comet.native.transition.v2",zr="comet.native.transition.v1";var Uc="comet.native.portable-migration.v1",GA=new Set(["schema","id","change","fromSchema","status","createdAt"]),UA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KA=/^[a-z0-9][a-z0-9-]{7,127}$/u,YA=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),XA=new Set([Ge,we,ge]);function QA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ZA(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function e_(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function t_(e){return e.schema===Ge?Jr(e):e.schema===we?ni(e):nt(e)}function i_(e){return JA.posix.normalize(e.replaceAll("\\","/"))}function r_(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:i_(t.source)})}function n_(e){return e==="shape"?"shape":"build"}function a_(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function o_(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function jw(e){let t=t_(e.state);_w(e.acceptance);let i=n_(t.phase),r=i==="shape"?0:1,n=ZA(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return St({schema:In,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:r_(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:a_(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:tr(o_(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Bf(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function zf(e){let t=QA(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!GA.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Uc)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!KA.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!UA.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!XA.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!YA.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Uc,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:e_(t.createdAt,"Native portable migration transaction createdAt")}}function $w(e){switch(zf(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Kc="comet.native.archive-transaction.v4",Ow="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",c_=new RegExp(`^portable-archive-(${Ow})\\.json$`,"u"),l_=new RegExp(`^portable-migration-(${Ow})\\.json$`,"u"),u_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,d_=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,f_=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),h_=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),p_=new Set(["capability","operation","source","content"]),Hw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Dw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fw(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function m_(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Dw(e,i);if(Fw(r,p_,i),typeof r.capability!="string"||!Hw.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function v_(e){let t=Dw(e,"Native portable Archive transaction");if(Fw(t,h_,"Native portable Archive transaction"),t.schema!==Kc)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!u_.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Hw.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!d_.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!f_.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(m_);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Kc,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Gr(e){let t=c_.exec(e);if(t)return{kind:"archive",change:t[1]};let i=l_.exec(e);return i?{kind:"migration",change:i[1]}:null}function rr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Gr(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Jf.join(e.transactionsDir,i)}async function Po(e,t){let i=Gr(t);if(!i)return null;let r=await ee({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Jf.join(e.transactionsDir,t);if(i.kind==="archive"){let s=v_(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=zf(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function Yc(e,t){let i=rr(e,t);try{return await Po(e,Jf.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Mw(e){let t;try{t=await s_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Gr(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function Lw(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Ro}from"fs";import Pt from"path";import{TextDecoder as b_}from"util";import{createHash as g_}from"node:crypto";import{constants as Xc,promises as z}from"node:fs";import K from"node:path";import{TextDecoder as w_}from"node:util";function Be(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}function Bw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Dn(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Hn(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function nr(e,t){let i=await z.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function ar(e,t,i){let r=K.resolve(e),n=K.resolve(t);if(!Be(r,n))throw new Error(`${i} is outside its managed root`);let a=[await nr(r,i)],o=r;for(let s of K.relative(r,n).split(K.sep).filter(Boolean)){await ve(a,i),o=K.join(o,s);let c=await nr(o,i);if(!Be(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ve(a,i),a}async function ve(e,t){for(let i of e){let r=await z.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Dn(i,r)||await z.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function y_(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ie(e){let t=Bw(e.maxBytes),i=K.resolve(e.file),r=await ar(e.root,K.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>nr(K.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ve(r,e.label);let a=await z.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=qw(a),s=await z.realpath(i);if(!Be(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Be(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Xc.O_RDONLY:Xc.O_RDONLY|Xc.O_NOFOLLOW|Xc.O_NONBLOCK,l=await z.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Hn(o,u)||!Hn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await y_(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),z.lstat(i),z.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!p.isFile()||p.isSymbolicLink()||m!==s||!Hn(o,v)||!Hn(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:g_("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Qc(e){let t=await ie(e),i;try{i=new w_("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function ft(e){let t=await ar(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await z.readdir(e.directory,{withFileTypes:!0});else{let r=Bw(e.maxEntries);i=[];let n=await z.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ve(t,e.label),{entries:i,verify:()=>ve(t,e.label)}}async function Wt(e){let t=await ar(e.root,e.directory,e.label);return{verify:()=>ve(t,e.label)}}async function N_(e){let t=K.resolve(e.directory),i=K.resolve(e.quarantine);if(K.dirname(i)!==K.dirname(t)||!Be(K.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await ar(e.root,K.dirname(t),e.label),n=await nr(t,e.label);if(!Be(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ve(r,e.label);let a=await z.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Dn(n,a)||await z.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await z.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await z.rename(t,i),await ve(r,e.label);let o=await z.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Dn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await z.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function Vw(e){await N_(e)}async function Zc(e){let t=K.resolve(e.file),i=await ar(e.root,K.dirname(t),e.label),r=await z.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=qw(r),a=await z.realpath(t);if(!Be(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Hn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ve(i,e.label);let[l,u]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Hn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await z.rm(t),await ve(i,e.label)}async function Gf(e){let t=K.resolve(e.directory),i=await ar(e.root,K.dirname(t),e.label),r=await nr(t,e.label);if(!Be(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ve(i,e.label);let n=await z.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Dn(r,n)||await z.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await z.rmdir(t),await ve(i,e.label)}async function ai(e){let t=K.resolve(e.root),i=K.resolve(e.directory);if(!Be(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await nr(t,e.label)],n=t;for(let a of K.relative(t,i).split(K.sep).filter(Boolean)){await ve(r,e.label),n=K.join(n,a);try{await z.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await nr(n,e.label);if(!Be(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await ve(r,e.label)}async function Uf(e){let t=K.resolve(e.root),i=K.resolve(e.source),r=K.resolve(e.target);if(i===r||!Be(t,i)||!Be(t,r)||Be(i,r)||Be(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await ai({root:t,directory:K.dirname(r),label:`${e.label} target parent`});let n=await ar(t,K.dirname(i),e.label),a=await ar(t,K.dirname(r),e.label),o=await nr(i,e.label);if(!Be(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await z.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ve(n,e.label),ve(a,e.label)]);let s=await z.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Dn(o,s)||await z.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await z.rename(i,r),await Promise.all([ve(n,e.label),ve(a,e.label)]);let c=await z.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Dn(o,c)||!Be(n[0].realPath,await z.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await z.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function or(e){let t=await ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Ug(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await z.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var k_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),S_=new Set(["id","type","source","target","staged","backup"]),E_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),P_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),R_=new Set(["sequence","timestamp","type","operationId"]),Gw=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Uw=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),x_=256*1024,C_=1024*1024,Kw=16*1024,tl=1024,Xf=64*1024*1024,A_=2e4,Yw=new b_("utf-8",{fatal:!0});function xo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Co(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Mn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Kf(e,t){if(typeof e!="string"||e.length===0||Pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function el(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Ww(e,t){if(Kf(e,t),e.includes("\\")||e!==Pt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function __(e,t){let i=xo(e,`transaction operations[${t}]`);if(Co(i,S_,`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`);Kf(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Kf(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function rl(e){let t=xo(e,"Native Archive transaction journal");if(Co(t,E_,"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"||!Gw.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(!Mn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(el(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=xo(s,`Archive transaction operations[${c}]`);if(Co(l,P_,`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`);Ww(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Ww(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&el(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(el(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`);el(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Qf(e){let t=xo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return rl(t);if(Co(t,k_,"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"||!Gw.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Pt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Mn(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(__),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Xw(e,t){let i=xo(e,`Native transaction event at line ${t}`);if(Co(i,R_,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Mn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Uw.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function T_(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Mn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Mn(e)}function Fn(e,t){return e.length<t.length&&t.startsWith(e)}function I_(e){let t='","operationId":"';if(Fn(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Fn(i.slice(r),'"}'):!1}function j_(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Kw)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Fn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!T_(n))return!1;if(r.length<24)return!0;if(!Mn(n))return!1;let a='","type":"',o=r.slice(24);if(Fn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Uw){if(Fn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(I_(l))return!0}else if(Fn(l,'"}'))return!0}return!1}function $_(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Kw)throw new Error(`Native transaction event at line ${t} is too large`);return Xw(JSON.parse(e),t)}function O_(e){let t=e.split(`
172
- `),i=t.at(-1)==="";if(i&&t.pop(),t.length>tl)throw new Error(`Native transaction event log exceeds ${tl} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push($_(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&j_(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function Qw(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
168
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=Uf(l,t);else if(i)Gw(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Uf(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Gw(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function UA(e){return[...Dn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Eo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function KA(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Yf(e,t,i,r=[],n="content-hash"){let a=Eo(i),o=t.replaceAll("\\","/").trim(),s=r.map(Eo);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${M(FA,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Xf(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function YA(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Dn(e)){n=s+1;let c=o?Kf(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function zc(e,t="brief.md",i=Po.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=YA(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Dn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Dn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Xf(o.map(l=>Yf("brief-example",t,l.join(`
169
+ `),[],r)),"Brief",r)}function Jc(e,t="spec.md",i=Po.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Yf("spec-scenario",t,[o.title,...o.body].join(`
170
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of Dn(e)){let u=l?Kf(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Eo(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Xf(n,"Specification",r)}function Gc(e,t="spec.md",i=Po.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Yf("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Dn(e)){let f=d?Kf(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Uf(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Xf(n,"Specification mandatory requirements",r)}function XA(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||KA(i)||qw.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=qw.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!qA.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function QA(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!BA.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Kw(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=QA(i,r),a=n.acceptance_id;if(typeof a!="string"||!LA.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return XA(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Yw(e){let t=UA(e);if(t.some(({line:l,body:u})=>!u&&(l===Vw||l===Ww)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Vw?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Ww?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
171
+ `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Kw(o),c=ZA(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function ZA(e){let t=Kw([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var e_=/^A[1-9]\d*$/u;function Qw(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Xw.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Xw.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function t_(e,t){return e.localeCompare(t,"en")}function Uc(e){let t=Qw(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>t_(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=zc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=Qw(a.source,`Native spec source for ${a.capability}`);r.push(...Jc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})),...Gc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Eo(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Zw(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!e_.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function ey(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Xc=mn(qr(),1);import{promises as i_}from"node:fs";var Mn="comet.native.v4",Ro="comet.native.local-execution.v4";function Qf(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var r_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,n_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,a_=/^A[1-9][0-9]*$/u,o_=/^[a-f0-9]{64}$/u,s_=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Yc=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function nt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function at(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Te(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function eh(e,t){return e===null?null:Te(e,t)}function c_(e,t){let i=Te(e,t);if(!o_.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Fn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function fe(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function l_(e,t){return e===null?null:fe(e,t,Number.MIN_SAFE_INTEGER)}function _e(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ni(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Qc(e,t){return ni(e,t,(i,r)=>Te(i,`${t}[${r}]`))}function Jr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Ln(e,t){let i=Te(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function th(e,t,i=!1){let r=Te(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function zt(e,t){let i=nt(e,t);return at(i,new Set(["text","truncated"]),t),{text:Te(i.text,`${t}.text`,{empty:!0}),truncated:Fn(i.truncated,`${t}.truncated`)}}function u_(e,t){let i=`Native spec_changes[${t}]`,r=nt(e,i);at(r,new Set(["capability","operation","source"]),i);let n=Te(r.capability,`${i}.capability`);if(!n_.test(n))throw new Error(`${i}.capability is invalid`);let a=_e(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:th(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function d_(e){let t="Native workspace",i=nt(e,t);at(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=_e(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=eh(i.change_branch,`${t}.change_branch`),a=eh(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:_e(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function f_(e){let t="Native loop",i=nt(e,t);at(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Qc(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Jr(r,`${t}.previous_unresolved_ids`),{stage:_e(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:fe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:fe(i.iteration,`${t}.iteration`),attempt:fe(i.attempt,`${t}.attempt`),retry_epoch:fe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:fe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:fe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:fe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:eh(i.next_action,`${t}.next_action`)}}function h_(e,t){let i=`Native acceptance[${t}]`,r=nt(e,i);at(r,new Set(["id","source","text","result","reason"]),i);let n=Te(r.id,`${i}.id`);if(!a_.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:th(r.source,`${i}.source`),text:Te(r.text,`${i}.text`),result:_e(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:zt(r.reason,`${i}.reason`)}}function p_(e,t){let i=`Native builder_handoff.checks[${t}]`,r=nt(e,i);return at(r,new Set(["name","result","note"]),i),{name:zt(r.name,`${i}.name`),result:_e(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:zt(r.note,`${i}.note`)}}function m_(e){let t="Native builder_handoff",i=nt(e,t);at(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),t);let r=Qc(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);return Jr(r,`${t}.addressed_acceptance_ids`),{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:Te(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Te(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),summary:zt(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ni(i.checks,`${t}.checks`,p_),checks_truncated:Fn(i.checks_truncated,`${t}.checks_truncated`),known_limits:ni(i.known_limits,`${t}.known_limits`,(n,a)=>zt(n,`${t}.known_limits[${a}]`)),known_limits_truncated:Fn(i.known_limits_truncated,`${t}.known_limits_truncated`),submitted_at:Ln(i.submitted_at,`${t}.submitted_at`)}}function v_(e,t){let i=`Native blockers[${t}]`,r=nt(e,i);at(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Qc(r.acceptance_ids,`${i}.acceptance_ids`);return Jr(n,`${i}.acceptance_ids`),{owner:_e(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:zt(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:_e(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function g_(e,t){let i=`Native verification.checks[${t}]`,r=nt(e,i);return at(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Te(r.id,`${i}.id`),name:zt(r.name,`${i}.name`),argv_display:ni(r.argv_display,`${i}.argv_display`,(n,a)=>zt(n,`${i}.argv_display[${a}]`)),argv_truncated:Fn(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:th(r.cwd_ref,`${i}.cwd_ref`,!0),status:_e(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:l_(r.exit_code,`${i}.exit_code`),duration_ms:fe(r.duration_ms,`${i}.duration_ms`)}}function w_(e){let t="Native verification",i=nt(e,t);at(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ni(i.checks,`${t}.checks`,g_);Jr(r.map(a=>a.id),`${t}.checks IDs`);let n=Te(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Te(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Te(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:fe(i.iteration,`${t}.iteration`,1),attempt:fe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":_e(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:_e(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:zt(i.summary,`${t}.summary`),risks:ni(i.risks,`${t}.risks`,(a,o)=>zt(a,`${t}.risks[${o}]`)),risks_truncated:Fn(i.risks_truncated,`${t}.risks_truncated`),completed_at:Ln(i.completed_at,`${t}.completed_at`)}}function ty(e,t){let i=`Native history[${t}]`,r=nt(e,i);at(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Qc(r.unresolved_ids,`${i}.unresolved_ids`);return Jr(n,`${i}.unresolved_ids`),{goal_cycle:fe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:fe(r.iteration,`${i}.iteration`),attempt:fe(r.attempt,`${i}.attempt`),outcome:_e(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:zt(r.summary,`${i}.summary`),completed_at:Ln(r.completed_at,`${i}.completed_at`)}}function y_(e){let t="Native history_overflow.outcome_counts",i=nt(e,t),r=["pass","fail","blocked","execution-error","recovery"];return at(i,new Set(r),t),{pass:fe(i.pass,`${t}.pass`),fail:fe(i.fail,`${t}.fail`),blocked:fe(i.blocked,`${t}.blocked`),"execution-error":fe(i["execution-error"],`${t}.execution-error`),recovery:fe(i.recovery,`${t}.recovery`)}}function N_(e){let t="Native history_overflow",i=nt(e,t);at(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=fe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Ln(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Ln(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=y_(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function b_(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff&&!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function k_(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function rt(e){let t=nt(e,"Native portable state");if(at(t,s_,"Native portable state"),t.schema!==Mn)throw new Error(`Native portable state schema must be ${Mn}`);let i=Te(t.name,"Native state name");if(!r_.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ni(t.spec_changes,"Native spec_changes",u_);Jr(r.map(s=>s.capability),"Native spec change capabilities");let n=ni(t.acceptance,"Native acceptance",h_);Jr(n.map(s=>s.id),"Native acceptance IDs");let a=ni(t.history,"Native history",ty);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Mn,name:i,language:_e(t.language,["en","zh-CN"],"Native state language"),phase:_e(t.phase,["shape","build","verify","archive"],"Native state phase"),status:_e(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:fe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:c_(t.children_contract_hash,"Native children contract hash")},spec_changes:r,workspace:d_(t.workspace),loop:f_(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:m_(t.builder_handoff),blockers:ni(t.blockers,"Native blockers",v_),verification:t.verification===null?null:w_(t.verification),history:a,history_overflow:N_(t.history_overflow),verification_result:_e(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:_e(t.verification_report,["verification.md"],"Native verification_report"),archived:Fn(t.archived,"Native archived"),created_at:Ln(t.created_at,"Native created_at")};return b_(o),k_(o),o}function Bn(e,t){let i=rt(e),r=ty(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return rt({...i,history:n,history_overflow:a})}function S_(e,t){let i=(0,Xc.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ge(e){let t=await i_.readFile(e,"utf8");return rt(S_(t,"Native portable state"))}async function Zc(e,t,i={}){let r=rt(t);await ue(e,(0,Xc.stringify)(r),i)}var Kc=new Map;async function E_(e,t){let i=Kc.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);Kc.set(e,a),await i;try{return await t()}finally{r(),Kc.get(e)===a&&Kc.delete(e)}}async function Gr(e){return E_(e.file,async()=>{let t=fe(e.expectedStateVersion,"Native expected state version",1),i=rt(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ge(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Yc(t,r.state_version);return await Zc(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ge(e.file);if(n.state_version!==t)throw new Yc(t,n.state_version)}}),i})}function P_(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function nr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(P_(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var ge="comet.native.v3",we="comet.native.v2",Ue="comet.native.v1",ar="comet.native.transition.v3",Ei="comet.native.transition.v2",Ur="comet.native.transition.v1";var el="comet.native.portable-migration.v1",x_=new Set(["schema","id","change","fromSchema","status","createdAt"]),C_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A_=/^[a-z0-9][a-z0-9-]{7,127}$/u,__=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),T_=new Set([Ue,we,ge]);function I_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function j_(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function $_(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function O_(e){return e.schema===Ue?Kr(e):e.schema===we?ai(e):ot(e)}function H_(e){return R_.posix.normalize(e.replaceAll("\\","/"))}function D_(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:H_(t.source)})}function M_(e){return e==="shape"?"shape":"build"}function F_(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function L_(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function iy(e){let t=O_(e.state);Zw(e.acceptance);let i=M_(t.phase),r=i==="shape"?0:1,n=j_(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return rt({schema:Mn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:D_(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:F_(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:nr(L_(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Qf(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function ih(e){let t=I_(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!x_.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==el)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!A_.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!C_.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!T_.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!__.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:el,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:$_(t.createdAt,"Native portable migration transaction createdAt")}}function ry(e){switch(ih(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var tl="comet.native.archive-transaction.v4",ny="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",q_=new RegExp(`^portable-archive-(${ny})\\.json$`,"u"),V_=new RegExp(`^portable-migration-(${ny})\\.json$`,"u"),W_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,z_=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,J_=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),G_=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),U_=new Set(["capability","operation","source","content"]),ay=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function oy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function sy(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function K_(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=oy(e,i);if(sy(r,U_,i),typeof r.capability!="string"||!ay.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function Y_(e){let t=oy(e,"Native portable Archive transaction");if(sy(t,G_,"Native portable Archive transaction"),t.schema!==tl)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!W_.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!ay.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!z_.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!J_.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(K_);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:tl,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function Yr(e){let t=q_.exec(e);if(t)return{kind:"archive",change:t[1]};let i=V_.exec(e);return i?{kind:"migration",change:i[1]}:null}function or(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=Yr(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return rh.join(e.transactionsDir,i)}async function xo(e,t){let i=Yr(t);if(!i)return null;let r=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=rh.join(e.transactionsDir,t);if(i.kind==="archive"){let s=Y_(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=ih(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function il(e,t){let i=or(e,t);try{return await xo(e,rh.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function cy(e){let t;try{t=await B_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>Yr(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function ly(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Co}from"fs";import Pt from"path";import{TextDecoder as tT}from"util";import{createHash as X_}from"node:crypto";import{constants as rl,promises as W}from"node:fs";import K from"node:path";import{TextDecoder as Q_}from"node:util";function Be(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}function uy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Vn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function qn(e,t){return z({...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 sr(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function cr(e,t,i){let r=K.resolve(e),n=K.resolve(t);if(!Be(r,n))throw new Error(`${i} is outside its managed root`);let a=[await sr(r,i)],o=r;for(let s of K.relative(r,n).split(K.sep).filter(Boolean)){await ve(a,i),o=K.join(o,s);let c=await sr(o,i);if(!Be(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ve(a,i),a}async function ve(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Vn(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Z_(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ie(e){let t=uy(e.maxBytes),i=K.resolve(e.file),r=await cr(e.root,K.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>sr(K.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ve(r,e.label);let a=await W.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=dy(a),s=await W.realpath(i);if(!Be(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Be(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?rl.O_RDONLY:rl.O_RDONLY|rl.O_NOFOLLOW|rl.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!qn(o,u)||!qn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Z_(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await ve(r,e.label),await ve(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!qn(o,v)||!qn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:X_("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function nl(e){let t=await ie(e),i;try{i=new Q_("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function pt(e){let t=await cr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=uy(e.maxEntries);i=[];let n=await W.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ve(t,e.label),{entries:i,verify:()=>ve(t,e.label)}}async function Jt(e){let t=await cr(e.root,e.directory,e.label);return{verify:()=>ve(t,e.label)}}async function eT(e){let t=K.resolve(e.directory),i=K.resolve(e.quarantine);if(K.dirname(i)!==K.dirname(t)||!Be(K.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await cr(e.root,K.dirname(t),e.label),n=await sr(t,e.label);if(!Be(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ve(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Vn(n,a)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await ve(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Vn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function fy(e){await eT(e)}async function al(e){let t=K.resolve(e.file),i=await cr(e.root,K.dirname(t),e.label),r=await W.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=dy(r),a=await W.realpath(t);if(!Be(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!qn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ve(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!qn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await ve(i,e.label)}async function nh(e){let t=K.resolve(e.directory),i=await cr(e.root,K.dirname(t),e.label),r=await sr(t,e.label);if(!Be(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ve(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Vn(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await ve(i,e.label)}async function oi(e){let t=K.resolve(e.root),i=K.resolve(e.directory);if(!Be(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await sr(t,e.label)],n=t;for(let a of K.relative(t,i).split(K.sep).filter(Boolean)){await ve(r,e.label),n=K.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await sr(n,e.label);if(!Be(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await ve(r,e.label)}async function ah(e){let t=K.resolve(e.root),i=K.resolve(e.source),r=K.resolve(e.target);if(i===r||!Be(t,i)||!Be(t,r)||Be(i,r)||Be(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await oi({root:t,directory:K.dirname(r),label:`${e.label} target parent`});let n=await cr(t,K.dirname(i),e.label),a=await cr(t,K.dirname(r),e.label),o=await sr(i,e.label);if(!Be(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ve(n,e.label),ve(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Vn(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,r),await Promise.all([ve(n,e.label),ve(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Vn(o,c)||!Be(n[0].realPath,await W.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function lr(e){let t=await ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await vw(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var iT=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),rT=new Set(["id","type","source","target","staged","backup"]),nT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),aT=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),oT=new Set(["sequence","timestamp","type","operationId"]),vy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),gy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),sT=256*1024,cT=1024*1024,wy=16*1024,sl=1024,ch=64*1024*1024,lT=2e4,yy=new tT("utf-8",{fatal:!0});function Ao(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _o(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function zn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function oh(e,t){if(typeof e!="string"||e.length===0||Pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ol(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function hy(e,t){if(oh(e,t),e.includes("\\")||e!==Pt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function uT(e,t){let i=Ao(e,`transaction operations[${t}]`);if(_o(i,rT,`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`);oh(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&oh(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function ll(e){let t=Ao(e,"Native Archive transaction journal");if(_o(t,nT,"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"||!vy.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!zn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ol(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=Ao(s,`Archive transaction operations[${c}]`);if(_o(l,aT,`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`);hy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&hy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&ol(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(ol(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`);ol(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function lh(e){let t=Ao(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return ll(t);if(_o(t,iT,"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"||!vy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Pt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!zn(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(uT),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Ny(e,t){let i=Ao(e,`Native transaction event at line ${t}`);if(_o(i,oT,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!zn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!gy.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function dT(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!zn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||zn(e)}function Wn(e,t){return e.length<t.length&&t.startsWith(e)}function fT(e){let t='","operationId":"';if(Wn(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Wn(i.slice(r),'"}'):!1}function hT(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>wy)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Wn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!dT(n))return!1;if(r.length<24)return!0;if(!zn(n))return!1;let a='","type":"',o=r.slice(24);if(Wn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of gy){if(Wn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(fT(l))return!0}else if(Wn(l,'"}'))return!0}return!1}function pT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>wy)throw new Error(`Native transaction event at line ${t} is too large`);return Ny(JSON.parse(e),t)}function mT(e){let t=e.split(`
172
+ `),i=t.at(-1)==="";if(i&&t.pop(),t.length>sl)throw new Error(`Native transaction event log exceeds ${sl} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(pT(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&hT(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function by(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
173
173
  `)}
174
- `}function H_(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Pt.join(e.transactionsDir,t)}function nl(e,t){let i=H_(e,t);return{directory:i,journal:Pt.join(i,"transaction.json"),events:Pt.join(i,"events.jsonl"),staged:Pt.join(i,"staged"),backups:Pt.join(i,"backups")}}async function oi(e,t){let i=nl(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function D_(e,t){if(t.length===0||Pt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=Pt.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function sr(e,t){let i=D_(e,t);return T(j(e,i),i)}async function Ur(e){try{return await Ro.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Zf(e,t,i={}){let r=await oi(e,t);try{await Ro.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ie({root:e.runtimeDir,file:r.events,maxBytes:C_,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=Yw.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=O_(a),s=Qw(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function zw(e,t,i){let r=await Zf(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Rt(e,t,i,r){let n=await oi(e,t),a=await Zf(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await ue(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>zw(e,t,a)}),o;if(a.events.length>=tl)throw new Error(`Native transaction event log ${t} exceeds ${tl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return Xw(s,s.sequence),await Ro.mkdir(n.directory,{recursive:!0}),await ue(n.events,Qw([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>zw(e,t,a)}),s}async function Zw(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Qf(t);let i=await oi(e,t.id);await Ro.mkdir(i.staged,{recursive:!0}),await Ro.mkdir(i.backups,{recursive:!0}),await te(i.journal,t,{containedRoot:e.runtimeDir}),await Rt(e,t.id,"prepared")}async function ht(e,t,i={}){let r=await oi(e,t),n=await ie({root:e.runtimeDir,file:r.journal,maxBytes:x_,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Yw.decode(n.bytes)),o=Qf(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function cr(e,t,i={}){return(await Zf(e,t,i)).events}async function il(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=Qf({...t,status:i});return await te((await oi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function Yf(e,t,i){try{return await ie({root:j(e,t),file:t,maxBytes:Xf,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function eh(e,t,i,r){let n=await Yf(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await Yf(e,i,`${r} target`);await ai({root:j(e,i),directory:Pt.dirname(i),label:`${r} target parent`}),await or({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Xf,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function ey(e,t,i){let r=await Yf(e,t,i);r&&await Zc({root:j(e,t),file:t,maxBytes:Xf,expectedHash:r.hash,expectedSize:r.size,label:i})}async function Jw(e,t){if(!t.backup)return;let i=await sr(e,t.target),r=await sr(e,t.backup);!await Ur(i)||await Ur(r)||await eh(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function F_(e,t){let i=await sr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Jw(e,t),await eh(e,await sr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Jw(e,t),await ey(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await sr(e,t.source),[n,a]=await Promise.all([Ur(r),Ur(i)]);if(!n&&a){await(await ft({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:A_})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Uf({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function ty(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await il(e,t,"applying"):t,n=await cr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Rt(e,r.id,"operation-started",s.id),await F_(e,s),await Rt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await ht(e,r.id),r}async function M_(e,t){let i=await sr(e,t.target),r=t.backup?await sr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await sr(e,t.source);if(await Ur(i)){if(await Ur(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Uf({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Ur(r)?await eh(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await ey(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function al(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await cr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await il(e,t,"rolling-back");await Rt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await M_(e,a);return await Rt(e,r.id,"rollback-completed"),r=await il(e,r,"rolled-back"),r}async function Ln(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Rt(e,t.id,i),i==="commit"?il(e,t,"committed"):t}async function q_(e,t,i){let r;try{r=await L_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await ht(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Gr(n.name))try{let a=await Po(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Lw(a))return!0}catch{return!0}return!1}async function V_(e,t){let i=Date.now()+5e3,r=B_.join(e.locksDir,"root-move.lock");for(;;)try{return await Zi(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await No(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function he(e,t,i,r){let n=await V_(e,t);try{if(await _n(e.projectRoot),await q_(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await er(n)}}function iy(e){return Number.isSafeInteger(e)&&e>=1}async function ry(e){if(!iy(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(!iy(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as ul}from"crypto";import{spawn as hy}from"node:child_process";import{promises as oe}from"fs";import B from"path";import{createHash as ny}from"crypto";import{createReadStream as W_}from"fs";async function zt(e){let t=ny("sha256");for await(let i of W_(e))t.update(i);return t.digest("hex")}function D(e){return ny("sha256").update(e).digest("hex")}var ol={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},oh=1e3,z_=8*1024*1024,J_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,G_=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),U_=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),K_=new Set(["schema","include","exclude","hash"]),Y_=new Set(["provider","gitSelection","physicalSelection","projection"]),X_=new Set(["provider","selection"]),Q_=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Z_=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),eT=new Set(["schema","status","before","after"]),tT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),iT=new Set(["path","hash","size","type","gitObjectId"]),rT=new Set(["path","size","type","reason"]),nT=new Set(["ref","hash","count"]),aT=new Set(["change-created","legacy-migration","explicit"]),oT=new Set(["file","directory","other"]),sT=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"]),dl=/^[a-f0-9]{64}$/u,py=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,cT=new Set(["EACCES","EPERM"]),zn=64*1024,nh=64*1024,lT=6e4,uT=1e3,dT=2,sh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},fT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function my(e){let t=e.deadlineMs??lT;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 Jt(e){return Math.max(0,e.deadlineAt-Date.now())}function F(e){return Jt(e)>=1}function th(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 Vn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function hT(e){let t={...fT,...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 pT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&B.win32.isAbsolute(r)?B.win32.resolve(r):"C:\\Windows",a=B.win32.join(n,"System32","taskkill.exe");if(!B.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=hy(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),uT),u.unref()}catch{d(!1)}});for(let s=0;s<dT;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function ch(e,t,i,r){let n=Jt(e);if(n<1)throw th();let a=e.gitProcess,o=hy(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=pT(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?th(v.error):th()}return{code:h,spawnError:s}});return{child:o,completion:f}}function vy(e){let t={...sh,...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 sl(e,t,i,r=nh){let{child:n,completion:a}=ch(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=zn)return;let v=zn-c,p=Buffer.from(h).subarray(0,v);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function ih(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function _o(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=ch(e,t,i,r.stdin!==void 0),c=[],l=ul("sha256"),u=[],d=0,f=0,h=0,v=0,p=Buffer.alloc(0),m=!1,b=!1,y=!1,P=S=>{let k=0;for(;k<S.byteLength;){let N=S.indexOf(0,k),R=N<0?S.byteLength:N,w=S.subarray(k,R);if(!m&&w.byteLength>0&&(p.byteLength+w.byteLength>r.maxRecordBytes?(p=Buffer.alloc(0),m=!0,b=!0):p=Buffer.concat([p,w])),N<0)break;v+=1,p.byteLength===0&&!m&&(y=!0);let g=p.byteLength+1;!m&&v<=r.maxRecords&&h+g<=r.maxBytes?(c.push(p),h+=g):b=!0,p=Buffer.alloc(0),m=!1,k=N+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){P(S);return}for(let N=0;N<S.byteLength;N+=k)P(S.subarray(N,Math.min(S.byteLength,N+k)))}),o.stderr.on("data",S=>{if(d>=zn)return;let k=zn-d,N=Buffer.from(S).subarray(0,k);u.push(N),d+=N.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let N=r.acceptedExitCodes??[0];if(S!==null&&N.includes(S)&&k===null&&!y&&p.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||p.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function cl(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 mT(e,t,i){if(i.length===0)return new Set;let r=await _o(e,t,["check-ignore","--no-index","-z","--stdin"],{...sh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=cl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function vT(e,t,i){let{child:r,completion:n}=ch(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=zn)return;let d=zn-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Wn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||B.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||B.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function gT(e,t){return e.map(i=>{let r=Wn(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function wT(e){let t=B.resolve(e);for(;;){try{return await oe.lstat(B.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=B.dirname(t);if(i===t)return!1;t=i}}async function gy(e,t,i,r={}){let n=B.resolve(t.projectRoot),a=B.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=B.relative(n,B.resolve(f)).replaceAll("\\","/"),v=Wn(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await _o(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await _o(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await _o(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function wy(e){return{stageBefore:ih(e.stagedBefore),combined:ih(e.combined),stageAfter:ih(e.stagedAfter)}}async function yy(e,t,i=sh,r={}){let n=B.resolve(t.projectRoot);if(!await wT(n))return null;let a;try{a=await sl(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Vn(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await gy(e,t,i,r)}catch(y){throw Vn(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=y=>{for(let P of y){let S=cl(P),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let N=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(S.slice(0,k))?.groups;if(!N)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Wn(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),N.stage==="0"&&d.set(R,N.objectId),N.mode==="160000"&&N.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(cl),p=gT(v,"combined"),m=new Set(p.filter(y=>!u.has(y))),b=new Set(p.filter((y,P)=>!u.has(y)&&v[P].endsWith("/")));for(let y of f)b.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:wy(o)}}function ur(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function ay(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function yT(e,t){return!ur(e.stageBefore,e.stageAfter)||!ur(e.stageAfter,t.stageBefore)||!ur(e.combined,t.combined)||!ur(t.stageBefore,t.stageAfter)}async function Ny(e,t,i,r,n){let a;try{a=await gy(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Vn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=wy(a),c=ay(o)||ay(s),l=yT(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:D(`comet.native.git-selection-overflow.v2
175
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var NT=(1n<<256n)-1n;function bT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function oy(e){let t=B.resolve(e.paths.projectRoot),i=B.resolve(e.paths.nativeRoot),r=B.resolve(e.paths.runtimeDir),n=B.resolve(e.paths.configFile),a=B.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,p=!1,m=()=>Jt(e.execution)>=1?!0:(h=!0,p=!0,!1),b=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),N=ul("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=N[R];if(l=l+BigInt(`0x${N.toString("hex")}`)&NT,d+=1,f+=k.byteLength,Buffer.byteLength(S.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,p=!0;return}o.push(S)},y=async S=>{if(p||!m())return;let k;try{k=await oe.opendir(S)}catch(E){if(!m())return;if(!be(E)&&!Ne(E)||S===t&&be(E))throw E;v||=Ne(E),h||=be(E),p=!0;return}if(!m()){try{await k.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let N=!1,R;try{for(;!p&&m();){let E;try{E=await k.read()}catch(Q){if(!m())break;if(!be(Q)&&!Ne(Q)||S===t&&be(Q))throw Q;v||=Ne(Q),h||=be(Q),p=!0;break}if(!m()||E===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,p=!0;break}let q=B.join(S,E.name),O=ST(t,q);if(q===n||q===a||Gt(i,q)||Gt(r,q)||e.denylist.some(Q=>Gt(Q,q))||ti(O)!==null)continue;if(!m())break;let He;try{He=await oe.lstat(q)}catch(Q){if(!m())break;if(!be(Q)&&!Ne(Q))throw Q;if(v=!0,b({path:O,type:"other"}),s.push({path:O,size:null,type:"file",reason:be(Q)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),p||!m())break;continue}if(!m())break;let ce=bT(He);if(ce==="directory"){if(xT(e.policy,O))continue;if(!m())break;let Q;try{Q=await oe.realpath(q)}catch(Qt){if(!m())break;if(!be(Qt)&&!Ne(Qt))throw Qt;if(v=!0,b({path:O,type:ce}),s.push({path:O,size:null,type:"directory",reason:be(Qt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),p||!m())break;continue}if(!m())break;if(!$(e.physicalProjectRoot,Q)||Gt(e.physicalNativeRoot,Q))continue;if(b({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||(await y(q),p))break;continue}if(b({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||p)break}}catch(E){N=!0,R=E}let w;try{await k.close()}catch(E){w=E}let g=m();if(N)throw R;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await y(t),m(),h?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let P=h?D(`comet.native.physical-selection-incomplete.v1
176
- ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):D(`comet.native.physical-selection.v1
177
- ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:P,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function by(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 kT(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!by(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function ky(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function sy(e,t){let r=(await sl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!py.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return D(`gitlink:${r}`)}async function cy(e,t){let i=await sy(e,t),r=await vT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await sy(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Ao(e,t){if(ti(t)!==null)return!1;let i=B.resolve(e.projectRoot,...t.split("/"));return!Gt(B.resolve(e.nativeRoot),i)&&!Gt(B.resolve(e.runtimeDir),i)}function lh(e,t={}){let i=Si(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function ST(e,t){return B.relative(e,t).split(B.sep).join("/")}function ET(e,t){return t.map(i=>B.resolve(e,...i.split(/[\\/]/u)))}function Gt(e,t){let i=B.resolve(e),r=B.resolve(t);return r===i||$(i,r)}function be(e){return cT.has(e.code??"")}function Ne(e){return e.code==="ENOENT"}function uh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
178
- `)}function PT(e,t){return D(`comet.native.snapshot-policy.v1
179
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function rh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function RT(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function ly(e){let t=$c(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?RT(n):void 0;if(a&&!a())return!1;let o=rh(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=rh(i,c,a),o===null||o.size===0)return!1}return rh(i,o,a)?.has(i.length)??!1}}function Sy(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>$c(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>$c(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=PT(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(ly),excludeMatchers:i.map(ly),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function xT(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function uy(e,t,i){if(!e)return!0;let r=()=>F(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function To(e,t,i){let r=JSON.stringify(i);return D(`${e}
174
+ `}function vT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Pt.join(e.transactionsDir,t)}function ul(e,t){let i=vT(e,t);return{directory:i,journal:Pt.join(i,"transaction.json"),events:Pt.join(i,"events.jsonl"),staged:Pt.join(i,"staged"),backups:Pt.join(i,"backups")}}async function si(e,t){let i=ul(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function gT(e,t){if(t.length===0||Pt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=Pt.resolve(n,...a.split(/[\\/]/u));if(!$(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function ur(e,t){let i=gT(e,t);return T(j(e,i),i)}async function Xr(e){try{return await Co.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uh(e,t,i={}){let r=await si(e,t);try{await Co.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ie({root:e.runtimeDir,file:r.events,maxBytes:cT,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=yy.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=mT(a),s=by(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function py(e,t,i){let r=await uh(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Rt(e,t,i,r){let n=await si(e,t),a=await uh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await ue(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>py(e,t,a)}),o;if(a.events.length>=sl)throw new Error(`Native transaction event log ${t} exceeds ${sl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return Ny(s,s.sequence),await Co.mkdir(n.directory,{recursive:!0}),await ue(n.events,by([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>py(e,t,a)}),s}async function ky(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=lh(t);let i=await si(e,t.id);await Co.mkdir(i.staged,{recursive:!0}),await Co.mkdir(i.backups,{recursive:!0}),await te(i.journal,t,{containedRoot:e.runtimeDir}),await Rt(e,t.id,"prepared")}async function mt(e,t,i={}){let r=await si(e,t),n=await ie({root:e.runtimeDir,file:r.journal,maxBytes:sT,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(yy.decode(n.bytes)),o=lh(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function dr(e,t,i={}){return(await uh(e,t,i)).events}async function cl(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=lh({...t,status:i});return await te((await si(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function sh(e,t,i){try{return await ie({root:j(e,t),file:t,maxBytes:ch,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function dh(e,t,i,r){let n=await sh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await sh(e,i,`${r} target`);await oi({root:j(e,i),directory:Pt.dirname(i),label:`${r} target parent`}),await lr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:ch,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function Sy(e,t,i){let r=await sh(e,t,i);r&&await al({root:j(e,t),file:t,maxBytes:ch,expectedHash:r.hash,expectedSize:r.size,label:i})}async function my(e,t){if(!t.backup)return;let i=await ur(e,t.target),r=await ur(e,t.backup);!await Xr(i)||await Xr(r)||await dh(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function wT(e,t){let i=await ur(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await my(e,t),await dh(e,await ur(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await my(e,t),await Sy(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await ur(e,t.source),[n,a]=await Promise.all([Xr(r),Xr(i)]);if(!n&&a){await(await pt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:lT})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await ah({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function Ey(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await cl(e,t,"applying"):t,n=await dr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Rt(e,r.id,"operation-started",s.id),await wT(e,s),await Rt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await mt(e,r.id),r}async function yT(e,t){let i=await ur(e,t.target),r=t.backup?await ur(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await ur(e,t.source);if(await Xr(i)){if(await Xr(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await ah({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await Xr(r)?await dh(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await Sy(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function dl(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await dr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await cl(e,t,"rolling-back");await Rt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await yT(e,a);return await Rt(e,r.id,"rollback-completed"),r=await cl(e,r,"rolled-back"),r}async function Jn(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Rt(e,t.id,i),i==="commit"?cl(e,t,"committed"):t}async function kT(e,t,i){let r;try{r=await NT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await mt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(Yr(n.name))try{let a=await xo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(ly(a))return!0}catch{return!0}return!1}async function ST(e,t){let i=Date.now()+5e3,r=bT.join(e.locksDir,"root-move.lock");for(;;)try{return await ir(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await ko(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function he(e,t,i,r){let n=await ST(e,t);try{if(await On(e.projectRoot),await kT(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await rr(n)}}function Py(e){return Number.isSafeInteger(e)&&e>=1}async function Ry(e){if(!Py(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!Py(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as vl}from"crypto";import{spawn as Hy}from"node:child_process";import{promises as oe}from"fs";import q from"path";import{createHash as xy}from"crypto";import{createReadStream as ET}from"fs";async function Gt(e){let t=xy("sha256");for await(let i of ET(e))t.update(i);return t.digest("hex")}function F(e){return xy("sha256").update(e).digest("hex")}var fl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},gh=1e3,PT=8*1024*1024,RT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xT=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),CT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),AT=new Set(["schema","include","exclude","hash"]),_T=new Set(["provider","gitSelection","physicalSelection","projection"]),TT=new Set(["provider","selection"]),IT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),jT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),$T=new Set(["schema","status","before","after"]),OT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),HT=new Set(["path","hash","size","type","gitObjectId"]),DT=new Set(["path","size","type","reason"]),MT=new Set(["ref","hash","count"]),FT=new Set(["change-created","legacy-migration","explicit"]),LT=new Set(["file","directory","other"]),BT=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"]),gl=/^[a-f0-9]{64}$/u,Dy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,qT=new Set(["EACCES","EPERM"]),Xn=64*1024,mh=64*1024,VT=6e4,WT=1e3,zT=2,wh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},JT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function My(e){let t=e.deadlineMs??VT;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Ut(e){return Math.max(0,e.deadlineAt-Date.now())}function L(e){return Ut(e)>=1}function fh(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 Kn(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function GT(e){let t={...JT,...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 UT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&q.win32.isAbsolute(r)?q.win32.resolve(r):"C:\\Windows",a=q.win32.join(n,"System32","taskkill.exe");if(!q.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=Hy(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),WT),u.unref()}catch{d(!1)}});for(let s=0;s<zT;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function yh(e,t,i,r){let n=Ut(e);if(n<1)throw fh();let a=e.gitProcess,o=Hy(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=UT(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?fh(v.error):fh()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Fy(e){let t={...wh,...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 hl(e,t,i,r=mh){let{child:n,completion:a}=yh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=Xn)return;let v=Xn-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function hh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Io(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=yh(e,t,i,r.stdin!==void 0),c=[],l=vl("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,N=!1,y=!1,E=S=>{let k=0;for(;k<S.byteLength;){let b=S.indexOf(0,k),R=b<0?S.byteLength:b,w=S.subarray(k,R);if(!m&&w.byteLength>0&&(h.byteLength+w.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,N=!0):h=Buffer.concat([h,w])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let g=h.byteLength+1;!m&&v<=r.maxRecords&&p+g<=r.maxBytes?(c.push(h),p+=g):N=!0,h=Buffer.alloc(0),m=!1,k=b+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>r.maxBytes&&(N=!0);let k=r.outputChunkBytes;if(k===void 0){E(S);return}for(let b=0;b<S.byteLength;b+=k)E(S.subarray(b,Math.min(S.byteLength,b+k)))}),o.stderr.on("data",S=>{if(d>=Xn)return;let k=Xn-d,b=Buffer.from(S).subarray(0,k);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:k})=>{let b=r.acceptedExitCodes??[0];if(S!==null&&b.includes(S)&&k===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:N,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function pl(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 KT(e,t,i){if(i.length===0)return new Set;let r=await Io(e,t,["check-ignore","--no-index","-z","--stdin"],{...wh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=pl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function YT(e,t,i){let{child:r,completion:n}=yh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=Xn)return;let d=Xn-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Yn(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||q.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||q.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function XT(e,t){return e.map(i=>{let r=Yn(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function QT(e){let t=q.resolve(e);for(;;){try{return await oe.lstat(q.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=q.dirname(t);if(i===t)return!1;t=i}}async function Ly(e,t,i,r={}){let n=q.resolve(t.projectRoot),a=q.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=q.relative(n,q.resolve(f)).replaceAll("\\","/"),v=Yn(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Io(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Io(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Io(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function By(e){return{stageBefore:hh(e.stagedBefore),combined:hh(e.combined),stageAfter:hh(e.stagedAfter)}}async function qy(e,t,i=wh,r={}){let n=q.resolve(t.projectRoot);if(!await QT(n))return null;let a;try{a=await hl(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw Kn(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Ly(e,t,i,r)}catch(y){throw Kn(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let E of y){let S=pl(E),k=S.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(S.slice(0,k))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Yn(S.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),b.stage==="0"&&d.set(R,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(R)}};p(s.records),p(l.records);let v=c.records.map(pl),h=XT(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),N=new Set(h.filter((y,E)=>!u.has(y)&&v[E].endsWith("/")));for(let y of f)N.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:N,omissions:[],overflow:null,evidence:null,initialFence:By(o)}}function hr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Cy(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function ZT(e,t){return!hr(e.stageBefore,e.stageAfter)||!hr(e.stageAfter,t.stageBefore)||!hr(e.combined,t.combined)||!hr(t.stageBefore,t.stageAfter)}async function Vy(e,t,i,r,n){let a;try{a=await Ly(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Kn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=By(a),c=Cy(o)||Cy(s),l=ZT(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:F(`comet.native.git-selection-overflow.v2
175
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var eI=(1n<<256n)-1n;function tI(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Ay(e){let t=q.resolve(e.paths.projectRoot),i=q.resolve(e.paths.nativeRoot),r=q.resolve(e.paths.runtimeDir),n=q.resolve(e.paths.configFile),a=q.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>Ut(e.execution)>=1?!0:(p=!0,h=!0,!1),N=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),b=vl("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=b[R];if(l=l+BigInt(`0x${b.toString("hex")}`)&eI,d+=1,f+=k.byteLength,Buffer.byteLength(S.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(S)},y=async S=>{if(h||!m())return;let k;try{k=await oe.opendir(S)}catch(P){if(!m())return;if(!ke(P)&&!be(P)||S===t&&ke(P))throw P;v||=be(P),p||=ke(P),h=!0;return}if(!m()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let b=!1,R;try{for(;!h&&m();){let P;try{P=await k.read()}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z)||S===t&&ke(Z))throw Z;v||=be(Z),p||=ke(Z),h=!0;break}if(!m()||P===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let D=q.join(S,P.name),O=rI(t,D);if(D===n||D===a||Kt(i,D)||Kt(r,D)||e.denylist.some(Z=>Kt(Z,D))||ii(O)!==null)continue;if(!m())break;let De;try{De=await oe.lstat(D)}catch(Z){if(!m())break;if(!ke(Z)&&!be(Z))throw Z;if(v=!0,N({path:O,type:"other"}),s.push({path:O,size:null,type:"file",reason:ke(Z)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;let ce=tI(De);if(ce==="directory"){if(sI(e.policy,O))continue;if(!m())break;let Z;try{Z=await oe.realpath(D)}catch(Zt){if(!m())break;if(!ke(Zt)&&!be(Zt))throw Zt;if(v=!0,N({path:O,type:ce}),s.push({path:O,size:null,type:"directory",reason:ke(Zt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(O),h||!m())break;continue}if(!m())break;if(!$(e.physicalProjectRoot,Z)||Kt(e.physicalNativeRoot,Z))continue;if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||(await y(D),h))break;continue}if(N({path:O,type:ce}),await e.hooks?.afterNode?.(O),!m()||h)break}}catch(P){b=!0,R=P}let w;try{await k.close()}catch(P){w=P}let g=m();if(b)throw R;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((S,k)=>S.path.localeCompare(k.path,"en")),s.sort((S,k)=>S.path.localeCompare(k.path,"en")));let E=p?F(`comet.native.physical-selection-incomplete.v1
176
+ ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):F(`comet.native.physical-selection.v1
177
+ ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function Wy(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 iI(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!Wy(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function zy(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function _y(e,t){let r=(await hl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Dy.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${r}`)}async function Ty(e,t){let i=await _y(e,t),r=await YT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await _y(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function To(e,t){if(ii(t)!==null)return!1;let i=q.resolve(e.projectRoot,...t.split("/"));return!Kt(q.resolve(e.nativeRoot),i)&&!Kt(q.resolve(e.runtimeDir),i)}function Nh(e,t={}){let i=Pi(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function rI(e,t){return q.relative(e,t).split(q.sep).join("/")}function nI(e,t){return t.map(i=>q.resolve(e,...i.split(/[\\/]/u)))}function Kt(e,t){let i=q.resolve(e),r=q.resolve(t);return r===i||$(i,r)}function ke(e){return qT.has(e.code??"")}function be(e){return e.code==="ENOENT"}function bh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
178
+ `)}function aI(e,t){return F(`comet.native.snapshot-policy.v1
179
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function ph(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function oI(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Iy(e){let t=Lc(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?oI(n):void 0;if(a&&!a())return!1;let o=ph(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=ph(i,c,a),o===null||o.size===0)return!1}return ph(i,o,a)?.has(i.length)??!1}}function Jy(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Lc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>Lc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=aI(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(Iy),excludeMatchers:i.map(Iy),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function sI(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function jy(e,t,i){if(!e)return!0;let r=()=>L(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function jo(e,t,i){let r=JSON.stringify(i);return F(`${e}
180
180
  ${Buffer.byteLength(t)}:${t}
181
- ${Buffer.byteLength(r)}:${r}`)}function ah(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ll(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!ah(i))return e.splice(t,1),i}return null}function lr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function CT(e,t,i,r){if(!F(r))return{status:"budget-exhausted"};let n;try{n=await oe.open(e,"r")}catch(c){if(!F(r))return{status:"budget-exhausted"};throw c}if(!F(r))return await n.close(),{status:"budget-exhausted"};let a=ul("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!F(r))return{status:"budget-exhausted"};let c=await n.stat();if(!F(r))return{status:"budget-exhausted"};if(!c.isFile()||!lr(i,c))return{status:"changed"};for(;;){if(!F(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!F(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!F(r))return{status:"budget-exhausted"};let d=await n.stat();return F(r)?!d.isFile()||!lr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ct(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function qn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function si(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Ey(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=B.posix.normalize(e);if(i!==e||B.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function AT(e,t){let i=xt(e,`Native snapshot entry ${t}`);Ct(i,iT,`Native snapshot entry ${t}`);let r=Ey(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!dl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:si(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!py.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function _T(e,t){let i=xt(e,`Native snapshot omission ${t}`);if(Ct(i,rT,`Native snapshot omission ${t}`),!oT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!sT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Ey(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:si(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function TT(e){let t=xt(e,"Native snapshot omission overflow");if(Ct(t,nT,"Native snapshot omission overflow"),typeof t.hash!="string"||!dl.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:qn(t.count,"Native snapshot omission overflow count")}}function Bn(e,t){let i=xt(e,t);if(Ct(i,Z_,t),typeof i.hash!="string"||!dl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=si(i.recordCount,`${t} recordCount`),n=si(i.storedRecordCount,`${t} storedRecordCount`),a=si(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function dy(e){let t=xt(e,"Native Git selection evidence");if(Ct(t,Q_,"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=Bn(t.stageBefore,"Native Git selection stageBefore"),r=Bn(t.combined,"Native Git selection combined"),n=Bn(t.stageAfter,"Native Git selection stageAfter"),a=Bn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Bn(t.finalCombined,"Native Git selection finalCombined"),s=Bn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!ur(i,n)||!ur(n,a)||!ur(r,o)||!ur(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function fy(e,t){let i=xt(e,t);if(Ct(i,tT,t),typeof i.hash!="string"||!dl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=si(i.visitedNodeCount,`${t} visitedNodeCount`),n=si(i.recordCount,`${t} recordCount`),a=si(i.storedRecordCount,`${t} storedRecordCount`),o=si(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function IT(e){let t=xt(e,"Native physical selection evidence");if(Ct(t,eT,"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=fy(t.before,"Native physical selection before"),r=fy(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!by(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Si(e){let t=xt(e,"Native content snapshot manifest");if(Ct(t,G_,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!aT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let N=xt(t.capture,"Native content snapshot capture");if(Ct(N,Y_,"Native content snapshot capture"),N.provider!=="git"&&N.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=N.gitSelection===void 0?void 0:dy(N.gitSelection),w=N.physicalSelection===void 0?void 0:IT(N.physicalSelection),g=null;if(N.projection!==void 0){let E=xt(N.projection,"Native content snapshot projection");if(Ct(E,X_,"Native content snapshot projection"),E.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...E.selection===void 0?{}:{selection:dy(E.selection)}}}if(N.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&g)throw new Error("Native physical-tree capture cannot combine selection and projection");i=g?{provider:"physical-tree",projection:g}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=xt(t.limits,"Native content snapshot limits");Ct(r,U_,"Native content snapshot limits");let n={maxFiles:qn(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:qn(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:qn(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:qn(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:qn(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let N=xt(t.policy,"Native snapshot policy");if(Ct(N,K_,"Native snapshot policy"),N.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(N.include)||!Array.isArray(N.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Sy({include:N.include,exclude:N.exclude,hash:N.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(AT),s=t.omitted.map(_T),c=si(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:TT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(N=>N.size>n.maxFileBytes)||o.reduce((N,R)=>N+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(N=>N.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>oh||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(N=>N.reason==="git-enumeration-limit"),f=s.filter(N=>N.reason==="git-selection-changed");for(let N of[...d,...f])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(N=>N.reason==="physical-enumeration-limit"),b=s.filter(N=>N.reason==="physical-selection-changed");for(let N of[...m,...b])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,P=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(P!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(uh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function fl(e,t,i={}){let r=Si(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=B.resolve(e.projectRoot),a=my(i),o=vy(i.gitSelectionLimits),s=await yy(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(ky(s).filter(w=>Ao(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>Ao(e,w)),d=(w,g)=>g.some(E=>w===E||w.startsWith(`${E}/`)),f=w=>d(w,l),h=w=>d(w,u),v=[...r.entries.map(w=>w.path),...r.omitted.flatMap(w=>w.type==="directory"?[w.path,`${w.path}/`]:[w.path])].filter(w=>!c.has(w)&&!f(w)&&!h(w)),p=await mT(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!h(w.path)&&Ao(e,w.path)&&(c.has(w.path)||!p.has(w.path)));await Ny(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let w of l)b.push({path:w,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((w,g)=>w.path.localeCompare(g.path,"en"));let y=r.omitted.filter(w=>f(w.path)||h(w.path)||!Ao(e,w.path)?!1:p.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of b)y.some(g=>g.path===w.path&&g.reason===w.reason)||y.push(w);y.sort((w,g)=>w.path.localeCompare(g.path,"en"));let P=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??D("comet.native.snapshot-omission-overflow.v1");s.overflow&&(P+=s.overflow.count,S=To(S,"git-selection",{source:"git-selection",...s.overflow}));let k=w=>{P+=1,S=To(S,"omission",w)};for(;y.length>oh;){let w=ll(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(w)}let N=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+P===0,entries:m,omitted:y,omittedCount:y.length+P,...P>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:P}}:{}}),R=N();for(;uh(R)>r.limits.maxManifestBytes;){let w=ll(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(w),R=N()}return Si(R)}function Py(e,t){if(!J_.test(t))throw new Error(`Invalid Native change name: ${t}`);return B.join(H(e,t),"baseline-manifest.json")}async function hl(e,t={}){let i={maxFiles:t.limits?.maxFiles??ol.maxFiles,maxFileBytes:t.limits?.maxFileBytes??ol.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??ol.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??ol.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Sy(t.policy),n=my({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=vy(t.gitSelectionLimits),o=hT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=B.resolve(e.projectRoot),c=await oe.realpath(s),l=B.resolve(e.nativeRoot),u=await oe.realpath(l),d=B.resolve(e.runtimeDir),f=B.resolve(e.configFile),h=B.join(s,".comet","current-change.json"),v=ET(s,t.denylist??[]),p=[],m=[],b=new Map,y=new Map,P=0,S=0,k=D("comet.native.snapshot-omission-overflow.v1"),N=0,R=!1,w=null,g=_=>{S+=1,k=To(k,"omission",_)},E=_=>{if(P+=1,m.length<oh){m.push(_);return}if(ah(_)){let A=ll(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),m.push(_);return}g(_)},q=_=>{P+=_.count,S+=_.count,k=To(k,"git-selection",{source:"git-selection",..._})},O=_=>{S+=1,k=To(k,"manifest-entry",{reason:"manifest-size",entry:_})},He=async(_,A)=>{p.push(_),N+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ce=(_,A)=>{let I=p.findIndex(ae=>ae.path===_);if(I<0)return;let[V]=p.splice(I,1);N-=V.size,b.delete(_),E(A)},Q=async(_,A,I,V)=>{if(!I.isFile()||I.isSymbolicLink()||!F(n))return;let ae;try{ae=await oe.realpath(_)}catch(C){if(!F(n))return;if(!be(C)&&!Ne(C))throw C;E({path:A,size:I.size,type:"file",reason:Ne(C)?"changed-during-read":"unreadable"});return}if(!F(n)||!$(c,ae)||Gt(u,ae))return;if(p.length>=i.maxFiles){E({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){E({path:A,size:I.size,type:"file",reason:"file-size"});return}if(N+I.size>i.maxTotalBytes){E({path:A,size:I.size,type:"file",reason:"total-size"});return}let G,M,pe;try{if(G=await CT(ae,I.size,I,n),G.status==="budget-exhausted"||!F(n))return;if(G.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!F(n)||(pe=await oe.realpath(_),!F(n)))return;M=await oe.lstat(_)}catch(C){if(!F(n))return;if(!be(C)&&!Ne(C))throw C;E({path:A,size:I.size,type:"file",reason:Ne(C)?"changed-during-read":"unreadable"});return}if(F(n)){if(G.bytes!==I.size||pe!==ae||!lr(I,G.finalStat)||!lr(G.finalStat,M)||!M.isFile()||M.isSymbolicLink()||M.size!==I.size||M.mtimeMs!==I.mtimeMs||M.ctimeMs!==I.ctimeMs){E({path:A,size:M.isFile()?M.size:null,type:M.isFile()?"file":"other",reason:"changed-during-read"});return}F(n)&&await He({path:A,hash:G.hash,size:M.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:ae,stat:M})}},Qt=async(_,A,I)=>{if(!F(n))return;let V,ae,G;try{if(V=await oe.readlink(_,{encoding:"buffer"}),!F(n)||(G=await oe.lstat(_),!F(n)))return;ae=await oe.readlink(_,{encoding:"buffer"})}catch(C){if(!F(n))return;if(!be(C)&&!Ne(C))throw C;E({path:A,size:null,type:"other",reason:Ne(C)?"changed-during-read":"unreadable"});return}if(!F(n))return;if(!G.isSymbolicLink()||!lr(I,G)||G.mtimeMs!==I.mtimeMs||G.ctimeMs!==I.ctimeMs||!V.equals(ae)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let M=V.byteLength;if(p.length>=i.maxFiles){E({path:A,size:M,type:"other",reason:"file-count"});return}if(M>i.maxFileBytes){E({path:A,size:M,type:"other",reason:"file-size"});return}if(N+M>i.maxTotalBytes){E({path:A,size:M,type:"other",reason:"total-size"});return}let pe=ul("sha256").update("symlink\0").update(V).digest("hex");F(n)&&await He({path:A,hash:pe,size:M,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:G})},Ot=async()=>{for(let[_,A]of[...b]){if(!F(n))return;if(A.kind==="file"){let M,pe;try{if(M=await oe.realpath(A.target),!F(n))return;pe=await oe.lstat(A.target)}catch(C){if(!F(n))return;if(!be(C)&&!Ne(C))throw C;ce(_,{path:_,size:null,type:"file",reason:be(C)?"unreadable":"changed-during-read"});continue}if(!F(n))return;(M!==A.realTarget||!pe.isFile()||pe.isSymbolicLink()||!lr(A.stat,pe)||pe.size!==A.stat.size||pe.mtimeMs!==A.stat.mtimeMs||pe.ctimeMs!==A.stat.ctimeMs)&&ce(_,{path:_,size:pe.isFile()?pe.size:null,type:pe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let M,pe;try{if(M=await oe.lstat(A.target),!F(n))return;pe=await oe.readlink(A.target,{encoding:"buffer"})}catch(C){if(!F(n))return;if(!be(C)&&!Ne(C))throw C;ce(_,{path:_,size:null,type:"other",reason:be(C)?"unreadable":"changed-during-read"});continue}if(!F(n))return;(!M.isSymbolicLink()||!lr(A.stat,M)||M.mtimeMs!==A.stat.mtimeMs||M.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(pe))&&ce(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,V;try{if(I=await oe.realpath(A.target),!F(n))return;V=await oe.lstat(A.target)}catch{if(!F(n))return;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!F(n))return;if(!(I===A.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&lr(A.stat,V)&&$(c,I)&&!Gt(u,I))){ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let G;try{if(!F(n))return;G=await cy(n,I)}catch(M){if(Vn(M))throw M;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!F(n))return;G.dirty?ce(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):G.hash!==A.hash&&ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!F(n))return;try{let I=await oe.lstat(A);if(!F(n))return;E({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!F(n))return;if(Ne(I))continue;if(!be(I))throw I;E({path:_,size:null,type:"file",reason:"unreadable"})}}},lt=await yy(n,e,a,t.gitSelectionHooks);if(lt===null){let _=await oy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||b.has(V.path))continue;if(Jt(n)<1)break;if(!uy(r,V.path,n))continue;if(Jt(n)<1)break;let ae=B.resolve(s,...V.path.split("/")),G;try{G=await oe.lstat(ae)}catch(M){if(!F(n))break;if(!be(M)&&!Ne(M))throw M;E({path:V.path,size:null,type:"file",reason:Ne(M)?"changed-during-read":"unreadable"});continue}if(Jt(n)<1)break;if(V.type==="symlink"&&G.isSymbolicLink()){if(await Qt(ae,V.path,G),Jt(n)<1)break;continue}if(V.type!=="file"||!G.isFile()||G.isSymbolicLink()){E({path:V.path,size:G.isFile()?G.size:null,type:G.isDirectory()?"directory":G.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Q(ae,V.path,G),Jt(n)<1)break}Jt(n)>=1&&await Ot();let A=await oy({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=kT(_.evidence,A.evidence);w=I.evidence;for(let V of[..._.omissions,...A.omissions,...I.omissions])m.some(ae=>ae.path===V.path&&ae.reason===V.reason)||E(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let C=Si(_);for(let le of C.entries)le.gitObjectId!==void 0&&A.set(le.path,le);I=A.size>0}let V=new Set,ae=!0;try{let C=await _o(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(C.overflow)I=!1,ae=!1,A.clear();else for(let le of C.records){let me=cl(le),Je=me.indexOf(" "),De=Je<0?null:Wn(me.slice(Je+1));if(Je!==1||De===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");me[0]!=="H"&&V.add(De)}}catch(C){if(Vn(C))throw C;I=!1,ae=!1,A.clear()}let G=new Set;try{let C=await sl(n,s,["ls-files","--modified","-z"],nh);for(let le of C.toString("utf8").split("\0")){let me=Wn(le);me!==null&&G.add(me)}}catch{I=!1,ae=!1,A.clear()}let M=new Set,pe=new Set;for(let C of ky(lt)){if(b.has(C)||!Ao(e,C))continue;if(Jt(n)<1)break;if(!uy(r,C,n))continue;if(Jt(n)<1)break;let le=B.resolve(s,...C.split("/"));if(le===f||le===h||Gt(d,le)||v.some(ut=>Gt(ut,le)))continue;if(lt.gitlinks.has(C)){if(p.length>=i.maxFiles){E({path:C,size:0,type:"file",reason:"file-count"});continue}let ut,bs;try{[ut,bs]=await Promise.all([oe.realpath(le),oe.lstat(le)])}catch{E({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(bs.isSymbolicLink()||!bs.isDirectory()||!$(c,ut)||Gt(u,ut)){E({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let dn=await cy(n,ut);if(dn.dirty){E({path:C,size:null,type:"directory",reason:"gitlink-dirty"});continue}await He({path:C,hash:dn.hash,size:0,type:"file"},{kind:"gitlink",target:le,realTarget:ut,stat:bs,hash:dn.hash})}catch(dn){if(Vn(dn))throw dn;E({path:C,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let me;try{me=await oe.lstat(le)}catch(ut){if(Ne(ut)&&lt.tracked.has(C)){y.set(C,le);continue}if(!be(ut)&&!Ne(ut))throw ut;E({path:C,size:null,type:"file",reason:Ne(ut)?"changed-during-read":"unreadable"});continue}if(me.isSymbolicLink()){await Qt(le,C,me);continue}if(!me.isFile()){lt.nestedRepositories.has(C)||E({path:C,size:null,type:"other",reason:"changed-during-read"});continue}let Je=lt.trackedObjectIds.get(C),De=Je?A.get(C):void 0;if(I&&De?.gitObjectId!==void 0&&De.gitObjectId===Je&&!V.has(C)&&!G.has(C)){if(p.length>=i.maxFiles){E({path:C,size:De.size,type:"file",reason:"file-count"});continue}if(De.size>i.maxFileBytes){E({path:C,size:De.size,type:"file",reason:"file-size"});continue}if(N+De.size>i.maxTotalBytes){E({path:C,size:De.size,type:"file",reason:"total-size"});continue}p.push({...De}),N+=De.size,M.add(C);continue}let Kp=ae&&!V.has(C)&&!G.has(C)?Je:void 0;await Q(le,C,me,Kp),Kp!==void 0&&pe.add(C)}if(await Ot(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Ny(n,e,a,lt,t.gitSelectionHooks?.outputChunkBytes),M.size>0||I&&pe.size>0){let C=await sl(n,s,["ls-files","--modified","-z"],nh),le=new Set;for(let me of C.toString("utf8").split("\0")){let Je=Wn(me);Je!==null&&le.add(Je)}for(let me of M){if(!le.has(me))continue;let Je=p.find(De=>De.path===me);ce(me,{path:me,size:Je?.size??null,type:"file",reason:"changed-during-read"})}for(let me of pe){if(!le.has(me))continue;let Je=p.find(De=>De.path===me);Je&&delete Je.gitObjectId}}for(let C of lt.omissions)E(C);lt.overflow&&q(lt.overflow)}p.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let RS=lt===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...lt.evidence?{gitSelection:lt.evidence}:{}},Up=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:RS,createdAt:(t.now??new Date).toISOString(),complete:P===0,limits:i,...r?{policy:r.manifest}:{},entries:p,omitted:m,omittedCount:P,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),Tu=Up();for(;uh(Tu)>i.maxManifestBytes;){if(m.filter(A=>!ah(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let V=ll(m);if(V===null)break;g(V)}}else if(p.length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I of p.splice(-A))P+=1,O(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Tu=Up()}return Tu}async function dh(e,t,i={}){let n=(await Pe(e.projectRoot))?.native.snapshot??Tf;return hl(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function fh(e,t,i){let r=Py(e,t);await T(j(e,r),r),await te(r,Si(i))}async function Jn(e,t){let i=Py(e,t),r=j(e,i);await T(r,i);try{let n=await Qc({root:r,file:i,maxBytes:z_,label:"Native baseline snapshot manifest"});return Si(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as YT}from"crypto";import XT from"path";var pt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as WT}from"node:crypto";import{constants as ml,promises as Ue}from"node:fs";import mt from"node:path";import{TextDecoder as zT}from"node:util";import LT from"path";var FT=xa(Sn(),1);var UB=4*1024*1024;var Ry=(e,t)=>{let i=e[t];return i==null?null:String(i)};function jo(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 Io(e,t){let i=jo(e,t);if(LT.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 BT(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function xy(e){if(!e.run_id)return null;let t=jo(e,"run_id"),i=jo(e,"skill"),r=jo(e,"skill_version"),n=jo(e,"skill_hash"),a=Io(e,"pending_ref"),o=Io(e,"trajectory_ref"),s=Io(e,"context_ref"),c=Io(e,"artifacts_ref"),l=Io(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Ry(e,"current_step"),iteration:u,pending:Ry(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:BT(e)}}var B1=256*1024;var qT=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function VT(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=xy(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function pl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!qT.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return VT(t)}var qe={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 Oo(e,t){let i=mt.relative(e,t);return i===""||!mt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${mt.sep}`)}function Ay(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function $o(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function JT(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dr(e,t,i){let r=pt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=mt.resolve(e),a=mt.resolve(n,...r.slice(8).split("/"));if(!Oo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Cy(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 hh(e,t){let i=mt.resolve(e),r=mt.resolve(t);if(!Oo(i,r))throw new Error("Native Run path is outside its change");let n=[await Cy(i)],a=i;for(let o of mt.relative(i,r).split(mt.sep).filter(Boolean)){a=mt.join(a,o);let s;try{s=await Cy(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Oo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function vl(e){for(let t of e){let i=await Ue.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!JT(t,i)||await Ue.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function GT(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Kr(e,t,i,r,n){let a=await hh(e,mt.dirname(t));if(!a)return null;await n?.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(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Ay(o),c=await Ue.realpath(t);if(!Oo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?ml.O_RDONLY:ml.O_RDONLY|ml.O_NOFOLLOW|ml.O_NONBLOCK,u;try{u=await Ue.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),Ue.lstat(t),Ue.realpath(t)]);if(await vl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!$o(s,d)||!$o(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await GT(u,i,r);await n?.beforeFinalCheck?.();let[p,m,b]=await Promise.all([u.stat(),Ue.lstat(t),Ue.realpath(t)]);if(await vl(a),!m.isFile()||m.isSymbolicLink()||b!==c||!$o(s,p)||!$o(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new zT("utf-8",{fatal:!0}).decode(v)}catch(P){throw new Error(`${r} is not valid UTF-8`,{cause:P})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function UT(e,t,i){let r=await hh(e,mt.dirname(t));if(!r)return{exists:!1};let n;try{n=await Ue.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Ue.realpath(t);if(!Oo(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await vl(r),{exists:!0,identity:Ay(n),realPath:a}}async function KT(e,t,i,r){let n=await hh(e,mt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await Ue.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!$o(i.identity,a)||await Ue.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await vl(n)}async function gl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await UT(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ue(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await KT(e.changeDir,e.file,i,e.label)}});let r=await Kr(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function _y(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function Ty(e){return`${JSON.stringify(e,null,2)}
182
- `}function fr(e){return pl(e)}async function Te(e,t){let i=dr(e,"stateRef"),r=await Kr(e,i,qe.runStateBytes,"Native Run state",t);return r?pl(_y(r.text,"Native Run state")):null}async function Yr(e,t,i){let r=pl(t);await gl({changeDir:e,file:dr(e,"stateRef"),content:Ty(r),maxBytes:qe.runStateBytes,label:"Native Run state",hooks:i})}async function Ke(e,t,i){let r=dr(e,"trajectoryRef",t),n=await Kr(e,r,qe.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>qe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${qe.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 Iy(e,t,i){return(await Kr(e,dr(e,"trajectoryRef",t),qe.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function jy(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=dr(e,"trajectoryRef",t),o=await Kr(e,a,qe.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(WT("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await gl({changeDir:e,file:a,content:i,maxBytes:qe.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function $y(e,t,i,r){let n=dr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
183
- `;if(Buffer.byteLength(a,"utf8")>qe.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${qe.trajectoryEventBytes} bytes`);let o=await Kr(e,n,qe.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=qe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${qe.trajectoryEvents} events`);await gl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:qe.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Gn(e,t,i){let r=await Kr(e,dr(e,"checkpointRef",t),qe.checkpointBytes,"Native Run checkpoint",i);return r?_y(r.text,"Native Run checkpoint"):null}async function Oy(e,t,i,r){await gl({changeDir:e,file:dr(e,"checkpointRef",t),content:Ty(i),maxBytes:qe.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var QT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wl=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 ph(e){return YT("sha256").update(e).digest("hex")}function ZT(e,t){if(!QT.test(t))throw new Error(`Invalid Native change name: ${t}`);return XT.join(H(e,t),"trajectory.jsonl")}function eI(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function tI(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 iI(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=eI(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
184
- `)])}catch(d){if(!tI(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:ph(t),targetHash:ph(l),tailHash:ph(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Hy(e,t){let i=ZT(e,t);await T(j(e,i),i);let r=H(e,t),n=await Iy(r,pt.trajectoryRef);return n===null?{status:"clean",file:i}:iI(i,Buffer.from(n))}async function Un(e,t){let i=await Hy(e,t);return"inspection"in i?i.inspection:i}async function yl(e,t){let i=await Un(e,t);if(i.status!=="clean")throw new wl(i)}async function Dy(e,t,i){return he(e,`repair trajectory tail for ${t}`,async()=>{let r=await Hy(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new wl(r)}try{await jy(H(e,t),pt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await Un(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as nI}from"node:crypto";import{promises as Nl}from"node:fs";import Ei from"node:path";var Ho=/^[a-f0-9]{64}$/u,Fy=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,aI=16*1024,vh=process.platform,oI=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Kn(e){return oI.has(e)}function By(e,t){let i=Ei.relative(e,t);return Ei.isAbsolute(i)||i===".."||i.startsWith(`..${Ei.sep}`)?null:i.replaceAll("\\","/")||"."}function qy(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Vy(e,t){if(e.length===0||qy(e)||e.includes("\\")||Ei.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=Ei.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function gh(e,t){return nI("sha256").update(`${e}
185
- ${t}`).digest("hex")}async function My(e,t){let i=await Nl.realpath(t),r=await Nl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=vh==="win32"?Ei.normalize(i).toLowerCase():i;return gh(e,`${n}
181
+ ${Buffer.byteLength(r)}:${r}`)}function vh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ml(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!vh(i))return e.splice(t,1),i}return null}function fr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ht(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cI(e,t,i,r){if(!L(r))return{status:"budget-exhausted"};let n;try{n=await oe.open(e,"r")}catch(c){if(!L(r))return{status:"budget-exhausted"};throw c}if(!L(r))return await n.close(),{status:"budget-exhausted"};let a=vl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!L(r))return{status:"budget-exhausted"};let c=await n.stat();if(!L(r))return{status:"budget-exhausted"};if(!c.isFile()||!fr(i,c))return{status:"changed"};for(;;){if(!L(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!L(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!L(r))return{status:"budget-exhausted"};let d=await n.stat();return L(r)?!d.isFile()||!fr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ct(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function Un(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ci(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Gy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=q.posix.normalize(e);if(i!==e||q.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function lI(e,t){let i=xt(e,`Native snapshot entry ${t}`);Ct(i,HT,`Native snapshot entry ${t}`);let r=Gy(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!gl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:ci(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Dy.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function uI(e,t){let i=xt(e,`Native snapshot omission ${t}`);if(Ct(i,DT,`Native snapshot omission ${t}`),!LT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!BT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Gy(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ci(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function dI(e){let t=xt(e,"Native snapshot omission overflow");if(Ct(t,MT,"Native snapshot omission overflow"),typeof t.hash!="string"||!gl.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:Un(t.count,"Native snapshot omission overflow count")}}function Gn(e,t){let i=xt(e,t);if(Ct(i,jT,t),typeof i.hash!="string"||!gl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=ci(i.recordCount,`${t} recordCount`),n=ci(i.storedRecordCount,`${t} storedRecordCount`),a=ci(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function $y(e){let t=xt(e,"Native Git selection evidence");if(Ct(t,IT,"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=Gn(t.stageBefore,"Native Git selection stageBefore"),r=Gn(t.combined,"Native Git selection combined"),n=Gn(t.stageAfter,"Native Git selection stageAfter"),a=Gn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Gn(t.finalCombined,"Native Git selection finalCombined"),s=Gn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!hr(i,n)||!hr(n,a)||!hr(r,o)||!hr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Oy(e,t){let i=xt(e,t);if(Ct(i,OT,t),typeof i.hash!="string"||!gl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=ci(i.visitedNodeCount,`${t} visitedNodeCount`),n=ci(i.recordCount,`${t} recordCount`),a=ci(i.storedRecordCount,`${t} storedRecordCount`),o=ci(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function fI(e){let t=xt(e,"Native physical selection evidence");if(Ct(t,$T,"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=Oy(t.before,"Native physical selection before"),r=Oy(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!Wy(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Pi(e){let t=xt(e,"Native content snapshot manifest");if(Ct(t,xT,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!FT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=xt(t.capture,"Native content snapshot capture");if(Ct(b,_T,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=b.gitSelection===void 0?void 0:$y(b.gitSelection),w=b.physicalSelection===void 0?void 0:fI(b.physicalSelection),g=null;if(b.projection!==void 0){let P=xt(b.projection,"Native content snapshot projection");if(Ct(P,TT,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");g={provider:"git",...P.selection===void 0?{}:{selection:$y(P.selection)}}}if(b.provider==="git"){if(w||g)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(w&&g)throw new Error("Native physical-tree capture cannot combine selection and projection");i=g?{provider:"physical-tree",projection:g}:{provider:"physical-tree",...w?{physicalSelection:w}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=xt(t.limits,"Native content snapshot limits");Ct(r,CT,"Native content snapshot limits");let n={maxFiles:Un(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Un(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Un(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Un(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:Un(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=xt(t.policy,"Native snapshot policy");if(Ct(b,AT,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Jy({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(lI),s=t.omitted.map(uI),c=ci(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:dI(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,R)=>b+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>gh||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),N=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...N])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,E=y?.status==="overflow"||y?.status==="overflow-and-changed",S=y?.status==="changed"||y?.status==="overflow-and-changed";if(E!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(N.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(bh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function wl(e,t,i={}){let r=Pi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=q.resolve(e.projectRoot),a=My(i),o=Fy(i.gitSelectionLimits),s=await qy(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(zy(s).filter(w=>To(e,w))),l=[...s.gitlinks].filter(w=>c.has(w)),u=[...s.nestedRepositories].filter(w=>To(e,w)),d=(w,g)=>g.some(P=>w===P||w.startsWith(`${P}/`)),f=w=>d(w,l),p=w=>d(w,u),v=[...r.entries.map(w=>w.path),...r.omitted.flatMap(w=>w.type==="directory"?[w.path,`${w.path}/`]:[w.path])].filter(w=>!c.has(w)&&!f(w)&&!p(w)),h=await KT(a,n,v),m=r.entries.filter(w=>!f(w.path)&&!p(w.path)&&To(e,w.path)&&(c.has(w.path)||!h.has(w.path)));await Vy(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let w of l)N.push({path:w,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((w,g)=>w.path.localeCompare(g.path,"en"));let y=r.omitted.filter(w=>f(w.path)||p(w.path)||!To(e,w.path)?!1:h.has(w.path)?c.has(w.path)||[...c].some(g=>g.startsWith(`${w.path}/`)):!0);for(let w of N)y.some(g=>g.path===w.path&&g.reason===w.reason)||y.push(w);y.sort((w,g)=>w.path.localeCompare(g.path,"en"));let E=r.omissionOverflow?.count??0,S=r.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,S=jo(S,"git-selection",{source:"git-selection",...s.overflow}));let k=w=>{E+=1,S=jo(S,"omission",w)};for(;y.length>gh;){let w=ml(y);if(w===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(w)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+E===0,entries:m,omitted:y,omittedCount:y.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:E}}:{}}),R=b();for(;bh(R)>r.limits.maxManifestBytes;){let w=ml(y);if(w===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(w),R=b()}return Pi(R)}function Uy(e,t){if(!RT.test(t))throw new Error(`Invalid Native change name: ${t}`);return q.join(H(e,t),"baseline-manifest.json")}async function yl(e,t={}){let i={maxFiles:t.limits?.maxFiles??fl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??fl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??fl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??fl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Jy(t.policy),n=My({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Fy(t.gitSelectionLimits),o=GT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=q.resolve(e.projectRoot),c=await oe.realpath(s),l=q.resolve(e.nativeRoot),u=await oe.realpath(l),d=q.resolve(e.runtimeDir),f=q.resolve(e.configFile),p=q.join(s,".comet","current-change.json"),v=nI(s,t.denylist??[]),h=[],m=[],N=new Map,y=new Map,E=0,S=0,k=F("comet.native.snapshot-omission-overflow.v1"),b=0,R=!1,w=null,g=_=>{S+=1,k=jo(k,"omission",_)},P=_=>{if(E+=1,m.length<gh){m.push(_);return}if(vh(_)){let A=ml(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),m.push(_);return}g(_)},D=_=>{E+=_.count,S+=_.count,k=jo(k,"git-selection",{source:"git-selection",..._})},O=_=>{S+=1,k=jo(k,"manifest-entry",{reason:"manifest-size",entry:_})},De=async(_,A)=>{h.push(_),b+=_.size,N.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ce=(_,A)=>{let I=h.findIndex(ae=>ae.path===_);if(I<0)return;let[V]=h.splice(I,1);b-=V.size,N.delete(_),P(A)},Z=async(_,A,I,V)=>{if(!I.isFile()||I.isSymbolicLink()||!L(n))return;let ae;try{ae=await oe.realpath(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n)||!$(c,ae)||Kt(u,ae))return;if(h.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let G,B,pe;try{if(G=await cI(ae,I.size,I,n),G.status==="budget-exhausted"||!L(n))return;if(G.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!L(n)||(pe=await oe.realpath(_),!L(n)))return;B=await oe.lstat(_)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:I.size,type:"file",reason:be(C)?"changed-during-read":"unreadable"});return}if(L(n)){if(G.bytes!==I.size||pe!==ae||!fr(I,G.finalStat)||!fr(G.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}L(n)&&await De({path:A,hash:G.hash,size:B.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:_,realTarget:ae,stat:B})}},Zt=async(_,A,I)=>{if(!L(n))return;let V,ae,G;try{if(V=await oe.readlink(_,{encoding:"buffer"}),!L(n)||(G=await oe.lstat(_),!L(n)))return;ae=await oe.readlink(_,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;P({path:A,size:null,type:"other",reason:be(C)?"changed-during-read":"unreadable"});return}if(!L(n))return;if(!G.isSymbolicLink()||!fr(I,G)||G.mtimeMs!==I.mtimeMs||G.ctimeMs!==I.ctimeMs||!V.equals(ae)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=V.byteLength;if(h.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(b+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let pe=vl("sha256").update("symlink\0").update(V).digest("hex");L(n)&&await De({path:A,hash:pe,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:V,stat:G})},Dt=async()=>{for(let[_,A]of[...N]){if(!L(n))return;if(A.kind==="file"){let B,pe;try{if(B=await oe.realpath(A.target),!L(n))return;pe=await oe.lstat(A.target)}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"file",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(B!==A.realTarget||!pe.isFile()||pe.isSymbolicLink()||!fr(A.stat,pe)||pe.size!==A.stat.size||pe.mtimeMs!==A.stat.mtimeMs||pe.ctimeMs!==A.stat.ctimeMs)&&ce(_,{path:_,size:pe.isFile()?pe.size:null,type:pe.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,pe;try{if(B=await oe.lstat(A.target),!L(n))return;pe=await oe.readlink(A.target,{encoding:"buffer"})}catch(C){if(!L(n))return;if(!ke(C)&&!be(C))throw C;ce(_,{path:_,size:null,type:"other",reason:ke(C)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(!B.isSymbolicLink()||!fr(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(pe))&&ce(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,V;try{if(I=await oe.realpath(A.target),!L(n))return;V=await oe.lstat(A.target)}catch{if(!L(n))return;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;if(!(I===A.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&fr(A.stat,V)&&$(c,I)&&!Kt(u,I))){ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let G;try{if(!L(n))return;G=await Ty(n,I)}catch(B){if(Kn(B))throw B;ce(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;G.dirty?ce(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):G.hash!==A.hash&&ce(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!L(n))return;try{let I=await oe.lstat(A);if(!L(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!L(n))return;if(be(I))continue;if(!ke(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},dt=await qy(n,e,a,t.gitSelectionHooks);if(dt===null){let _=await Ay({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of _.records){if(V.type!=="file"&&V.type!=="symlink"||N.has(V.path))continue;if(Ut(n)<1)break;if(!jy(r,V.path,n))continue;if(Ut(n)<1)break;let ae=q.resolve(s,...V.path.split("/")),G;try{G=await oe.lstat(ae)}catch(B){if(!L(n))break;if(!ke(B)&&!be(B))throw B;P({path:V.path,size:null,type:"file",reason:be(B)?"changed-during-read":"unreadable"});continue}if(Ut(n)<1)break;if(V.type==="symlink"&&G.isSymbolicLink()){if(await Zt(ae,V.path,G),Ut(n)<1)break;continue}if(V.type!=="file"||!G.isFile()||G.isSymbolicLink()){P({path:V.path,size:G.isFile()?G.size:null,type:G.isDirectory()?"directory":G.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await Z(ae,V.path,G),Ut(n)<1)break}Ut(n)>=1&&await Dt();let A=await Ay({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=iI(_.evidence,A.evidence);w=I.evidence;for(let V of[..._.omissions,...A.omissions,...I.omissions])m.some(ae=>ae.path===V.path&&ae.reason===V.reason)||P(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let C=Pi(_);for(let le of C.entries)le.gitObjectId!==void 0&&A.set(le.path,le);I=A.size>0}let V=new Set,ae=!0;try{let C=await Io(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(C.overflow)I=!1,ae=!1,A.clear();else for(let le of C.records){let me=pl(le),Je=me.indexOf(" "),Me=Je<0?null:Yn(me.slice(Je+1));if(Je!==1||Me===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");me[0]!=="H"&&V.add(Me)}}catch(C){if(Kn(C))throw C;I=!1,ae=!1,A.clear()}let G=new Set;try{let C=await hl(n,s,["ls-files","--modified","-z"],mh);for(let le of C.toString("utf8").split("\0")){let me=Yn(le);me!==null&&G.add(me)}}catch{I=!1,ae=!1,A.clear()}let B=new Set,pe=new Set;for(let C of zy(dt)){if(N.has(C)||!To(e,C))continue;if(Ut(n)<1)break;if(!jy(r,C,n))continue;if(Ut(n)<1)break;let le=q.resolve(s,...C.split("/"));if(le===f||le===p||Kt(d,le)||v.some(ft=>Kt(ft,le)))continue;if(dt.gitlinks.has(C)){if(h.length>=i.maxFiles){P({path:C,size:0,type:"file",reason:"file-count"});continue}let ft,xs;try{[ft,xs]=await Promise.all([oe.realpath(le),oe.lstat(le)])}catch{P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(xs.isSymbolicLink()||!xs.isDirectory()||!$(c,ft)||Kt(u,ft)){P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let pn=await Ty(n,ft);if(pn.dirty){P({path:C,size:null,type:"directory",reason:"gitlink-dirty"});continue}await De({path:C,hash:pn.hash,size:0,type:"file"},{kind:"gitlink",target:le,realTarget:ft,stat:xs,hash:pn.hash})}catch(pn){if(Kn(pn))throw pn;P({path:C,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let me;try{me=await oe.lstat(le)}catch(ft){if(be(ft)&&dt.tracked.has(C)){y.set(C,le);continue}if(!ke(ft)&&!be(ft))throw ft;P({path:C,size:null,type:"file",reason:be(ft)?"changed-during-read":"unreadable"});continue}if(me.isSymbolicLink()){await Zt(le,C,me);continue}if(!me.isFile()){dt.nestedRepositories.has(C)||P({path:C,size:null,type:"other",reason:"changed-during-read"});continue}let Je=dt.trackedObjectIds.get(C),Me=Je?A.get(C):void 0;if(I&&Me?.gitObjectId!==void 0&&Me.gitObjectId===Je&&!V.has(C)&&!G.has(C)){if(h.length>=i.maxFiles){P({path:C,size:Me.size,type:"file",reason:"file-count"});continue}if(Me.size>i.maxFileBytes){P({path:C,size:Me.size,type:"file",reason:"file-size"});continue}if(b+Me.size>i.maxTotalBytes){P({path:C,size:Me.size,type:"file",reason:"total-size"});continue}h.push({...Me}),b+=Me.size,B.add(C);continue}let vm=ae&&!V.has(C)&&!G.has(C)?Je:void 0;await Z(le,C,me,vm),vm!==void 0&&pe.add(C)}if(await Dt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Vy(n,e,a,dt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&pe.size>0){let C=await hl(n,s,["ls-files","--modified","-z"],mh),le=new Set;for(let me of C.toString("utf8").split("\0")){let Je=Yn(me);Je!==null&&le.add(Je)}for(let me of B){if(!le.has(me))continue;let Je=h.find(Me=>Me.path===me);ce(me,{path:me,size:Je?.size??null,type:"file",reason:"changed-during-read"})}for(let me of pe){if(!le.has(me))continue;let Je=h.find(Me=>Me.path===me);Je&&delete Je.gitObjectId}}for(let C of dt.omissions)P(C);dt.overflow&&D(dt.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let eE=dt===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...dt.evidence?{gitSelection:dt.evidence}:{}},mm=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:eE,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:E,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),Vu=mm();for(;bh(Vu)>i.maxManifestBytes;){if(m.filter(A=>!vh(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let V=ml(m);if(V===null)break;g(V)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))E+=1,O(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Vu=mm()}return Vu}async function kh(e,t,i={}){let n=(await Ne(e.projectRoot))?.native.snapshot??qf;return yl(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Sh(e,t,i){let r=Uy(e,t);await T(j(e,r),r),await te(r,Pi(i))}async function Qn(e,t){let i=Uy(e,t),r=j(e,i);await T(r,i);try{let n=await nl({root:r,file:i,maxBytes:PT,label:"Native baseline snapshot manifest"});return Pi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as II}from"crypto";import jI from"path";var vt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as RI}from"node:crypto";import{constants as bl,promises as Ke}from"node:fs";import gt from"node:path";import{TextDecoder as xI}from"node:util";import kI from"path";var wI=mn(qr(),1);var Yq=4*1024*1024;var yI=null;function NI(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function Ky(e,t){return(...i)=>{let r=yI;if(r===null)return t(...i);let n=NI(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var t1=Ky("hookWritePolicy",async e=>(await Df(e))?.hook??{allow_paths:[]});var Yy=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Oo(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 $o(e,t){let i=Oo(e,t);if(kI.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 SI(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Xy(e){if(!e.run_id)return null;let t=Oo(e,"run_id"),i=Oo(e,"skill"),r=Oo(e,"skill_version"),n=Oo(e,"skill_hash"),a=$o(e,"pending_ref"),o=$o(e,"trajectory_ref"),s=$o(e,"context_ref"),c=$o(e,"artifacts_ref"),l=$o(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:Yy(e,"current_step"),iteration:u,pending:Yy(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:SI(e)}}var K1=256*1024;var EI=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function PI(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=Xy(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Nl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!EI.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return PI(t)}var qe={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 Do(e,t){let i=gt.relative(e,t);return i===""||!gt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${gt.sep}`)}function Zy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ho(e,t){return z({...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 CI(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function pr(e,t,i){let r=vt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=gt.resolve(e),a=gt.resolve(n,...r.slice(8).split("/"));if(!Do(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function Qy(e){let t=await Ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Eh(e,t){let i=gt.resolve(e),r=gt.resolve(t);if(!Do(i,r))throw new Error("Native Run path is outside its change");let n=[await Qy(i)],a=i;for(let o of gt.relative(i,r).split(gt.sep).filter(Boolean)){a=gt.join(a,o);let s;try{s=await Qy(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Do(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function kl(e){for(let t of e){let i=await Ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!CI(t,i)||await Ke.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function AI(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function Qr(e,t,i,r,n){let a=await Eh(e,gt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Ke.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=Zy(o),c=await Ke.realpath(t);if(!Do(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?bl.O_RDONLY:bl.O_RDONLY|bl.O_NOFOLLOW|bl.O_NONBLOCK,u;try{u=await Ke.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Ke.lstat(t),Ke.realpath(t)]);if(await kl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Ho(s,d)||!Ho(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await AI(u,i,r);await n?.beforeFinalCheck?.();let[h,m,N]=await Promise.all([u.stat(),Ke.lstat(t),Ke.realpath(t)]);if(await kl(a),!m.isFile()||m.isSymbolicLink()||N!==c||!Ho(s,h)||!Ho(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new xI("utf-8",{fatal:!0}).decode(v)}catch(E){throw new Error(`${r} is not valid UTF-8`,{cause:E})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function _I(e,t,i){let r=await Eh(e,gt.dirname(t));if(!r)return{exists:!1};let n;try{n=await Ke.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Ke.realpath(t);if(!Do(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await kl(r),{exists:!0,identity:Zy(n),realPath:a}}async function TI(e,t,i,r){let n=await Eh(e,gt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await Ke.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Ho(i.identity,a)||await Ke.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await kl(n)}async function Sl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await _I(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ue(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await TI(e.changeDir,e.file,i,e.label)}});let r=await Qr(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function eN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function tN(e){return`${JSON.stringify(e,null,2)}
182
+ `}function mr(e){return Nl(e)}async function Ie(e,t){let i=pr(e,"stateRef"),r=await Qr(e,i,qe.runStateBytes,"Native Run state",t);return r?Nl(eN(r.text,"Native Run state")):null}async function Zr(e,t,i){let r=Nl(t);await Sl({changeDir:e,file:pr(e,"stateRef"),content:tN(r),maxBytes:qe.runStateBytes,label:"Native Run state",hooks:i})}async function Ye(e,t,i){let r=pr(e,"trajectoryRef",t),n=await Qr(e,r,qe.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>qe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${qe.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 iN(e,t,i){return(await Qr(e,pr(e,"trajectoryRef",t),qe.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function rN(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=pr(e,"trajectoryRef",t),o=await Qr(e,a,qe.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(RI("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await Sl({changeDir:e,file:a,content:i,maxBytes:qe.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function nN(e,t,i,r){let n=pr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
183
+ `;if(Buffer.byteLength(a,"utf8")>qe.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${qe.trajectoryEventBytes} bytes`);let o=await Qr(e,n,qe.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=qe.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${qe.trajectoryEvents} events`);await Sl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:qe.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function Zn(e,t,i){let r=await Qr(e,pr(e,"checkpointRef",t),qe.checkpointBytes,"Native Run checkpoint",i);return r?eN(r.text,"Native Run checkpoint"):null}async function aN(e,t,i,r){await Sl({changeDir:e,file:pr(e,"checkpointRef",t),content:tN(i),maxBytes:qe.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var $I=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,El=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 Ph(e){return II("sha256").update(e).digest("hex")}function OI(e,t){if(!$I.test(t))throw new Error(`Invalid Native change name: ${t}`);return jI.join(H(e,t),"trajectory.jsonl")}function HI(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function DI(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 MI(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=HI(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
184
+ `)])}catch(d){if(!DI(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Ph(t),targetHash:Ph(l),tailHash:Ph(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function oN(e,t){let i=OI(e,t);await T(j(e,i),i);let r=H(e,t),n=await iN(r,vt.trajectoryRef);return n===null?{status:"clean",file:i}:MI(i,Buffer.from(n))}async function ea(e,t){let i=await oN(e,t);return"inspection"in i?i.inspection:i}async function Pl(e,t){let i=await ea(e,t);if(i.status!=="clean")throw new El(i)}async function sN(e,t,i){return he(e,`repair trajectory tail for ${t}`,async()=>{let r=await oN(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new El(r)}try{await rN(H(e,t),vt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await ea(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as LI}from"node:crypto";import{promises as Rl}from"node:fs";import Ri from"node:path";var Mo=/^[a-f0-9]{64}$/u,cN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,BI=16*1024,xh=process.platform,qI=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ta(e){return qI.has(e)}function dN(e,t){let i=Ri.relative(e,t);return Ri.isAbsolute(i)||i===".."||i.startsWith(`..${Ri.sep}`)?null:i.replaceAll("\\","/")||"."}function fN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function hN(e,t){if(e.length===0||fN(e)||e.includes("\\")||Ri.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=Ri.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Ch(e,t){return LI("sha256").update(`${e}
185
+ ${t}`).digest("hex")}async function lN(e,t){let i=await Rl.realpath(t),r=await Rl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=xh==="win32"?Ri.normalize(i).toLowerCase():i;return Ch(e,`${n}
186
186
  ${r.dev}
187
187
  ${r.ino}
188
- ${r.birthtimeMs}`)}async function Ly(e,t){let i=await Nl.realpath(t),r=await Nl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=vh==="win32"?Ei.normalize(i).toLowerCase():i;return gh(e,n)}function sI(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 mh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||qy(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Wy(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(mh(e.changeBranch,"Native workspace change branch"),mh(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 cI(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Fy.test(t.baseCommit)||typeof t.targetCommit!="string"||!Fy.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");mh(t.targetBranch,"Native workspace Git target branch")}function Do(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Ho.test(String(t.projectRootId))||!Ho.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");sI(t.capturedAt),Vy(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ho.test(String(t.projectRootPathId))||a&&!Ho.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ho.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&cI(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Wy(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 Yn(e,t){return Ei.join(H(e,t),"workspace.json")}function lI(e,t){let i=Yn(e,t),r=j(e,i),n=By(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:Vy(n,"Native workspace file ref")}}async function zy(e,t){try{let i=lI(e,t),r=await ee({root:i.root,ref:i.ref,maxBytes:aI});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Jy(e,t){let i=Ae(e.projectRoot),r={projectRoot:Ei.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await vt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await Xn({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function wh(e,t){let i=await zy(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Do(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function Gy(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=By(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ae(e.paths.projectRoot),r=i.isGitWorktree?mf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:mf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([My("comet.native.workspace-project-root.v2",e.paths.projectRoot),My("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Ly("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Ly("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&Wy(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:gh("comet.native.workspace-session.v2",`${s}
188
+ ${r.birthtimeMs}`)}async function uN(e,t){let i=await Rl.realpath(t),r=await Rl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=xh==="win32"?Ri.normalize(i).toLowerCase():i;return Ch(e,n)}function VI(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 Rh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||fN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function pN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Rh(e.changeBranch,"Native workspace change branch"),Rh(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 WI(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!cN.test(t.baseCommit)||typeof t.targetCommit!="string"||!cN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Rh(t.targetBranch,"Native workspace Git target branch")}function Fo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Mo.test(String(t.projectRootId))||!Mo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");VI(t.capturedAt),hN(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Mo.test(String(t.projectRootPathId))||a&&!Mo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Mo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&WI(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(pN(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 ia(e,t){return Ri.join(H(e,t),"workspace.json")}function zI(e,t){let i=ia(e,t),r=j(e,i),n=dN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:hN(n,"Native workspace file ref")}}async function mN(e,t){try{let i=zI(e,t),r=await Q({root:i.root,ref:i.ref,maxBytes:BI});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function vN(e,t){let i=Ae(e.projectRoot),r={projectRoot:Ri.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await wt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await ra({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Ah(e,t){let i=await mN(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Fo(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function gN(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=dN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ae(e.paths.projectRoot),r=i.isGitWorktree?xf(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:xf(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([lN("comet.native.workspace-project-root.v2",e.paths.projectRoot),lN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),uN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),uN("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&pN(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Ch("comet.native.workspace-session.v2",`${s}
189
189
  ${c}
190
- ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Do(h),h}async function bl(e){let t=await Gy(e),i=Yn(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await te(i,t,{containedRoot:r}),t}async function vt(e,t){let i=await zy(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Do(i),i)}async function Uy(e){return await wh(e.paths,e.name)?bl(e):null}async function Fo(e){Do(e.identity);let t=await Gy({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),vh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function Xn(e){if(Do(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Fo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ae(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Ky(e,t){let i=await vt(e,t);if(i===null)return null;let r=await Xn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Xy=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],uI=new Set(Xy),Qy=new Set([...Xy,"minimum_runtime_version","revision"]),dI=new Set([...Qy,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),fI=new Set(["capability","operation","source","base_hash"]),hI=new Set(["shape","build","verify","archive"]),pI=new Set(["implicit","confirmed"]),mI=new Set(["pending","pass","fail"]),Re="comet-state.yaml",Nh=/^[a-f0-9]{64}$/u,Zy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Mo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Qr=class extends Error{constructor(i,r){super(i!==ge||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Lo=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Bo=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Qn=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},$q=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
191
- `);function Vo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function eN(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Sl(e){if(!Zy.test(e))throw new Error(`Invalid Native change name: ${e}`)}function gI(e){if(!Zy.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function tN(e,t){if(e.length===0||ci.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function wI(e,t){let i=Vo(e,`spec_changes[${t}]`);if(eN(i,fI,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(gI(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&tN(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Nh.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Nh.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function yI(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 bh(e,t){if(eN(e,t,Re),typeof e.name!="string")throw new Error("Native change name is required");if(Sl(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"||!hI.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&&!pI.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(wI),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!mI.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"&&tN(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!yI(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 Jr(e){let t=Vo(e,Re);if(t.schema!==Ge)throw new Error(`Expected ${Ge}`);return{schema:Ge,...bh(t,uI)}}function qo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function yh(e,t,i){if(e===null)return null;let r=typeof e=="string"?vI.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function NI(e){if(e==null)return null;if(typeof e!="string"||!Nh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function bI(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 ni(e){let t=Vo(e,Re);if(t.schema!==we)throw new Error(`Expected ${we}`);if(qo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${we} minimum_runtime_version must be 2`);return{schema:we,minimum_runtime_version:2,revision:qo(t.revision,"Native v2 revision"),...bh(t,Qy)}}function nt(e){let t=Vo(e,Re);if(t.schema!==ge){if(t.schema===Ge||t.schema===we){let o=t.schema===Ge?Jr(t):ni(t);throw new Mo(o.name,o.schema)}throw new Qr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=qo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Qr(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=qo(t.revision,"Native revision"),n=bh(t,dI),a=NI(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ge,minimum_runtime_version:3,revision:r,verification_protocol:bI(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:yh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:yh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:yh(t.partial_allowance,"Native partial_allowance","allowances")}}function iN(e){let t=Vo(e,Re);if(t.schema===Ge){let n=Jr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema===we){let n=ni(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema!==ge){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Qr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=qo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Qr(t.schema,i).message};let r=nt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function Xr(e){let t=nt(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 El(e){let t=ni(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function re(e,t){Sl(t);let i=ci.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Zn(e,t){let i=H(e,t),r=ci.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Yy.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ea(e,t){let i=H(e,t),r=ci.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Yy.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var kI=256*1024;async function Pl(e,t=ci.dirname(e)){let i=ci.relative(t,e).split(ci.sep).join("/"),r=await ee({root:t,ref:i,maxBytes:kI}),n=(0,kl.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function li(e,t){let i=ci.join(re(e,t),Re);await T(e.nativeRoot,i);let r=iN(await Pl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Zn(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await SI(e,r.state),r)}async function Rl(e,t){let i=ci.join(re(e,t),Re);await T(e.nativeRoot,i);let r=iN(await Pl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function SI(e,t){if(await Jn(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function je(e,t){let i=await li(e,t);if(i.status==="migration-required")throw new Mo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Qr(i.schema,i.minimumRuntimeVersion);return await Ky(e,t),i.state}async function rN(e,t,i){let r={...t,schema:ge,minimum_runtime_version:3,revision:i+1},n=await ry({expectedRevision:i,next:r,read:async()=>{let a=nt(await Pl(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ue(e,(0,kl.stringify)(Xr(a))),equals:(a,o)=>JSON.stringify(Xr(a))===JSON.stringify(Xr(o)),conflict:a=>new Lo(t.name,i,a)});return Object.assign(t,n),n}async function xl(e,t,i,r){if(await _n(e.projectRoot),await Zn(e,t.name))throw new Mo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await ea(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await je(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await yl(e,t.name);let a=ci.join(re(e,t.name),Re);return await T(e.nativeRoot,a),rN(a,t,i)}async function nN(e,t){return rN(e,t,t.revision)}async function aN(e){return nt(await Pl(e))}var sN=["Outcome","Scope","Non-goals","Acceptance examples"],EI=[...sN,"Constraints and invariants","Decisions","Open questions","Verification expectations"],PI=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],cN={maxFileBytes:ao};function lN(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
192
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function RI(e,t){let i=oN.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await kh.realpath(e),n=await kh.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await kh.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Wo(e){return{valid:e.length===0,findings:e}}async function Sh(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:cN.maxFileBytes})).text}catch(o){return Wo([{code:"brief-missing",message:o.message,path:t}])}let n=lN(r);for(let o of EI)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of sN)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Wo(i)}async function Eh(e,t){let i=[],r;try{r=(await ee({root:e,ref:t,maxBytes:cN.maxFileBytes})).text}catch(a){return Wo([{code:"verification-missing",message:a.message,path:t}])}let n=lN(r);for(let a of PI)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Wo(i)}function Cl(e,t){return oN.join(e.specsDir,t,"spec.md")}async function uN(e,t){let i=[],r=re(e,t.name);for(let n of t.spec_changes){let a=Cl(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await zt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await RI(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Wo(i)}import{promises as IO}from"node:fs";import Gb from"node:path";import dN from"node:path";var xI="comet.native.archive-preflight.v1",CI="comet.native.archive-preflight.v1",AI="comet.native.archive-operation.v1",_I=/^[a-f0-9]{64}$/u,fN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Al(e,t){return e<t?-1:e>t?1:0}function II(e,t){if(typeof e!="string"||!_I.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pi(e,t){return e===null?null:II(e,t)}function jI(e,t){let i=dN.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||dN.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 $I(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function OI(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function HI(e,t){if(!fN.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=Pi(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Pi(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Pi(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function DI(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:Pi(e.contractHash,"Native archive contract hash"),acceptanceHash:Pi(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Pi(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Pi(e.reportHash,"Native archive report hash"),envelopeHash:Pi(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Pi(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 FI(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!TI.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(Al);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function MI(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(Al)}function hN(e){if(!fN.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(HI).sort((l,u)=>Al(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:L(AI,l)})),r=DI(e.evidence),n=OI(e.workspace),a=[...new Set([...FI(e.findingCodes??[]),...MI({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(Al),o=$I(e.revision),s=jI(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:xI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:L(CI,c)}}import{createHash as LI}from"node:crypto";import pN from"node:path";var BI="comet.native.conflict-radar.v1",at=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}),qI="comet.native.conflict-radar.v1",VI="comet.native.conflict-radar-signals.v1",WI=/^[a-f0-9]{64}$/u,gN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zI=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),JI=new Set(["capability","operation","baseHash"]),GI=new Set(["path","kind"]);function ta(e,t){return e<t?-1:e>t?1:0}function Ph(e){return Buffer.byteLength(e,"utf8")}function Rh(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function xh(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(Ph(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function UI(e,t){let i=xh(e,t,at.maxArtifactPathBytes),r=pN.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||pN.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function wN(e,t){if(typeof e!="string"||!WI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function KI(e,t){let i=Rh(e,JI,t),r=xh(i.capability,`${t} capability`,at.maxCapabilityBytes);if(!gN.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:wN(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function YI(e,t){let i=Rh(e,GI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:UI(i.path,`${t} path`),kind:i.kind}}function XI(e,t){let i=Rh(e,zI,`Conflict radar change ${t}`),r=xh(i.name,`Conflict radar change ${t} name`,at.maxNameBytes);if(!gN.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>at.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>at.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>KI(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>ta(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>YI(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>ta(c.path,l.path)||ta(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:wN(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function QI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>at.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(XI).sort((n,a)=>ta(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>at.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>at.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function ZI(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function ej(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function tj(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function ij(e,t){let i=[],r=LI("sha256").update(`${VI}
193
- [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(bo(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<at.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(ZI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=ej(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:tj(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function mN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function rj(e,t){return mN(e.classification)-mN(t.classification)||ta(e.left,t.left)||ta(e.right,t.right)}function vN(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:BI,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function yN(e){let t=QI(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(ij(t[s],t[c]));i.sort(rj);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=L(qI,{changes:t,relationships:r}),a=i.slice(0,at.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=vN(t,i,a,n);for(;a.length>0&&Ph(JSON.stringify(o))>at.maxSerializedBytes;)a=a.slice(0,-1),o=vN(t,i,a,n);if(Ph(JSON.stringify(o))>at.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as p$}from"node:crypto";import{promises as Kt}from"node:fs";import fi from"node:path";import{createHash as xN}from"node:crypto";import NN from"path";var Ch="comet.native.implementation-scope.v2",CN="comet.native.content-snapshot-projection.v1",zo="comet.native.content-snapshot-projection.v1",AN="comet.native.implementation-scope.v2",nj="comet.native.unresolved-scope-id.v1",aj="comet.native.scope-detail-overflow.v1",oj="comet.native.snapshot-projection-overflow.v2",Ih=/^[a-f0-9]{64}$/u,en=1024*1024,sj=128,cj=128;function Ve(e,t){return e<t?-1:e>t?1:0}function Ah(e){if(!Ih.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function lj(e,t){return e===t?0:e===null?-1:t===null?1:Ve(e,t)}function pr(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=NN.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||NN.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function _N(e,t){return e==="."?e:pr(e,t)}function ia(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function uj(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:pr(e.path,`${t} path`),hash:e.hash,size:ia(e.size,`${t} size`),type:"file"}}function dj(e,t){return{path:_N(e.path,`${t} path`),size:e.size===null?null:ia(e.size,`${t} size`),type:e.type,reason:e.reason}}function fj(e,t){return Ve(e.path,t.path)||Ve(e.hash,t.hash)||e.size-t.size}function hj(e,t){return Ve(e.path,t.path)||Ve(e.reason,t.reason)||Ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Go(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
194
- `,"utf8")}function hr(e,t,i){let r=`${t}
195
- ${bo(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function pj(e){if(Go(e)<=en)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=xN("sha256");a.update(`${oj}
196
- `),e.omissionOverflow&&hr(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,hr(a,"omission",f)},s=f=>{r+=1,n+=1,hr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Go(u)>en;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<h;v+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function _h(e){let t=Si(e),i=t.entries.map((n,a)=>uj(n,`Snapshot entry ${a}`));if(i.sort(fj),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>dj(n,`Snapshot omission ${a}`));return r.sort(hj),pj({schema:CN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Uo(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:pr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>Ve(i.path,r.path)||Ve(i.kind,r.kind))}function Ko(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function bN(e){return e?{hash:e.hash,size:e.size}:null}function jh(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ve(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:bN(c),after:bN(l)})}}function TN(e,t){return{...e,attributedTo:t.filter(i=>Ko(i,e.path))}}function $h(e){let t=Uo(e.declaredArtifacts),i=[];return jh(e.baseline,e.current,r=>{i.push(TN(r,t))}),i}function Ri(e,t){return{id:`scope:${L(nj,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function mj(e,t){let i=t.omitted.map(r=>Ri({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(Ri({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Ri({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 kN(e,t){return mj(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Th(e,t){return Ve(e.kind,t.kind)||Ve(e.source,t.source)||lj(e.path,t.path)||Ve(e.id,t.id)}function vj(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Th)}function IN(e){return[...new Set(e.map((t,i)=>pr(t,`Git path ${i}`)))].sort(Ve)}function SN(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function gj(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function jN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=IN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:SN(e.baseCommit,"Native external drift base commit"),targetBranch:gj(e.targetBranch,"Native external drift target branch"),targetCommit:SN(e.targetCommit,"Native external drift target commit"),paths:t}}function $N(e){if(typeof e.contractHash!="string"||!Ih.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Uo(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:IN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:jN(e.externalDrift)}}}function wj(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return jh(e,t,h=>{let v=i.some(p=>Ko(p,h.path));if(d+=1,c.push(h.path),!v&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<sj){let p=TN(h,i),m=Go(p);l+m<=en?(a.push(p),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function ON(e,t){return Ri({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 yj(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:ia(Number(t[1]),"Scope overflow change count"),unresolved:ia(Number(t[2]),"Scope overflow unresolved count"),unattributed:ia(Number(t[3]),"Scope overflow unattributed count")},r=Zr(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(ON(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function Nj(e){let t=xN("sha256");t.update(`${aj}
197
- `);let i=0;jh(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){hr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Ko(o,n.path)&&(a+=1,hr(t,"change-attribution",o));hr(t,"change-end",{attributionCount:a}),a===0&&hr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&hr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function HN(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=wj(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(E=>!w.has(E)||n.some(q=>Ko(q,E)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=L(zo,e),c=L(zo,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=cj)break;l.push(Ri({kind:"snapshot-omission",source:R,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${R} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...kN("baseline",e),...kN("current",t),...o.totalChanges===0&&a===null?[Ri({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>R.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!R.has(w))}},v=R=>{let w=o.candidates.slice(0,R.detailedChangeCount),g=w.filter(Ot=>Ot.attributedTo.length===0&&!u.has(Ot.path)),E=o.totalChanges-w.length,q=o.totalUnattributed-g.length,O=d-R.detailedOmissionCount,He=q+O,ce=[...g.map(Ot=>Ri({kind:"unattributed-change",source:"implementation-scope",path:Ot.path,evidence:{after:Ot.after,before:Ot.before,changeKind:Ot.kind}},`Changed path is not covered by a declared artifact: ${Ot.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...He>0?[ON(R.overflowHash,{changes:E,unattributed:q,unresolved:He})]:[]],Q=vj(ce),Qt=R.includeGitAdvisory?h():void 0;return{schema:Ch,contractHash:r,baselineProjectionRef:Ah(s),baselineProjectionHash:s,currentProjectionRef:Ah(c),currentProjectionHash:c,complete:Q.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:Q,noCodeReason:a,...Qt?{gitAdvisory:Qt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},p=o.candidates.length,m=l.length,b=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:y});if(Go({...R,scopeHash:y})<=en)break;if(b){b=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>p||d>m?Nj({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:m}):y,k=v({detailedChangeCount:p,detailedOmissionCount:m,includeGitAdvisory:b,overflowHash:S}),N={...k,scopeHash:L(AN,k)};if(Go(N)>en)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return N}function Oh(e){let t=_h(e.baseline),i=_h(e.current),r=$N(e);return{authority:r,baseline:t,current:i,scope:HN(t,i,r)}}var bj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function ui(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function di(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Zr(e,t){if(typeof e!="string"||!Ih.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function EN(e,t,i){let r=Ah(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function ra(e,t){let i=ui(e,"Native snapshot projection");if(di(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==CN)throw new Error("Native snapshot projection schema is invalid");let r=Si({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=_h(r);if(L(zo,i)!==L(zo,n))throw new Error("Native snapshot projection is not canonical");let a=L(zo,n);if(t!==void 0&&Zr(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Hh(e,t){let i=ui(e,`Declared artifact ${t}`);if(di(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:pr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function PN(e,t){if(e===null)return null;let i=ui(e,t);return di(i,["hash","size"],[],t),{hash:Zr(i.hash,`${t} hash`),size:ia(i.size,`${t} size`)}}function RN(e,t){let i=ui(e,`Implementation change ${t}`);if(di(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Hh),n=Uo(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=PN(i.before,`Implementation change ${t} before`),o=PN(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:pr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function kj(e,t){let i=ui(e,`Unresolved scope ${t}`);di(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?_N(i.path,`Unresolved scope ${t} path`):pr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Jo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>pr(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function DN(e){let t=ui(e,"Native implementation external drift");if(di(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Jo(t.paths,"Native external drift paths");return jN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function na(e){let t=ui(e,"Native implementation scope"),i=[...bj].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(di(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Ch)throw new Error("Native implementation scope schema is invalid");let r=Zr(t.contractHash,"Implementation scope contractHash"),n=Zr(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=EN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Zr(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=EN(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(Hh);if(JSON.stringify(c)!==JSON.stringify(Uo(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(RN),u=[...l].sort((g,E)=>Ve(g.path,E.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(g=>g.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(g=>`${g.kind}:${g.path}`));if(l.some(g=>g.attributedTo.some(E=>!d.has(`${E.kind}:${E.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(E=>Ko(E,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(RN),h=t.externalDrift===void 0?void 0:DN(t.externalDrift),v=new Set(h?.paths??[]),p=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(kj),b=m.filter(g=>g.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=b[0]===void 0?null:yj(b[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let P=t.noCodeReason,S=[...p.map(g=>Ri({kind:"unattributed-change",source:"implementation-scope",path:g.path,evidence:{after:g.after,before:g.before,changeKind:g.kind}},`Changed path is not covered by a declared artifact: ${g.path}`)),...l.length+(y?.changes??0)===0&&P===null?[Ri({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Th))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(S.sort(Th))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let N;if(t.gitAdvisory!==void 0){let g=ui(t.gitAdvisory,"Implementation scope Git advisory");if(di(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let E=Jo(g.changedPaths,"Git changed paths"),q=Jo(g.pathsPresentInSnapshotChanges,"Git present paths"),O=Jo(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),He=[...q,...O].sort(Ve);if(JSON.stringify(He)!==JSON.stringify(E)||O.some(ce=>l.some(Q=>Q.path===ce)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:E,pathsPresentInSnapshotChanges:q,pathsAbsentFromSnapshotChanges:O}}let R={schema:Ch,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:P,...N?{gitAdvisory:N}:{},...h?{externalDrift:h}:{}},w=Zr(t.scopeHash,"Implementation scope scopeHash");if(L(AN,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function Sj(e){let t=ui(e,"Native implementation scope authority");if(di(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Hh);if(JSON.stringify(i)!==JSON.stringify(Uo(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Jo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:DN(t.externalDrift),a=$N({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Yo(e){let t=ui(e,"Native implementation scope bundle");di(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Sj(t.authority),r=ra(t.baseline),n=ra(t.current),a=na(t.scope),o=HN(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function FN(e){let t=na(e.scope);return Yo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import MN from"node:path";var Ej=/\b(Bearer|Basic)\s+[^\s"']+/giu,Pj=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,Rj=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,xj=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,Cj=/("(?:[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,Aj=/(["'])((?:[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,_j=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function At(e){return e.replace(Ej,"$1 [REDACTED]").replace(Pj,"[REDACTED PRIVATE KEY]").replace(Rj,"$1[REDACTED]@").replace(xj,"[REDACTED TOKEN]").replace(Cj,'$1"[REDACTED]"').replace(Aj,"$1$2$1$3$4[REDACTED]$4").replace(_j,"$1$2[REDACTED]")}var BN=/^[a-f0-9]{64}$/u;var Tj="comet.native.acceptance-trace.v2",Ij="comet.native.partial-allowance.v1",jj="comet.native.verification-evidence.v2";function xi(e,t){if(!BN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function qN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function VN(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 Dh(e,t,i=2e3){let r=At(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Xo(e,t){let i=MN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||MN.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 $j(e,t,i){let r=Xo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ti(r),a=r.toLowerCase(),o=i?Xo(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Fh(e){let t=Xo(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 aa(e,t){return e<t?-1:e>t?1:0}function _l(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tl(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function WN(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 LN(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function Oj(e){let t=_l(e,"Native acceptance trace");if(Tl(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"||!BN.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=Xo(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=_l(o,`Native acceptance trace entry ${s}`);if(Tl(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=>Fh(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(aa))||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:Xo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Dh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>aa(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=xi(t.traceHash,"Native acceptance trace hash");if(L(Tj,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Il(e){let t=_l(e,"Native partial allowance");if(Tl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(aa))||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:VN(t.change),scopeHash:xi(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Dh(t.reason,"Partial allowance reason"),confirmedSummary:Dh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:qN(t.sourceRevision),confirmedAt:WN(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=xi(t.allowanceHash,"Native partial allowance hash");if(L(Ij,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Qo(e){let t=_l(e,"Native verification evidence");if(Tl(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=xi(t.implementationScopeHash,"Native verification implementation scope hash"),r=Oj(t.acceptanceTrace),n=xi(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:xi(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Fh(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(aa)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(aa);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=>Fh(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(aa)))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:VN(t.change),sourceRevision:qN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:xi(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:LN(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:$j(t.reportRef,"Native verification report ref"),reportHash:xi(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:LN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:WN(t.createdAt,"Native verification timestamp")},d=xi(t.envelopeHash,"Native verification envelope hash");if(L(jj,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import zN from"node:path";var JN="comet.native.check-receipt.v1",Hj="comet.native.check-receipt.v1",oa="scoped-text-safety",Mh=1,ot=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Dj=/^[a-f0-9]{64}$/u,Fj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Mj="comet.native.checker-policy.v1",Lj="comet.native.check-input.v1",Bj=2048,GN=L(Mj,{policy:oa,version:Mh,limits:ot,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),qj=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),UN=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],YN=["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"],Vj=new Set(YN);function mr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Ci(e,t){if(typeof e!="string"||!Dj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function gt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function XN(e,t){let i=gt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function KN(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 Wj(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>Bj||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=zN.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||zN.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function zj(e){let t=mr(e,"Native check receipt checker");vr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=mr(t.limits,"Native check receipt limits");if(vr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==oa||t.version!==Mh||t.hash!==GN||i.maxFiles!==ot.maxFiles||i.maxFileBytes!==ot.maxFileBytes||i.maxTotalBytes!==ot.maxTotalBytes||i.maxIssues!==ot.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:oa,version:Mh,hash:GN,limits:{...ot}}}function Jj(e){let t=mr(e,"Native check receipt contract");return vr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Ci(t.expectedHash,"Native check expected contract hash"),beforeHash:Ci(t.beforeHash,"Native check before contract hash"),afterHash:Ci(t.afterHash,"Native check after contract hash")}}function Gj(e){let t=mr(e,"Native check receipt implementation");return vr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Ci(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Ci(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Ci(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Ci(t.afterSnapshotHash,"Native check after snapshot hash")}}function Uj(e,t){let i=mr(e,`Native check batch ${t}`);vr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:gt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:gt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:gt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:gt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:gt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:gt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>ot.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>ot.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function Kj(e){let t=mr(e,"Native check receipt counts");vr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:gt(t.filesSelected,"Native check filesSelected"),filesScanned:gt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:gt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:gt(t.bytesScanned,"Native check bytesScanned"),issueCount:gt(t.issueCount,"Native check issueCount"),recordedIssueCount:gt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(Uj):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ot.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>ot.maxFiles||i.bytesScanned>ot.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function Yj(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||UN.indexOf(e.kind)-UN.indexOf(t.kind)}function Xj(e){if(!Array.isArray(e)||e.length>ot.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=mr(r,`Native check issue ${n}`);if(vr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!qj.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:Wj(a.path,`Native check issue ${n} path`),line:XN(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(Yj);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function Qj(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!Vj.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=YN.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function Zj(e){return L(Lj,e)}function jl(e){let t=mr(e,"Native check receipt");if(vr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==JN)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!Fj.test(t.change))throw new Error("Native check receipt change name is invalid");let i=XN(t.sourceRevision,"Native check source revision"),r=zj(t.checker),n=Jj(t.contract),a=Gj(t.implementation),o=Zj({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Ci(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=KN(t.startedAt,"Native check receipt startedAt"),c=KN(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=Kj(t.counts),u=Xj(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=Qj(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>ot.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>ot.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:JN,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Ci(t.receiptHash,"Native check receipt content hash");if(L(Hj,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var Bh="comet.native.verification-receipt.v3",e$=Bh,t$="comet.native.declared-artifacts.v1",i$=/^[a-f0-9]{64}$/u,r$=/^acceptance-[a-f0-9]{64}$/u,n$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,a$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,o$=4096,s$=256,c$=1024;function sa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function gr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Ai(e,t){if(typeof e!="string"||!i$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ut(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=At(e).trim();if(!i||i.length>o$||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Lh(e,t){let i=Ut(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function Zo(e,t,i=Ut,r=!1,n=s$){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function l$(e,t){if(typeof e!="string"||!r$.test(e))throw new Error(`${t} is invalid`);return e}function u$(e){let t=sa(e,"Native verification receipt bindings");if(gr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!n$.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:Ai(t.contractHash,"Native verification receipt contract hash"),scopeHash:Ai(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Ai(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Ai(t.artifactHash,"Native verification receipt artifact hash")}}function d$(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=a$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function f$(e,t,i,r){let n=sa(t,`Native ${e} evidence`);if(e==="automated-check"){if(gr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Lh(n.startedAt,"Native automated-check start time"),o=Lh(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=sa(n.worktree,"Native automated-check worktree");if(gr(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=sa(n.afterFence,"Native automated-check after fence");if(gr(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:Ut(n.executable,"Native automated-check executable"),args:Zo(n.args,"Native automated-check arguments",Ut,!0),cwd:Ut(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ut(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Ai(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Ai(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Ai(n.outputHash,"Native automated-check output hash"),outputSummary:Ut(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){gr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=d$(n.checkReceiptRef);if(Ai(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Zo(n.subjects,"Native static inspection subjects",Ut,r==="required-check"),rule:Ut(n.rule,"Native static inspection rule"),resultSummary:Ut(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return gr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Zo(n.steps,"Native manual evidence steps"),observations:Zo(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function h$(e){let t=sa(e,"Native verification receipt");if(gr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=Ut(t.actor,"Native verification receipt actor"),o=Zo(t.acceptanceIds,"Native receipt acceptance IDs",l$,r==="required-check",c$).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Bh,kind:i,role:r,status:n,bindings:u$(t.bindings),acceptanceIds:o,actor:a,issuedAt:Lh(t.issuedAt,"Native verification receipt issue time"),evidence:f$(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==oa||s.actor!==`native-runtime:${oa}`))throw new Error("Native required check policy identity is invalid");return s}function $l(e){let t=sa(e,"Native verification receipt");if(gr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Bh)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=h$(r),a=Ai(t.receiptHash,"Native verification receipt hash");if(L(e$,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function qh(e){return L(t$,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var tb=/^[a-f0-9]{64}$/u,wr=en,EV=3*wr;function Vh(e,t){let i=fi.relative(e,t);return i===""||!fi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${fi.sep}`)}function m$(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ol(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function QN(e){let t=await Kt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Kt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function v$(e,t){let i=fi.resolve(e),r=fi.resolve(t);if(!Vh(i,r))throw new Error("Native evidence path is outside its change");let n=[await QN(i)],a=i;for(let o of fi.relative(i,r).split(fi.sep).filter(Boolean)){a=fi.join(a,o);let s=await QN(a);if(!Vh(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ZN(e){for(let t of e){let i=await Kt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!m$(t,i)||await Kt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function g$(e,t,i={}){let r=await v$(t,fi.dirname(e));await i.afterParentChainCaptured?.();let n=await Kt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Kt.realpath(e);if(!Vh(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Kt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Kt.lstat(e),Kt.realpath(e)]);if(await ZN(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Ol(s,n)||!Ol(s,c))throw new Error("Native evidence document changed while opening");if(s.size>wr)throw new Error(`Native evidence document exceeds ${wr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=wr+1-d,b=await o.read(f,0,Math.min(f.length,m),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>wr)throw new Error(`Native evidence document exceeds ${wr} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,p]=await Promise.all([o.stat(),Kt.lstat(e),Kt.realpath(e)]);if(await ZN(r),!v.isFile()||v.isSymbolicLink()||p!==a||!Ol(s,h)||!Ol(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function la(e,t){if(!tb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ib(e){return la("reports",e)}async function w$(e,t,i,r,n){if(!tb.test(i))throw new Error("Native report evidence hash is invalid");let a=await tn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||p$("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 ca(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 y$(e,t,i,r,n){let a=la(i,r);return n?fi.join(n,...a.split("/")):Xi(H(e,t),a)}async function tn(e){let t=y$(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),g$(t,i,e.hooks)}function eb(e,t){return ra(e,t)}function N$(e,t){let i=na(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function b$(e,t,i){let r=Il(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function k$(e,t,i){let r=Qo(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function S$(e,t,i,r=!1,n){let a=await Hl(e,t,i.implementationScopeRef,void 0,n);if(r&&await w$(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await rb(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function es(e,t,i,r,n){let a=ca(i,"scopes"),o=N$(await tn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=ca(o.baselineProjectionRef,"snapshots"),c=ca(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([tn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>eb(d,s)),tn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>eb(d,c))]);return FN({baseline:l,current:u,scope:o})}async function Hl(e,t,i,r,n){return(await es(e,t,i,r,n)).scope}async function rb(e,t,i,r,n){let a=ca(i,"allowances");return b$(await tn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ts(e,t,i,r,n){let a=ca(i,"receipts"),o=$l(await tn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function ua(e,t,i,r,n){let a=ca(i,"verifications"),o=k$(await tn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await S$(e,t,o,!1,n),o}var E$=4096;async function P$(e,t=at.maxChanges){try{let i=await ft({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 nb(e,t){let i=await je(e,t),[r,n]=await Promise.all([i.implementation_scope?Hl(e,t,i.implementation_scope):null,vt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Dl(e,t,i={}){let n=(await P$(e,E$)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await nb(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await nb(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=yN([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as q$}from"fs";import V$ from"path";import{isDeepStrictEqual as Ml}from"util";var da={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var R$=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function x$(e,t){return e<t?-1:e>t?1:0}function C$(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!R$.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(x$)}function Wh(e=[]){return C$(e,"Native repair failed check IDs",da.maxFailedCheckIds,!0)}function ab(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function A$(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:ab(e.failedAcceptanceIds,t.failedAcceptanceIds)&&ab(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function zh(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(A$(r,a))break;i+=1,r=a}return i}function Jh(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 ob="repairStagnation",wt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},T$=/^[a-f0-9]{64}$/u;var I$=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),j$=["data","runId","sequence","timestamp","type"],sb=["disposition","overrideSummaryHash","signatureHash"],$$=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],cb=12;function Uh(e,t){return e<t?-1:e>t?1:0}function lb(e,t,i){let r=Object.keys(e).sort(Uh);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Fl(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 is(e,t){if(typeof e!="string"||!T$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function O$(e){if(!Array.isArray(e)||e.length>da.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(Uh)}function ub(e){if(typeof e!="string"||e.length===0||e.length>wt.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 Gh(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>wt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>wt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>wt.maxTextCharacters&&(!n||e.length>wt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>wt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>wt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Gh(s,t+1,i,`${r}[${c}]`));return}let a=Fl(e,r),o=Object.keys(a);if(o.length>wt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>wt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>wt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Gh(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function H$(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 D$(e,t,i){let r=Fl(e,`Native repair trajectory event ${t+1}`);if(lb(r,j$,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(H$(r.timestamp),typeof r.type!="string"||!I$.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(ub(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Gh(r.data,0,n,"Native trajectory event data"),Fl(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Kh(e){let t=Fl(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Uh),r=i.length===sb.length&&i.every((l,u)=>l===sb[u]);r||lb(t,$$,"Native repair trajectory projection");let n=is(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:is(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=is(t.contractHash,"Native repair trajectory contract hash"),s=O$(t.failedAcceptanceIds),c=Wh(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function F$(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 M$(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??cb;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=zh({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<da.warningAtConsecutiveFailures?"continue":a<da.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function L$(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??cb;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function db(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>wt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=ub(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=D$(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>wt.maxTotalDataNodes||c>wt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?is(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?is(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,ob)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Kh(f[ob]);if(F$(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),M$(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");L$(v,i,r);let p=i.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>da.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function fb(e){return db(e).history}function hb(e){let t=db(e).latestProjection;return t?{...t}:null}var hi={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},rs=D("comet-native-runtime:v3:scope-reopen"),B$=[{skillVersion:"3",skillHash:D("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:D("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:D("comet-native-runtime:v1")}];function pb(e){return e.skillVersion===hi.definition.metadata.version&&e.skillHash===rs||B$.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Yh={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function yr(e){let i={sequence:(await Ke(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 $y(e.changeDir,e.run.trajectoryRef,i),i}async function rn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:D(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Oy(e.changeDir,e.run.checkpointRef,t),t}function mb(e){return D(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Sb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],W$=new Set(Sb),Eb=new Set([...Sb,"minimum_runtime_version","revision"]),z$=new Set([...Eb,"operation"]),J$=512*1024,Xh=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),G$=new Set([...Xh,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),ns=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 We(e,t){return V$.join(H(e,t),"transition.json")}function U$(e){return`transition-${e}`}async function K$(e,t,i){let r=U$(t);return Zi(e,r,i)}async function nn(e,t,i,r){let n=await K$(e,t,i);try{return await r()}finally{await er(n)}}function Bl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Zh(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Ll(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pi(e,t){return Ml(e,t)}function Qh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!G$.has(u)),a=[...Xh].find(u=>!Object.hasOwn(i,u)),o=Xh.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Jh(i.summary,"Native transition journal event summary"),At(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Jh(i.noCodeReason,"Native transition journal event no-code reason"),At(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Kh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function Y$(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return Qh({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Qh(e,t)}function ep(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?Y$(e.eventData,e.evidenceHash):Qh(e.eventData,e.evidenceHash),n=fr(e.nextRun),a=e.previousRun===null?null:fr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function vb(e,t,i=!1){if(e.skill!==hi.definition.metadata.name||(i?!pb(e):e.skillVersion!==hi.definition.metadata.version||e.skillHash!==rs)||e.orchestration!==hi.definition.orchestration.mode||e.pendingRef!==pt.pendingRef||e.trajectoryRef!==pt.trajectoryRef||e.contextRef!==pt.contextRef||e.artifactsRef!==pt.artifactsRef||e.checkpointRef!==pt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function gb(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 wb(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 tp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(vb(o,"next Run",r||a!==null),wb(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(vb(a,"previous Run",!0),wb(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!Ml(gb(a),gb(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function X$(e,t,i){return D(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Pb(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function yb(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function ip(e,t,i,r,n=!1){let a=i.eventData,o=yb(e),s=yb(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&Ml(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&Ml(e.spec_changes,t.spec_changes),l=mb({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=X$(e.name,a.summary,t.spec_changes),l=D(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function rp(e,t){let i=Bl(e);if(Zh(i,z$),i.schema!==ir)throw new Error(`Expected Native transition schema ${ir}`);let r=Ll(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${ir} minimum_runtime_version must be ${3}`);let n=Ll(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=ep(i,t),o=nt(i.previousState),s=nt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(ip(o,s,a,i.operation),tp(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ir,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function Q$(e,t){let i=Bl(e);if(Zh(i,W$),i.schema!==zr)throw new Error(`Expected Native transition schema ${zr}`);let r=ep(i,t,!0),n=Jr(i.previousState),a=Jr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return ip(n,a,r,Pb(n,a,r.eventData),!0),tp(n,a,r,!0),{schema:zr,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function np(e,t){let i=Bl(e);if(Zh(i,Eb),i.schema!==ki)throw new Error(`Expected Native transition schema ${ki}`);if(Ll(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ki} minimum_runtime_version must be 2`);let n=Ll(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=ep(i,t,!0),o=ni(i.previousState),s=ni(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(ip(o,s,a,Pb(o,s,a.eventData),!0),tp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ki,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function Z$(e,t){let i=Bl(e);if(i.schema===ir)return{status:"current",journal:rp(i,t)};if(i.schema===zr)return{status:"migration-required",journal:Q$(i,t)};if(i.schema===ki)return{status:"migration-required",journal:np(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function ap(e,t){let i=We(e,t),r=j(e,i);await T(r,i);try{let n=await ie({root:r,file:i,maxBytes:J$,label:`Native transition journal ${t}`});return Z$(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function _i(e,t){let i=await ap(e,t);if(!i)return null;if(i.status==="migration-required")throw new ns(t);return i.journal}function Nb(e,t){if(pi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(pi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function bb(e,t){if(pi(e,t.nextState))return"next";if(pi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function eO(e){let{journal:t}=e;return Rb({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 Rb(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function kb(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=eO({sequence:a.index+1,journal:t,type:a.event.type});if(!pi(Rb(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function ql(e,t,i){if(await Zn(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await yl(e,t);let r=await _i(e,t);if(!r)return null;let n=H(e,t),a=kb(await Ke(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Te(n),je(e,t)]),c=Nb(o,r),l=bb(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Yr(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!pi(await Te(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let m=await xl(e,r.nextState,r.previousState.revision);if(!pi(m,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!pi(await je(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await _i(e,t);if(!u||!pi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=kb(await Ke(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await yr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await yr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await rn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([Te(n),je(e,t)]);Nb(h,{...r,previousRun:r.nextRun}),bb(v,{...r,previousState:r.nextState});let p=await _i(e,t);if(!p||!pi(p,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await q$.rm(We(e,t),{force:!0}),r.nextState}async function xb(e,t,i){return he(e,`continue transition ${t}`,()=>nn(e,t,`continue transition ${t}`,()=>ql(e,t,i)))}import Cb from"node:path";var tO="comet.native.contract.v1",iO="comet.native.acceptance-set.v1",Ab=/^[a-f0-9]{64}$/u,as={maxAcceptanceCriteria:So.maxCriteria};function _b(e,t){let i=Cb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Cb.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 Tb(e){return L("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
198
- `))}function rO(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(Ab))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(Ab))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=_b(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Tb(e.markdown)},markdown:e.markdown}}function nO(e,t){return Ib(e.id,t.id)}function Ib(e,t){return e<t?-1:e>t?1:0}function jb(e){let t=_b(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(rO).sort((d,f)=>Ib(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Mc(e.briefMarkdown,t,as.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Lc(f,d.source,as.maxAcceptanceCriteria-a.length)),a.push(...Bc(f,d.source,as.maxAcceptanceCriteria-a.length)));if(a.sort(nO),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>as.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${as.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:Tb(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=L(iO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:L(tO,u)}}var Vl={maxSpecs:64,maxFileBytes:ao,maxTotalBytes:4*1024*1024};async function fa(e){if(e.specChanges.length>Vl.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ee({root:e.changeDir,ref:e.briefRef,maxBytes:Vl.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ee({root:e.changeDir,ref:n.source,maxBytes:Vl.maxFileBytes});if(i+=a.size,i>Vl.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:jb({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as SO}from"node:child_process";import{promisify as EO}from"node:util";var RW=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as dO}from"fs";import ha from"path";var br={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},pa=/^[a-f0-9]{64}$/u;function Wl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zl(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Nr(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 $b(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function op(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function aO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||ha.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=ha.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function sp(e,t){return ha.join(H(e,t),"checkpoints","progress.json")}function kr(e,t){return ha.join(H(e,t),"checkpoint-journal.json")}function cp(e,t,i){if(!pa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return ha.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function oO(e){if(!pa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function lp(e,t,i){let r=await ie({root:e,file:t,maxBytes:br.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function sO(e,t){let i=Wl(e,`checkpoint manifest artifact ${t}`);zl(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=aO(Nr(i.path,`checkpoint artifact ${t} path`,4096)),n=ti(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!pa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:op(i.size,`checkpoint artifact ${t} size`)}}function Jl(e,t){let i=Wl(e,"Native checkpoint manifest");if(zl(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>br.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(sO),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=op(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>br.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function up(e){return D(JSON.stringify(Jl(e,e.change)))}function dp(e,t){let i=Wl(e,"Native progress checkpoint");if(zl(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=$b(i.previousRevision,"Native checkpoint previousRevision"),a=$b(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Nr(i.manifestHash,"Native checkpoint manifestHash",64);if(!pa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=oO(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Nr(i.inputHash,"Native checkpoint inputHash",64);if(!pa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Nr(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=op(i.artifactCount,"Native checkpoint artifactCount");if(u>br.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Nr(i.summary,"Native checkpoint summary"),f=Nr(i.nextAction,"Native checkpoint nextAction");if(At(d)!==d||At(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Nr(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function cO(e,t){let i=Wl(e,"Native checkpoint journal");if(zl(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=nt(i.previousState),n=nt(i.nextState),a=dp(i.checkpoint,t),o=Jl(i.manifest,t),s=Nr(i.inputHash,"Native checkpoint journal inputHash",64),c=D(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!pa.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==up(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function lO(e,t,i){let r=ha.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=gf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ie({root:e.projectRoot,file:r,maxBytes:br.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function uO(e,t){let i=sp(e,t),r=j(e,i);await T(r,i);try{return dp(await lp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function fp(e,t,i){let r=cp(e,t,i),n=j(e,r);await T(n,r);let a=await lp(n,r,"Native checkpoint manifest"),o=Jl(a,t);if(hp(e,o),up(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Sr(e,t){let i=kr(e,t),r=j(e,i);await T(r,i);try{let n=cO(await lp(r,i,"Native checkpoint journal"),t);return hp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ob(e,t,i,r){let n=Jl(i,t);hp(e,n);let a=up(n),o=cp(e,t,a),s=j(e,o);await T(s,o);try{let c=await fp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await te(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function hp(e,t){for(let i of t.artifacts){let r=gf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Hb(e,t){let i=dp(t,t.change),r=await fp(e,i.change,i.manifestHash),n=D(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=sp(e,t.change),o=j(e,a);await T(o,a),await te(a,i,{containedRoot:o})}async function Db(e){let t;try{t=await uO(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:sp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await fp(e.paths,e.name,t.manifestHash);let a=D(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await lO(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:cp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Fb(e,t,i){let r=await Sr(e,t);if(!r)return null;if(await Ob(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await xl(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Hb(e,r.checkpoint),await i?.afterProgressWritten?.(r),await dO.rm(kr(e,t),{force:!0}),r}async function Mb(e,t,i){return he(e,`continue checkpoint ${t}`,()=>nn(e,t,`continue checkpoint ${t}`,async()=>(await ql(e,t),Fb(e,t,i))))}import{constants as pp,promises as _t}from"node:fs";import ma from"node:path";var fO=/^[a-f0-9]{64}$/u,hO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,os=512*1024;function pO(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Fe(i,r)?W(i,r):W(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mO(e,t){let i=ma.resolve(e),r=ma.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...ma.relative(i,r).split(ma.sep).filter(Boolean)]){o&&(a=ma.join(a,o));let s=await _t.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await _t.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Lb(e){for(let t of e){let i=await _t.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!pO(t,i)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function vO(e){if(!fO.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function gO(e){let t=hO.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function wO(e,t,i){return Xi(H(e,t),vO(i))}async function yO(e,t,i){let r=await mO(i,ma.dirname(e)),n=await _t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>os)throw new Error(`Native check receipt exceeds ${os} bytes`);let[a,o]=await Promise.all([_t.realpath(t),_t.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":pp.O_RDONLY|pp.O_NOFOLLOW|pp.O_NONBLOCK,c=await _t.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await Lb(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Gl(n,l)||!Gl(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=os+1-h,P=await c.read(v,0,Math.min(v.length,y),null);if(P.bytesRead===0)break;if(h+=P.bytesRead,h>os)throw new Error(`Native check receipt exceeds ${os} bytes`);f.push(Buffer.from(v.subarray(0,P.bytesRead)))}let[p,m,b]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await Lb(r),!m.isFile()||m.isSymbolicLink()||b!==o||!$(a,b)||!Gl(l,p)||!Gl(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Bb(e,t,i){let r=gO(i),n=H(e,t),a=wO(e,t,r),o=j(e,a);await T(o,a);let s=jl(await yO(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var ss=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var b2=64*1024;var k2=3600*1e3;var S2=EO(SO);var PO=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function qb(e,t){let i=[];for(let r of PO){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Vb(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Bb(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 Er=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function RO(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function xO(e){let t=RO(e.bundle.baseline),i=await dh(e.paths,t,{origin:"explicit",now:e.now});return Oh({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function zb(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await es(e.paths,e.state.name,e.state.implementation_scope),i=await fa({changeDir:re(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await xO({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Jb(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await zb(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 CO(e){let t=await ee({root:re(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:xw(t.text)}}function AO(e){let{receipt:t,implementationScope:i}=e,r=[],n=$h({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function _O(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:qh(e.implementationScope.scope.declaredArtifacts)}}async function Wb(e){let t=await ts(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=qb(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Er([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Vb({paths:e.paths,state:e.state,receipt:t});if(n){let a=AO({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function TO(e){let t=_O({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Wb({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Er)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Wb({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Er)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Er(i)}function mp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ul(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:mp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([zb(e),ua(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:mp(e.state.verification_result,"stale"),envelope:null};let r=await CO({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await TO({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:mp(e.state.verification_result,"invalid"),envelope:null}}}function jO(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Ub(e){try{return await IO.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $O(e,t){try{return(await ee({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function OO(e,t,i){let r=Cl(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Gb.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await $O(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ee({root:re(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function HO(e,t){return Ub(We(e,t))}async function Kl(e){let t=e.now??new Date,i=await je(e.paths,e.name),r=await vt(e.paths,e.name),n=await Pe(e.paths.projectRoot),a=jO(i.name,t),o=Gb.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>OO(e.paths,i.name,v))),Ul({paths:e.paths,state:i,now:t}),Dl(e.paths,i.name),Zn(e.paths,i.name),ea(e.paths,i.name),HO(e.paths,i.name),Ub(o)]);return hN({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as vp}from"node:fs";import Ti from"node:path";var DO="comet.native.archive-tree.v1",FO={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function Xb(e){let t={...FO,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function Kb(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function Yb(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function Qb(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await ft({root:e,directory:t,label:`Native Archive content directory ${Ti.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=Kb(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ti.join(t,u.name),f=Ti.relative(e,d).replaceAll("\\","/"),h=await vp.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){Yb(i,{ref:f,kind:"directory"},r,n),await Qb(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await ie({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);Yb(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await ft({root:e,directory:t,label:`Native Archive content directory ${Ti.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(Kb(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ti.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function Zb(e,t={}){let i=Xb(t);e=Ti.resolve(e);let r=await vp.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await Qb(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return D(`${DO}\0${o}`)}async function Yt(e,t={}){let i=Xb(t);e=Ti.resolve(e);let r;try{r=await vp.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ie({root:Ti.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ti.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await Zb(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Ye}from"node:fs";import Ee from"node:path";var wp=16*1024*1024,MO=256*1024,LO=16*1024,cs="comet.native.archive-cas.v1";function BO(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Ee.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function $e(e,t){let i=BO(e,t);return T(j(e,i),i)}function Pr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function va(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function st(e){let t=await Yt(e.target);if(!Pr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${va(t)}`);return t}async function yp(e,t){let i=await oi(e,t),r=await ie({root:e.runtimeDir,file:i.journal,maxBytes:MO,label:`Native Archive transaction journal ${t}`}),n=rl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Yl(e,t,i){let r=rl({...t,status:i}),n=await oi(e,r.id);return await te(n.journal,r,{containedRoot:e.runtimeDir}),r}function Xl(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function ek(e){return{...Xl(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Rr(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function qO(e,t){return Rr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Z(e){try{return await Ye.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mi(e){let t=await Ye.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=ek(t),r=await ie({root:j(e.paths,e.file),file:e.file,maxBytes:wp,label:e.label}),n=await Ye.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!qO(i,ek(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Xl(n),size:r.size}}function VO(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==cs||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:cs,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function vi(e,t,i,r){let n=await oi(e,t.id),a=Ee.join(n.backups,".cas"),o=`.${Ee.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Ee.join(a,`${i.id}.original.json`),postRecord:Ee.join(a,`${i.id}.post.json`),candidate:Ee.join(a,`${i.id}.candidate`),originalQuarantine:Ee.join(Ee.dirname(r),`${o}.original`),rollbackQuarantine:Ee.join(Ee.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Tt(e){if(!await Z(e.file))return null;let t=await ie({root:e.paths.runtimeDir,file:e.file,maxBytes:LO,label:`Archive CAS ${e.operation.id} ${e.role} record`});return VO(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Ql(e){let t=await Tt(e);if(t){if(!Rr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await ai({root:e.paths.runtimeDir,directory:Ee.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:cs,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await te(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Tt(e);if(!r||!Rr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function ke(e){let t=await mi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Rr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function WO(e){let t=await mi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Ql({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await ke({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function zO(e){if(!await Z(e.quarantine)||await Z(e.target))return;let t=await Wt({root:j(e.paths,e.target),directory:Ee.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Ye.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Ye.lstat(e.quarantine),Ye.lstat(e.target)]);if(!Rr(Xl(i),Xl(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Ye.unlink(e.quarantine),await t.verify()}async function nk(e){if(await Z(e.quarantine)){await ke({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Wt({root:j(e.paths,e.target),directory:Ee.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await ke({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await ke({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Ye.rename(e.target,e.quarantine),await t.verify(),await ke({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await zO(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function an(e){if(!await Z(e.file))return;await ke(e);let t=await Wt({root:j(e.paths,e.file),directory:Ee.dirname(e.file),label:e.label});await t.verify(),await ke(e),await Ye.unlink(e.file),await t.verify()}async function tk(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await $e(e,t.target),n=await $e(e,t.backup),a=await Yt(n);if(a!==null){if(!Pr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await st({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await or({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:wp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await st({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function ak(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await vi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await Z(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await ke({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await tk(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await Z(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await WO({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await ke({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await tk(e.paths,e.operation,e.hooks),await nk({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function ik(e){let t=await vi(e.paths,e.journal,e.operation,e.target);return await Z(t.candidate)?(await mi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await ai({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await or({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:wp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function JO(e){let t=e.operation.stagedHash,i=await vi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await Z(e.target))return await ke({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await Z(i.candidate)&&await an({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await Z(e.target)){let c=await ik(e),l=await mi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await mi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Rr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Ql({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await an({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await ik(e),a=await mi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await ai({root:j(e.paths,e.target),directory:Ee.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Wt({root:j(e.paths,e.target),directory:Ee.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await ke({paths:e.paths,file:n,operation:e.operation,record:{schema:cs,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Ye.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await mi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Rr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Ql({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await an({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function GO(e,t,i,r){let n=await $e(e,i.target),a=await $e(e,i.staged);if(await st({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await vi(e,t,i,n);(!await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await Z(n))&&await ak({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Yt(n);if(o!==null&&!Pr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${va(o)}`)}await JO({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await st({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function UO(e,t,i,r){let n=await $e(e,i.target);await ak({paths:e,journal:t,operation:i,target:n,hooks:r}),await st({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function KO(e,t){let i=await $e(e,t.source),r=await $e(e,t.target),[n,a]=await Promise.all([Yt(i),Yt(r)]);if(!(n===null&&Pr(a,t.expectedSourceHash,"directory"))){if(!Pr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${va(n)}, target=${va(a)}`);await Ye.mkdir(Ee.dirname(r),{recursive:!0}),await Ye.rename(i,r),await st({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function YO(e,t,i,r){return i.type==="write"?GO(e,t,i,r):i.type==="remove"?UO(e,t,i,r):KO(e,i)}function XO(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function QO(e,t,i,r){let n=await $e(e,i.target);if(i.type==="write"){let a=await $e(e,i.staged);await st({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await vi(e,t,i,n),s=await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await ke({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await st({target:await $e(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Tt({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await Z(o.originalQuarantine))await ke({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await st({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await st({target:await $e(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await vi(e,t,i,n),o=await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await Z(a.originalQuarantine))await ke({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await st({target:await $e(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await st({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function ok(e,t,i){let r=t.status==="prepared"?await Yl(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await cr(e,r.id),a=XO({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await QO(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Rt(e,r.id,"operation-started",l.id),await YO(e,r,l,i),await Rt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await yp(e,r.id),r}async function ZO(e){try{return await ke(e),!0}catch{return!1}}async function e0(e){await ke({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Wt({root:j(e.paths,e.target),directory:Ee.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await ke({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Ye.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await ke({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function gp(e){if(e.operation.type!=="write")return;let t=await vi(e.paths,e.journal,e.operation,e.target);if(!await Z(t.candidate))return;let i=await mi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await an({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:cs,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function t0(e,t,i,r){let n=await $e(e,i.target),a=await vi(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Tt({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await Z(a.candidate)&&await Z(n)){let l=await mi({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await mi({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Rr(l.identity,u.identity)&&(c=await Ql({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await Z(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await ke({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await Z(n)&&!(s!==null&&await ZO({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Yt(n);if(Pr(u,o)){await gp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await nk({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await Z(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await Z(n)){if(!s||!await Z(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await e0({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await Z(a.originalQuarantine)&&await an({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await Z(a.rollbackQuarantine)&&await an({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await gp({paths:e,journal:t,operation:i,target:n}),await st({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function i0(e,t){let i=await $e(e,t.source),r=await $e(e,t.target),[n,a]=await Promise.all([Yt(i),Yt(r)]);if(!(Pr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Pr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${va(n)}, target=${va(a)}`);await Ye.mkdir(Ee.dirname(i),{recursive:!0}),await Ye.rename(r,i)}}async function sk(e,t,i){let r=await cr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Yl(e,t,"rolling-back");await Rt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await i0(e,o):await t0(e,n,o,i));return await Rt(e,n.id,"rollback-completed"),n=await Yl(e,n,"rolled-back"),n}async function rk(e,t,i){let r=await $e(e,i.target);if(i.type==="write"){let n=await vi(e,t,i,r),a=await Tt({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await ke({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await st({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function r0(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await $e(e,i.target),n=await vi(e,t,i,r);if(await Z(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await rk(e,t,i),i.expectedTargetHash!==null){let a=await Tt({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await Z(n.originalQuarantine)&&await an({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await gp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await rk(e,t,i)}async function Zl(e,t,i){return i==="commit"&&await r0(e,t),await Rt(e,t.id,i),i==="commit"?Yl(e,t,"committed"):t}var vz=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as n0}from"fs";import a0 from"path";var Np="comet.selection.v2",o0=16*1024;function eu(e){return a0.join(e,".comet","current-change.json")}function s0(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ck(e){return e===null||typeof e=="string"}function c0(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(!s0(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&&!ck(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Np,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Np)throw new Error(`current change selection schema must be ${Np}`);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(!ck(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 bp(e){let t;try{let r=eu(e),{bytes:n}=await Br(r,o0,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...c0(t)}}async function lk(e){await n0.rm(eu(e),{force:!0})}async function uk(e,t,i){let r=await bp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await lk(e),!0)}import{promises as us}from"node:fs";import Ar from"node:path";var tu="skill-coordinated";function u0(e){return e.state_version+1}function d0(e){return e.map(t=>({...t,result:"pending",reason:null}))}function f0(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:tr(e.summary),completed_at:e.completedAt}}function kp(e){let t=St(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=On(t,f0({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return St({...r,phase:"build",status:"active",state_version:u0(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:d0(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as fk}from"node:fs";import ls from"node:path";function iu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ru(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function gi(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function dk(e,t){return e===null?null:gi(e,t)}function au(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function h0(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function p0(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function nu(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Sp(e,t){if(e===null)return null;let i=gi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Ep(e,t){let i=gi(e,t);if(!ls.isAbsolute(i))throw new Error(`${t} must be absolute`);return ls.resolve(i)}function m0(e,t){let i=`Native local checks[${t}]`,r=iu(e,i);if(ru(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>gi(l,`${i}.argv[${u}]`,!0)),a=nu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Sp(r.startedAt,`${i}.startedAt`),s=Sp(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=au(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:gi(r.id,`${i}.id`),name:gi(r.name,`${i}.name`),operationId:gi(r.operationId,`${i}.operationId`),status:a,repeatable:p0(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:au(r.executionCount,`${i}.executionCount`),argv:n,cwd:Ep(r.cwd,`${i}.cwd`),exitCode:h0(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:gi(r.log,`${i}.log`)}}function Pp(e){let t="Native local execution state",i=iu(e,t);if(ru(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Eo)throw new Error(`Native local execution schema must be ${Eo}`);let r=iu(i.workspace,"Native local workspace");ru(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=iu(i.execution,"Native local execution");ru(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Sp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:gi(o.operationId,"Native local execution.operationId"),stage:nu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:nu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:dk(o.executionId,"Native local execution.executionId"),status:nu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:au(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(m0);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Eo,change:gi(i.change,"Native local change"),basedOnStateVersion:au(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ep(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ep(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:dk(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function on(e){return Pp({schema:Eo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:ls.resolve(e.projectRoot),worktreeRoot:ls.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ou(e){let t;try{t=await fk.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Pp(i)}async function xr(e,t,i={}){let r=Pp(t);await fk.mkdir(ls.dirname(e),{recursive:!0}),await te(e,r,i)}import{promises as v0}from"node:fs";function Cr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
199
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Ii(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function g0(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function w0(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===tu?tu:"host-attested")}function y0(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${Ii(o.id)} | ${Ii(o.result)} | ${Ii(o.source)} | ${Ii(o.text)} | ${Ii(Cr(o.reason))} |`).join(`
200
- `),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(Cr).join(" ");return`| ${Ii(Cr(o.name))} | ${Ii(s||"—")} | ${Ii(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
201
- `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${Cr(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
202
- `),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${Cr(o)}`).join(`
203
- `),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${Ii(Cr(o.summary))} | ${o.completed_at} |`)].join(`
190
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Fo(p),p}async function xl(e){let t=await gN(e),i=ia(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await te(i,t,{containedRoot:r}),t}async function wt(e,t){let i=await mN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Fo(i),i)}async function wN(e){return await Ah(e.paths,e.name)?xl(e):null}async function Lo(e){Fo(e.identity);let t=await gN({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),xh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function ra(e){if(Fo(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 Lo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ae(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function yN(e,t){let i=await wt(e,t);if(i===null)return null;let r=await ra({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var bN=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],JI=new Set(bN),kN=new Set([...bN,"minimum_runtime_version","revision"]),GI=new Set([...kN,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),UI=new Set(["capability","operation","source","base_hash"]),KI=new Set(["shape","build","verify","archive"]),YI=new Set(["implicit","confirmed"]),XI=new Set(["pending","pass","fail"]),Re="comet-state.yaml",Th=/^[a-f0-9]{64}$/u,SN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QI=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Bo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},tn=class extends Error{constructor(i,r){super(i!==ge||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},qo=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Vo=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},na=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},qV=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
191
+ `);function zo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function EN(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Al(e){if(!SN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ZI(e){if(!SN.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function PN(e,t){if(e.length===0||li.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function ej(e,t){let i=zo(e,`spec_changes[${t}]`);if(EN(i,UI,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(ZI(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&PN(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Th.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Th.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function tj(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 Ih(e,t){if(EN(e,t,Re),typeof e.name!="string")throw new Error("Native change name is required");if(Al(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"||!KI.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&&!YI.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(ej),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!XI.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&PN(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!tj(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 Kr(e){let t=zo(e,Re);if(t.schema!==Ue)throw new Error(`Expected ${Ue}`);return{schema:Ue,...Ih(t,JI)}}function Wo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _h(e,t,i){if(e===null)return null;let r=typeof e=="string"?QI.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function ij(e){if(e==null)return null;if(typeof e!="string"||!Th.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function rj(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ai(e){let t=zo(e,Re);if(t.schema!==we)throw new Error(`Expected ${we}`);if(Wo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${we} minimum_runtime_version must be 2`);return{schema:we,minimum_runtime_version:2,revision:Wo(t.revision,"Native v2 revision"),...Ih(t,kN)}}function ot(e){let t=zo(e,Re);if(t.schema!==ge){if(t.schema===Ue||t.schema===we){let o=t.schema===Ue?Kr(t):ai(t);throw new Bo(o.name,o.schema)}throw new tn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Wo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new tn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Wo(t.revision,"Native revision"),n=Ih(t,GI),a=ij(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ge,minimum_runtime_version:3,revision:r,verification_protocol:rj(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_h(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_h(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_h(t.partial_allowance,"Native partial_allowance","allowances")}}function RN(e){let t=zo(e,Re);if(t.schema===Ue){let n=Kr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema===we){let n=ai(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ge}`}}if(t.schema!==ge){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new tn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Wo(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new tn(t.schema,i).message};let r=ot(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function en(e){let t=ot(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 _l(e){let t=ai(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function re(e,t){Al(t);let i=li.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function aa(e,t){let i=H(e,t),r=li.join(i,"schema-migration.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await NN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function oa(e,t){let i=H(e,t),r=li.join(i,"checkpoint-journal.json");await T($(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await NN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var nj=256*1024;async function Tl(e,t=li.dirname(e)){let i=li.relative(t,e).split(li.sep).join("/"),r=await Q({root:t,ref:i,maxBytes:nj}),n=(0,Cl.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function ui(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=RN(await Tl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await aa(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await aj(e,r.state),r)}async function Il(e,t){let i=li.join(re(e,t),Re);await T(e.nativeRoot,i);let r=RN(await Tl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function aj(e,t){if(await Qn(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function $e(e,t){let i=await ui(e,t);if(i.status==="migration-required")throw new Bo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new tn(i.schema,i.minimumRuntimeVersion);return await yN(e,t),i.state}async function xN(e,t,i){let r={...t,schema:ge,minimum_runtime_version:3,revision:i+1},n=await Ry({expectedRevision:i,next:r,read:async()=>{let a=ot(await Tl(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ue(e,(0,Cl.stringify)(en(a))),equals:(a,o)=>JSON.stringify(en(a))===JSON.stringify(en(o)),conflict:a=>new qo(t.name,i,a)});return Object.assign(t,n),n}async function jl(e,t,i,r){if(await On(e.projectRoot),await aa(e,t.name))throw new Bo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await oa(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await $e(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Pl(e,t.name);let a=li.join(re(e,t.name),Re);return await T(e.nativeRoot,a),xN(a,t,i)}async function CN(e,t){return xN(e,t,t.revision)}async function AN(e){return ot(await Tl(e))}var TN=["Outcome","Scope","Non-goals","Acceptance examples"],oj=[...TN,"Constraints and invariants","Decisions","Open questions","Verification expectations"],sj=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],IN={maxFileBytes:uo};function jN(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
192
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function cj(e,t){let i=_N.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await jh.realpath(e),n=await jh.realpath(i);if(!$(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await jh.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Jo(e){return{valid:e.length===0,findings:e}}async function $h(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:IN.maxFileBytes})).text}catch(o){return Jo([{code:"brief-missing",message:o.message,path:t}])}let n=jN(r);for(let o of oj)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of TN)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Jo(i)}async function Oh(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:IN.maxFileBytes})).text}catch(a){return Jo([{code:"verification-missing",message:a.message,path:t}])}let n=jN(r);for(let a of sj)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Jo(i)}function $l(e,t){return _N.join(e.specsDir,t,"spec.md")}async function $N(e,t){let i=[],r=re(e,t.name);for(let n of t.spec_changes){let a=$l(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await Gt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await cj(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Jo(i)}import{promises as p0}from"node:fs";import gk from"node:path";import ON from"node:path";var lj="comet.native.archive-preflight.v1",uj="comet.native.archive-preflight.v1",dj="comet.native.archive-operation.v1",fj=/^[a-f0-9]{64}$/u,HN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Ol(e,t){return e<t?-1:e>t?1:0}function pj(e,t){if(typeof e!="string"||!fj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function xi(e,t){return e===null?null:pj(e,t)}function mj(e,t){let i=ON.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||ON.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 vj(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function gj(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function wj(e,t){if(!HN.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=xi(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=xi(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=xi(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function yj(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:xi(e.contractHash,"Native archive contract hash"),acceptanceHash:xi(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:xi(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:xi(e.reportHash,"Native archive report hash"),envelopeHash:xi(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:xi(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 Nj(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!hj.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(Ol);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function bj(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(Ol)}function DN(e){if(!HN.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(wj).sort((l,u)=>Ol(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:M(dj,l)})),r=yj(e.evidence),n=gj(e.workspace),a=[...new Set([...Nj(e.findingCodes??[]),...bj({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(Ol),o=vj(e.revision),s=mj(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:lj,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:M(uj,c)}}import{createHash as kj}from"node:crypto";import MN from"node:path";var Sj="comet.native.conflict-radar.v1",st=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}),Ej="comet.native.conflict-radar.v1",Pj="comet.native.conflict-radar-signals.v1",Rj=/^[a-f0-9]{64}$/u,BN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xj=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),Cj=new Set(["capability","operation","baseHash"]),Aj=new Set(["path","kind"]);function sa(e,t){return e<t?-1:e>t?1:0}function Hh(e){return Buffer.byteLength(e,"utf8")}function Dh(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function Mh(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(Hh(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function _j(e,t){let i=Mh(e,t,st.maxArtifactPathBytes),r=MN.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||MN.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function qN(e,t){if(typeof e!="string"||!Rj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Tj(e,t){let i=Dh(e,Cj,t),r=Mh(i.capability,`${t} capability`,st.maxCapabilityBytes);if(!BN.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:qN(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function Ij(e,t){let i=Dh(e,Aj,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:_j(i.path,`${t} path`),kind:i.kind}}function jj(e,t){let i=Dh(e,xj,`Conflict radar change ${t}`),r=Mh(i.name,`Conflict radar change ${t} name`,st.maxNameBytes);if(!BN.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>st.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>st.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>Tj(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>sa(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>Ij(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>sa(c.path,l.path)||sa(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:qN(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function $j(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>st.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(jj).sort((n,a)=>sa(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>st.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>st.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function Oj(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 Hj(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function Dj(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function Mj(e,t){let i=[],r=kj("sha256").update(`${Pj}
193
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(So(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<st.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(Oj(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Hj(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:Dj(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function FN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function Fj(e,t){return FN(e.classification)-FN(t.classification)||sa(e.left,t.left)||sa(e.right,t.right)}function LN(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:Sj,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function VN(e){let t=$j(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(Mj(t[s],t[c]));i.sort(Fj);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=M(Ej,{changes:t,relationships:r}),a=i.slice(0,st.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=LN(t,i,a,n);for(;a.length>0&&Hh(JSON.stringify(o))>st.maxSerializedBytes;)a=a.slice(0,-1),o=LN(t,i,a,n);if(Hh(JSON.stringify(o))>st.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as Y$}from"node:crypto";import{promises as Xt}from"node:fs";import hi from"node:path";import{createHash as XN}from"node:crypto";import WN from"path";var Fh="comet.native.implementation-scope.v2",QN="comet.native.content-snapshot-projection.v1",Go="comet.native.content-snapshot-projection.v1",ZN="comet.native.implementation-scope.v2",Lj="comet.native.unresolved-scope-id.v1",Bj="comet.native.scope-detail-overflow.v1",qj="comet.native.snapshot-projection-overflow.v2",Vh=/^[a-f0-9]{64}$/u,nn=1024*1024,Vj=128,Wj=128;function Ve(e,t){return e<t?-1:e>t?1:0}function Lh(e){if(!Vh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function zj(e,t){return e===t?0:e===null?-1:t===null?1:Ve(e,t)}function gr(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=WN.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||WN.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function eb(e,t){return e==="."?e:gr(e,t)}function ca(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function Jj(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:gr(e.path,`${t} path`),hash:e.hash,size:ca(e.size,`${t} size`),type:"file"}}function Gj(e,t){return{path:eb(e.path,`${t} path`),size:e.size===null?null:ca(e.size,`${t} size`),type:e.type,reason:e.reason}}function Uj(e,t){return Ve(e.path,t.path)||Ve(e.hash,t.hash)||e.size-t.size}function Kj(e,t){return Ve(e.path,t.path)||Ve(e.reason,t.reason)||Ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ko(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
194
+ `,"utf8")}function vr(e,t,i){let r=`${t}
195
+ ${So(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function Yj(e){if(Ko(e)<=nn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=XN("sha256");a.update(`${qj}
196
+ `),e.omissionOverflow&&vr(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,vr(a,"omission",f)},s=f=>{r+=1,n+=1,vr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Ko(u)>nn;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function Bh(e){let t=Pi(e),i=t.entries.map((n,a)=>Jj(n,`Snapshot entry ${a}`));if(i.sort(Uj),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>Gj(n,`Snapshot omission ${a}`));return r.sort(Kj),Yj({schema:QN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Yo(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:gr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>Ve(i.path,r.path)||Ve(i.kind,r.kind))}function Xo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function zN(e){return e?{hash:e.hash,size:e.size}:null}function Wh(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ve(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:zN(c),after:zN(l)})}}function tb(e,t){return{...e,attributedTo:t.filter(i=>Xo(i,e.path))}}function zh(e){let t=Yo(e.declaredArtifacts),i=[];return Wh(e.baseline,e.current,r=>{i.push(tb(r,t))}),i}function Ci(e,t){return{id:`scope:${M(Lj,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function Xj(e,t){let i=t.omitted.map(r=>Ci({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(Ci({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Ci({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 JN(e,t){return Xj(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function qh(e,t){return Ve(e.kind,t.kind)||Ve(e.source,t.source)||zj(e.path,t.path)||Ve(e.id,t.id)}function Qj(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(qh)}function ib(e){return[...new Set(e.map((t,i)=>gr(t,`Git path ${i}`)))].sort(Ve)}function GN(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function Zj(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function rb(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=ib(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:GN(e.baseCommit,"Native external drift base commit"),targetBranch:Zj(e.targetBranch,"Native external drift target branch"),targetCommit:GN(e.targetCommit,"Native external drift target commit"),paths:t}}function nb(e){if(typeof e.contractHash!="string"||!Vh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Yo(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:ib(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:rb(e.externalDrift)}}}function e$(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return Wh(e,t,p=>{let v=i.some(h=>Xo(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<Vj){let h=tb(p,i),m=Ko(h);l+m<=nn?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function ab(e,t){return Ci({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 t$(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:ca(Number(t[1]),"Scope overflow change count"),unresolved:ca(Number(t[2]),"Scope overflow unresolved count"),unattributed:ca(Number(t[3]),"Scope overflow unattributed count")},r=rn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(ab(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function i$(e){let t=XN("sha256");t.update(`${Bj}
197
+ `);let i=0;Wh(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){vr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Xo(o,n.path)&&(a+=1,vr(t,"change-attribution",o));vr(t,"change-end",{attributionCount:a}),a===0&&vr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&vr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function ob(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=e$(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),w=new Set(o.changePaths),g=i.externalDrift.paths.filter(P=>!w.has(P)||n.some(D=>Xo(D,P)));if(g.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${g.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=M(Go,e),c=M(Go,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=Wj)break;l.push(Ci({kind:"snapshot-omission",source:R,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${R} snapshot omitted ${g.path}: ${g.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...JN("baseline",e),...JN("current",t),...o.totalChanges===0&&a===null?[Ci({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>R.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!R.has(w))}},v=R=>{let w=o.candidates.slice(0,R.detailedChangeCount),g=w.filter(Dt=>Dt.attributedTo.length===0&&!u.has(Dt.path)),P=o.totalChanges-w.length,D=o.totalUnattributed-g.length,O=d-R.detailedOmissionCount,De=D+O,ce=[...g.map(Dt=>Ci({kind:"unattributed-change",source:"implementation-scope",path:Dt.path,evidence:{after:Dt.after,before:Dt.before,changeKind:Dt.kind}},`Changed path is not covered by a declared artifact: ${Dt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...De>0?[ab(R.overflowHash,{changes:P,unattributed:D,unresolved:De})]:[]],Z=Qj(ce),Zt=R.includeGitAdvisory?p():void 0;return{schema:Fh,contractHash:r,baselineProjectionRef:Lh(s),baselineProjectionHash:s,currentProjectionRef:Lh(c),currentProjectionHash:c,complete:Z.length===0,declaredArtifacts:n,changes:w,unattributed:g,unresolvedScopes:Z,noCodeReason:a,...Zt?{gitAdvisory:Zt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,N=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let R=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:y});if(Ko({...R,scopeHash:y})<=nn)break;if(N){N=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let S=o.totalChanges>h||d>m?i$({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,k=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:N,overflowHash:S}),b={...k,scopeHash:M(ZN,k)};if(Ko(b)>nn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function Jh(e){let t=Bh(e.baseline),i=Bh(e.current),r=nb(e);return{authority:r,baseline:t,current:i,scope:ob(t,i,r)}}var r$=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function rn(e,t){if(typeof e!="string"||!Vh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function UN(e,t,i){let r=Lh(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function la(e,t){let i=di(e,"Native snapshot projection");if(fi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==QN)throw new Error("Native snapshot projection schema is invalid");let r=Pi({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=Bh(r);if(M(Go,i)!==M(Go,n))throw new Error("Native snapshot projection is not canonical");let a=M(Go,n);if(t!==void 0&&rn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Gh(e,t){let i=di(e,`Declared artifact ${t}`);if(fi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:gr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function KN(e,t){if(e===null)return null;let i=di(e,t);return fi(i,["hash","size"],[],t),{hash:rn(i.hash,`${t} hash`),size:ca(i.size,`${t} size`)}}function YN(e,t){let i=di(e,`Implementation change ${t}`);if(fi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(Gh),n=Yo(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=KN(i.before,`Implementation change ${t} before`),o=KN(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:gr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function n$(e,t){let i=di(e,`Unresolved scope ${t}`);fi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?eb(i.path,`Unresolved scope ${t} path`):gr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Uo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>gr(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function sb(e){let t=di(e,"Native implementation external drift");if(fi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=Uo(t.paths,"Native external drift paths");return rb({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function ua(e){let t=di(e,"Native implementation scope"),i=[...r$].filter(g=>g!=="gitAdvisory"&&g!=="externalDrift");if(fi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Fh)throw new Error("Native implementation scope schema is invalid");let r=rn(t.contractHash,"Implementation scope contractHash"),n=rn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=UN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=rn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=UN(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(Gh);if(JSON.stringify(c)!==JSON.stringify(Yo(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(YN),u=[...l].sort((g,P)=>Ve(g.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(g=>g.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(g=>`${g.kind}:${g.path}`));if(l.some(g=>g.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(g=>JSON.stringify(g.attributedTo)!==JSON.stringify(c.filter(P=>Xo(P,g.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(YN),p=t.externalDrift===void 0?void 0:sb(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(g=>g.attributedTo.length===0&&!v.has(g.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(n$),N=m.filter(g=>g.kind==="scope-detail-overflow");if(N.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=N[0]===void 0?null:t$(N[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,S=[...h.map(g=>Ci({kind:"unattributed-change",source:"implementation-scope",path:g.path,evidence:{after:g.after,before:g.before,changeKind:g.kind}},`Changed path is not covered by a declared artifact: ${g.path}`)),...l.length+(y?.changes??0)===0&&E===null?[Ci({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=m.filter(g=>g.kind==="unattributed-change"||g.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(qh))||new Set(m.map(g=>g.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(S.sort(qh))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let g=di(t.gitAdvisory,"Implementation scope Git advisory");if(fi(g,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),g.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=Uo(g.changedPaths,"Git changed paths"),D=Uo(g.pathsPresentInSnapshotChanges,"Git present paths"),O=Uo(g.pathsAbsentFromSnapshotChanges,"Git absent paths"),De=[...D,...O].sort(Ve);if(JSON.stringify(De)!==JSON.stringify(P)||O.some(ce=>l.some(Z=>Z.path===ce)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:D,pathsAbsentFromSnapshotChanges:O}}let R={schema:Fh,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:E,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},w=rn(t.scopeHash,"Implementation scope scopeHash");if(M(ZN,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function a$(e){let t=di(e,"Native implementation scope authority");if(fi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(Gh);if(JSON.stringify(i)!==JSON.stringify(Yo(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=Uo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:sb(t.externalDrift),a=nb({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Qo(e){let t=di(e,"Native implementation scope bundle");fi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=a$(t.authority),r=la(t.baseline),n=la(t.current),a=ua(t.scope),o=ob(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function cb(e){let t=ua(e.scope);return Qo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import lb from"node:path";var o$=/\b(Bearer|Basic)\s+[^\s"']+/giu,s$=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,c$=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,l$=/\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,u$=/("(?:[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,d$=/(["'])((?:[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,f$=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function At(e){return e.replace(o$,"$1 [REDACTED]").replace(s$,"[REDACTED PRIVATE KEY]").replace(c$,"$1[REDACTED]@").replace(l$,"[REDACTED TOKEN]").replace(u$,'$1"[REDACTED]"').replace(d$,"$1$2$1$3$4[REDACTED]$4").replace(f$,"$1$2[REDACTED]")}var db=/^[a-f0-9]{64}$/u;var h$="comet.native.acceptance-trace.v2",p$="comet.native.partial-allowance.v1",m$="comet.native.verification-evidence.v2";function Ai(e,t){if(!db.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function fb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function hb(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 Uh(e,t,i=2e3){let r=At(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Zo(e,t){let i=lb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||lb.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 v$(e,t,i){let r=Zo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ii(r),a=r.toLowerCase(),o=i?Zo(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function Kh(e){let t=Zo(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 da(e,t){return e<t?-1:e>t?1:0}function Hl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Dl(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function pb(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 ub(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function g$(e){let t=Hl(e,"Native acceptance trace");if(Dl(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"||!db.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=Zo(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Hl(o,`Native acceptance trace entry ${s}`);if(Dl(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=>Kh(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(da))||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:Zo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Uh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>da(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Ai(t.traceHash,"Native acceptance trace hash");if(M(h$,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Ml(e){let t=Hl(e,"Native partial allowance");if(Dl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(da))||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:hb(t.change),scopeHash:Ai(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Uh(t.reason,"Partial allowance reason"),confirmedSummary:Uh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:fb(t.sourceRevision),confirmedAt:pb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Ai(t.allowanceHash,"Native partial allowance hash");if(M(p$,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function es(e){let t=Hl(e,"Native verification evidence");if(Dl(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=Ai(t.implementationScopeHash,"Native verification implementation scope hash"),r=g$(t.acceptanceTrace),n=Ai(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Ai(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Kh(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(da)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(da);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=>Kh(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(da)))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:hb(t.change),sourceRevision:fb(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ai(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:ub(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:v$(t.reportRef,"Native verification report ref"),reportHash:Ai(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:ub(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:pb(t.createdAt,"Native verification timestamp")},d=Ai(t.envelopeHash,"Native verification envelope hash");if(M(m$,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import mb from"node:path";var vb="comet.native.check-receipt.v1",w$="comet.native.check-receipt.v1",fa="scoped-text-safety",Yh=1,ct=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),y$=/^[a-f0-9]{64}$/u,N$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,b$="comet.native.checker-policy.v1",k$="comet.native.check-input.v1",S$=2048,gb=M(b$,{policy:fa,version:Yh,limits:ct,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),E$=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),wb=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Nb=["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"],P$=new Set(Nb);function wr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function _i(e,t){if(typeof e!="string"||!y$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function bb(e,t){let i=yt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function yb(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 R$(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>S$||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=mb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||mb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function x$(e){let t=wr(e,"Native check receipt checker");yr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=wr(t.limits,"Native check receipt limits");if(yr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==fa||t.version!==Yh||t.hash!==gb||i.maxFiles!==ct.maxFiles||i.maxFileBytes!==ct.maxFileBytes||i.maxTotalBytes!==ct.maxTotalBytes||i.maxIssues!==ct.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:fa,version:Yh,hash:gb,limits:{...ct}}}function C$(e){let t=wr(e,"Native check receipt contract");return yr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:_i(t.expectedHash,"Native check expected contract hash"),beforeHash:_i(t.beforeHash,"Native check before contract hash"),afterHash:_i(t.afterHash,"Native check after contract hash")}}function A$(e){let t=wr(e,"Native check receipt implementation");return yr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:_i(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:_i(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:_i(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:_i(t.afterSnapshotHash,"Native check after snapshot hash")}}function _$(e,t){let i=wr(e,`Native check batch ${t}`);yr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:yt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:yt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:yt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:yt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:yt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:yt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>ct.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>ct.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function T$(e){let t=wr(e,"Native check receipt counts");yr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:yt(t.filesSelected,"Native check filesSelected"),filesScanned:yt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:yt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:yt(t.bytesScanned,"Native check bytesScanned"),issueCount:yt(t.issueCount,"Native check issueCount"),recordedIssueCount:yt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(_$):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ct.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>ct.maxFiles||i.bytesScanned>ct.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function I$(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||wb.indexOf(e.kind)-wb.indexOf(t.kind)}function j$(e){if(!Array.isArray(e)||e.length>ct.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=wr(r,`Native check issue ${n}`);if(yr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!E$.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:R$(a.path,`Native check issue ${n} path`),line:bb(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(I$);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function $$(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!P$.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Nb.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function O$(e){return M(k$,e)}function Fl(e){let t=wr(e,"Native check receipt");if(yr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==vb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!N$.test(t.change))throw new Error("Native check receipt change name is invalid");let i=bb(t.sourceRevision,"Native check source revision"),r=x$(t.checker),n=C$(t.contract),a=A$(t.implementation),o=O$({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(_i(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=yb(t.startedAt,"Native check receipt startedAt"),c=yb(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=T$(t.counts),u=j$(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=$$(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>ct.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>ct.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:vb,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=_i(t.receiptHash,"Native check receipt content hash");if(M(w$,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var Qh="comet.native.verification-receipt.v3",H$=Qh,D$="comet.native.declared-artifacts.v1",M$=/^[a-f0-9]{64}$/u,F$=/^acceptance-[a-f0-9]{64}$/u,L$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,B$=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,q$=4096,V$=256,W$=1024;function ha(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 Nr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Ti(e,t){if(typeof e!="string"||!M$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=At(e).trim();if(!i||i.length>q$||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Xh(e,t){let i=Yt(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function ts(e,t,i=Yt,r=!1,n=V$){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function z$(e,t){if(typeof e!="string"||!F$.test(e))throw new Error(`${t} is invalid`);return e}function J$(e){let t=ha(e,"Native verification receipt bindings");if(Nr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!L$.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Ti(t.contractHash,"Native verification receipt contract hash"),scopeHash:Ti(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Ti(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Ti(t.artifactHash,"Native verification receipt artifact hash")}}function G$(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=B$.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function U$(e,t,i,r){let n=ha(t,`Native ${e} evidence`);if(e==="automated-check"){if(Nr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Xh(n.startedAt,"Native automated-check start time"),o=Xh(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=ha(n.worktree,"Native automated-check worktree");if(Nr(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=ha(n.afterFence,"Native automated-check after fence");if(Nr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Yt(n.executable,"Native automated-check executable"),args:ts(n.args,"Native automated-check arguments",Yt,!0),cwd:Yt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Yt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Ti(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Ti(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Ti(n.outputHash,"Native automated-check output hash"),outputSummary:Yt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Nr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=G$(n.checkReceiptRef);if(Ti(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:ts(n.subjects,"Native static inspection subjects",Yt,r==="required-check"),rule:Yt(n.rule,"Native static inspection rule"),resultSummary:Yt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Nr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:ts(n.steps,"Native manual evidence steps"),observations:ts(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function K$(e){let t=ha(e,"Native verification receipt");if(Nr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=Yt(t.actor,"Native verification receipt actor"),o=ts(t.acceptanceIds,"Native receipt acceptance IDs",z$,r==="required-check",W$).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Qh,kind:i,role:r,status:n,bindings:J$(t.bindings),acceptanceIds:o,actor:a,issuedAt:Xh(t.issuedAt,"Native verification receipt issue time"),evidence:U$(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==fa||s.actor!==`native-runtime:${fa}`))throw new Error("Native required check policy identity is invalid");return s}function Ll(e){let t=ha(e,"Native verification receipt");if(Nr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Qh)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=K$(r),a=Ti(t.receiptHash,"Native verification receipt hash");if(M(H$,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Zh(e){return M(D$,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Pb=/^[a-f0-9]{64}$/u,br=nn,IW=3*br;function ep(e,t){let i=hi.relative(e,t);return i===""||!hi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${hi.sep}`)}function X$(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Bl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ht(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kb(e){let t=await Xt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Xt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Q$(e,t){let i=hi.resolve(e),r=hi.resolve(t);if(!ep(i,r))throw new Error("Native evidence path is outside its change");let n=[await kb(i)],a=i;for(let o of hi.relative(i,r).split(hi.sep).filter(Boolean)){a=hi.join(a,o);let s=await kb(a);if(!ep(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Sb(e){for(let t of e){let i=await Xt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!X$(t,i)||await Xt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function Z$(e,t,i={}){let r=await Q$(t,hi.dirname(e));await i.afterParentChainCaptured?.();let n=await Xt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Xt.realpath(e);if(!ep(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Xt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await Sb(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Bl(s,n)||!Bl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>br)throw new Error(`Native evidence document exceeds ${br} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=br+1-d,N=await o.read(f,0,Math.min(f.length,m),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>br)throw new Error(`Native evidence document exceeds ${br} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),Xt.lstat(e),Xt.realpath(e)]);if(await Sb(r),!v.isFile()||v.isSymbolicLink()||h!==a||!Bl(s,p)||!Bl(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function ma(e,t){if(!Pb.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function Rb(e){return ma("reports",e)}async function eO(e,t,i,r,n){if(!Pb.test(i))throw new Error("Native report evidence hash is invalid");let a=await an({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||Y$("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 pa(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 tO(e,t,i,r,n){let a=ma(i,r);return n?hi.join(n,...a.split("/")):er(H(e,t),a)}async function an(e){let t=tO(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),Z$(t,i,e.hooks)}function Eb(e,t){return la(e,t)}function iO(e,t){let i=ua(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function rO(e,t,i){let r=Ml(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function nO(e,t,i){let r=es(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function aO(e,t,i,r=!1,n){let a=await ql(e,t,i.implementationScopeRef,void 0,n);if(r&&await eO(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await xb(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function is(e,t,i,r,n){let a=pa(i,"scopes"),o=iO(await an({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=pa(o.baselineProjectionRef,"snapshots"),c=pa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([an({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Eb(d,s)),an({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Eb(d,c))]);return cb({baseline:l,current:u,scope:o})}async function ql(e,t,i,r,n){return(await is(e,t,i,r,n)).scope}async function xb(e,t,i,r,n){let a=pa(i,"allowances");return rO(await an({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function rs(e,t,i,r,n){let a=pa(i,"receipts"),o=Ll(await an({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function va(e,t,i,r,n){let a=pa(i,"verifications"),o=nO(await an({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await aO(e,t,o,!1,n),o}var oO=4096;async function sO(e,t=st.maxChanges){try{let i=await pt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function Cb(e,t){let i=await $e(e,t),[r,n]=await Promise.all([i.implementation_scope?ql(e,t,i.implementation_scope):null,wt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function Vl(e,t,i={}){let n=(await sO(e,oO)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await Cb(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await Cb(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=VN([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as EO}from"fs";import PO from"path";import{isDeepStrictEqual as zl}from"util";var ga={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var cO=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function lO(e,t){return e<t?-1:e>t?1:0}function uO(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!cO.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(lO)}function tp(e=[]){return uO(e,"Native repair failed check IDs",ga.maxFailedCheckIds,!0)}function Ab(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function dO(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Ab(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Ab(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function ip(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(dO(r,a))break;i+=1,r=a}return i}function rp(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 _b="repairStagnation",Nt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},hO=/^[a-f0-9]{64}$/u;var pO=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),mO=["data","runId","sequence","timestamp","type"],Tb=["disposition","overrideSummaryHash","signatureHash"],vO=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Ib=12;function ap(e,t){return e<t?-1:e>t?1:0}function jb(e,t,i){let r=Object.keys(e).sort(ap);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Wl(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 ns(e,t){if(typeof e!="string"||!hO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function gO(e){if(!Array.isArray(e)||e.length>ga.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(ap)}function $b(e){if(typeof e!="string"||e.length===0||e.length>Nt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function np(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Nt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Nt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Nt.maxTextCharacters&&(!n||e.length>Nt.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Nt.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>np(s,t+1,i,`${r}[${c}]`));return}let a=Wl(e,r),o=Object.keys(a);if(o.length>Nt.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Nt.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");np(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function wO(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 yO(e,t,i){let r=Wl(e,`Native repair trajectory event ${t+1}`);if(jb(r,mO,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(wO(r.timestamp),typeof r.type!="string"||!pO.has(r.type))throw new Error("Native repair trajectory event type is invalid");if($b(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return np(r.data,0,n,"Native trajectory event data"),Wl(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function op(e){let t=Wl(e,"Native repair trajectory projection"),i=Object.keys(t).sort(ap),r=i.length===Tb.length&&i.every((l,u)=>l===Tb[u]);r||jb(t,vO,"Native repair trajectory projection");let n=ns(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:ns(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=ns(t.contractHash,"Native repair trajectory contract hash"),s=gO(t.failedAcceptanceIds),c=tp(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function NO(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 bO(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??Ib;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=ip({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<ga.warningAtConsecutiveFailures?"continue":a<ga.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function kO(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??Ib;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Ob(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Nt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=$b(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=yO(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Nt.maxTotalDataNodes||c>Nt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?ns(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?ns(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,_b)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=op(f[_b]);if(NO(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),bO(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");kO(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>ga.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Hb(e){return Ob(e).history}function Db(e){let t=Ob(e).latestProjection;return t?{...t}:null}var pi={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},as=F("comet-native-runtime:v3:scope-reopen"),SO=[{skillVersion:"3",skillHash:F("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function Mb(e){return e.skillVersion===pi.definition.metadata.version&&e.skillHash===as||SO.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var sp={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function kr(e){let i={sequence:(await Ye(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 nN(e.changeDir,e.run.trajectoryRef,i),i}async function on(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await aN(e.changeDir,e.run.checkpointRef,t),t}function Fb(e){return F(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Gb=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],RO=new Set(Gb),Ub=new Set([...Gb,"minimum_runtime_version","revision"]),xO=new Set([...Ub,"operation"]),CO=512*1024,cp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),AO=new Set([...cp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),os=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 We(e,t){return PO.join(H(e,t),"transition.json")}function _O(e){return`transition-${e}`}async function TO(e,t,i){let r=_O(t);return ir(e,r,i)}async function sn(e,t,i,r){let n=await TO(e,t,i);try{return await r()}finally{await rr(n)}}function Gl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function up(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Jl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){return zl(e,t)}function lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!AO.has(u)),a=[...cp].find(u=>!Object.hasOwn(i,u)),o=cp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(rp(i.summary,"Native transition journal event summary"),At(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(rp(i.noCodeReason,"Native transition journal event no-code reason"),At(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?op(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function IO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return lp({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return lp(e,t)}function dp(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?IO(e.eventData,e.evidenceHash):lp(e.eventData,e.evidenceHash),n=mr(e.nextRun),a=e.previousRun===null?null:mr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Lb(e,t,i=!1){if(e.skill!==pi.definition.metadata.name||(i?!Mb(e):e.skillVersion!==pi.definition.metadata.version||e.skillHash!==as)||e.orchestration!==pi.definition.orchestration.mode||e.pendingRef!==vt.pendingRef||e.trajectoryRef!==vt.trajectoryRef||e.contextRef!==vt.contextRef||e.artifactsRef!==vt.artifactsRef||e.checkpointRef!==vt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Bb(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 qb(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 fp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Lb(o,"next Run",r||a!==null),qb(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(Lb(a,"previous Run",!0),qb(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!zl(Bb(a),Bb(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function jO(e,t,i){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Kb(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Vb(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function hp(e,t,i,r,n=!1){let a=i.eventData,o=Vb(e),s=Vb(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&zl(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&zl(e.spec_changes,t.spec_changes),l=Fb({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=jO(e.name,a.summary,t.spec_changes),l=F(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function pp(e,t){let i=Gl(e);if(up(i,xO),i.schema!==ar)throw new Error(`Expected Native transition schema ${ar}`);let r=Jl(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${ar} minimum_runtime_version must be ${3}`);let n=Jl(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=dp(i,t),o=ot(i.previousState),s=ot(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(hp(o,s,a,i.operation),fp(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ar,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function $O(e,t){let i=Gl(e);if(up(i,RO),i.schema!==Ur)throw new Error(`Expected Native transition schema ${Ur}`);let r=dp(i,t,!0),n=Kr(i.previousState),a=Kr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return hp(n,a,r,Kb(n,a,r.eventData),!0),fp(n,a,r,!0),{schema:Ur,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function mp(e,t){let i=Gl(e);if(up(i,Ub),i.schema!==Ei)throw new Error(`Expected Native transition schema ${Ei}`);if(Jl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ei} minimum_runtime_version must be 2`);let n=Jl(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=dp(i,t,!0),o=ai(i.previousState),s=ai(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(hp(o,s,a,Kb(o,s,a.eventData),!0),fp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ei,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function OO(e,t){let i=Gl(e);if(i.schema===ar)return{status:"current",journal:pp(i,t)};if(i.schema===Ur)return{status:"migration-required",journal:$O(i,t)};if(i.schema===Ei)return{status:"migration-required",journal:mp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function vp(e,t){let i=We(e,t),r=j(e,i);await T(r,i);try{let n=await ie({root:r,file:i,maxBytes:CO,label:`Native transition journal ${t}`});return OO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Ii(e,t){let i=await vp(e,t);if(!i)return null;if(i.status==="migration-required")throw new os(t);return i.journal}function Wb(e,t){if(mi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(mi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function zb(e,t){if(mi(e,t.nextState))return"next";if(mi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function HO(e){let{journal:t}=e;return Yb({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 Yb(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Jb(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=HO({sequence:a.index+1,journal:t,type:a.event.type});if(!mi(Yb(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function Ul(e,t,i){if(await aa(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Pl(e,t);let r=await Ii(e,t);if(!r)return null;let n=H(e,t),a=Jb(await Ye(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Ie(n),$e(e,t)]),c=Wb(o,r),l=zb(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await Zr(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!mi(await Ie(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let m=await jl(e,r.nextState,r.previousState.revision);if(!mi(m,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!mi(await $e(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Ii(e,t);if(!u||!mi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Jb(await Ye(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await kr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await kr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await on({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[p,v]=await Promise.all([Ie(n),$e(e,t)]);Wb(p,{...r,previousRun:r.nextRun}),zb(v,{...r,previousState:r.nextState});let h=await Ii(e,t);if(!h||!mi(h,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await EO.rm(We(e,t),{force:!0}),r.nextState}async function Xb(e,t,i){return he(e,`continue transition ${t}`,()=>sn(e,t,`continue transition ${t}`,()=>Ul(e,t,i)))}import Qb from"node:path";var DO="comet.native.contract.v1",MO="comet.native.acceptance-set.v1",Zb=/^[a-f0-9]{64}$/u,ss={maxAcceptanceCriteria:Po.maxCriteria};function ek(e,t){let i=Qb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Qb.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 tk(e){return M("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
198
+ `))}function FO(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(Zb))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(Zb))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=ek(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:tk(e.markdown)},markdown:e.markdown}}function LO(e,t){return ik(e.id,t.id)}function ik(e,t){return e<t?-1:e>t?1:0}function rk(e){let t=ek(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(FO).sort((d,f)=>ik(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=zc(e.briefMarkdown,t,ss.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Jc(f,d.source,ss.maxAcceptanceCriteria-a.length)),a.push(...Gc(f,d.source,ss.maxAcceptanceCriteria-a.length)));if(a.sort(LO),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>ss.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${ss.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:tk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=M(MO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(DO,u)}}var Kl={maxSpecs:64,maxFileBytes:uo,maxTotalBytes:4*1024*1024};async function wa(e){if(e.specChanges.length>Kl.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Q({root:e.changeDir,ref:e.briefRef,maxBytes:Kl.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Q({root:e.changeDir,ref:n.source,maxBytes:Kl.maxFileBytes});if(i+=a.size,i>Kl.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:rk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as a0}from"node:child_process";import{promisify as o0}from"node:util";var $2=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as GO}from"fs";import ya from"path";var Er={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Na=/^[a-f0-9]{64}$/u;function Yl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xl(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Sr(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 nk(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function BO(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||ya.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=ya.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function wp(e,t){return ya.join(H(e,t),"checkpoints","progress.json")}function Pr(e,t){return ya.join(H(e,t),"checkpoint-journal.json")}function yp(e,t,i){if(!Na.test(i))throw new Error("Native checkpoint manifest hash is invalid");return ya.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function qO(e){if(!Na.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Np(e,t,i){let r=await ie({root:e,file:t,maxBytes:Er.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function VO(e,t){let i=Yl(e,`checkpoint manifest artifact ${t}`);Xl(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=BO(Sr(i.path,`checkpoint artifact ${t} path`,4096)),n=ii(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Na.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:gp(i.size,`checkpoint artifact ${t} size`)}}function Ql(e,t){let i=Yl(e,"Native checkpoint manifest");if(Xl(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>Er.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(VO),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=gp(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Er.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function bp(e){return F(JSON.stringify(Ql(e,e.change)))}function kp(e,t){let i=Yl(e,"Native progress checkpoint");if(Xl(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=nk(i.previousRevision,"Native checkpoint previousRevision"),a=nk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Sr(i.manifestHash,"Native checkpoint manifestHash",64);if(!Na.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=qO(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Sr(i.inputHash,"Native checkpoint inputHash",64);if(!Na.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Sr(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=gp(i.artifactCount,"Native checkpoint artifactCount");if(u>Er.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Sr(i.summary,"Native checkpoint summary"),f=Sr(i.nextAction,"Native checkpoint nextAction");if(At(d)!==d||At(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Sr(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function WO(e,t){let i=Yl(e,"Native checkpoint journal");if(Xl(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ot(i.previousState),n=ot(i.nextState),a=kp(i.checkpoint,t),o=Ql(i.manifest,t),s=Sr(i.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Na.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==bp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function zO(e,t,i){let r=ya.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,r)||$(e.nativeRoot,r)||$(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Af(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ie({root:e.projectRoot,file:r,maxBytes:Er.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function JO(e,t){let i=wp(e,t),r=j(e,i);await T(r,i);try{return kp(await Np(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Sp(e,t,i){let r=yp(e,t,i),n=j(e,r);await T(n,r);let a=await Np(n,r,"Native checkpoint manifest"),o=Ql(a,t);if(Ep(e,o),bp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Rr(e,t){let i=Pr(e,t),r=j(e,i);await T(r,i);try{let n=WO(await Np(r,i,"Native checkpoint journal"),t);return Ep(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ak(e,t,i,r){let n=Ql(i,t);Ep(e,n);let a=bp(n),o=yp(e,t,a),s=j(e,o);await T(s,o);try{let c=await Sp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await te(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function Ep(e,t){for(let i of t.artifacts){let r=Af(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function ok(e,t){let i=kp(t,t.change),r=await Sp(e,i.change,i.manifestHash),n=F(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=wp(e,t.change),o=j(e,a);await T(o,a),await te(a,i,{containedRoot:o})}async function sk(e){let t;try{t=await JO(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:wp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Sp(e.paths,e.name,t.manifestHash);let a=F(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await zO(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:yp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function ck(e,t,i){let r=await Rr(e,t);if(!r)return null;if(await ak(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await jl(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await ok(e,r.checkpoint),await i?.afterProgressWritten?.(r),await GO.rm(Pr(e,t),{force:!0}),r}async function lk(e,t,i){return he(e,`continue checkpoint ${t}`,()=>sn(e,t,`continue checkpoint ${t}`,async()=>(await Ul(e,t),ck(e,t,i))))}import{constants as Pp,promises as _t}from"node:fs";import ba from"node:path";var UO=/^[a-f0-9]{64}$/u,KO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,cs=512*1024;function YO(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Zl(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return ht(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function XO(e,t){let i=ba.resolve(e),r=ba.resolve(t);if(!$(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...ba.relative(i,r).split(ba.sep).filter(Boolean)]){o&&(a=ba.join(a,o));let s=await _t.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await _t.realpath(a);if(n.length>0&&!$(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function uk(e){for(let t of e){let i=await _t.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!YO(t,i)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function QO(e){if(!UO.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function ZO(e){let t=KO.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function e0(e,t,i){return er(H(e,t),QO(i))}async function t0(e,t,i){let r=await XO(i,ba.dirname(e)),n=await _t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>cs)throw new Error(`Native check receipt exceeds ${cs} bytes`);let[a,o]=await Promise.all([_t.realpath(t),_t.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Pp.O_RDONLY|Pp.O_NOFOLLOW|Pp.O_NONBLOCK,c=await _t.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await uk(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Zl(n,l)||!Zl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=cs+1-p,E=await c.read(v,0,Math.min(v.length,y),null);if(E.bytesRead===0)break;if(p+=E.bytesRead,p>cs)throw new Error(`Native check receipt exceeds ${cs} bytes`);f.push(Buffer.from(v.subarray(0,E.bytesRead)))}let[h,m,N]=await Promise.all([c.stat(),_t.lstat(e),_t.realpath(e)]);if(await uk(r),!m.isFile()||m.isSymbolicLink()||N!==o||!$(a,N)||!Zl(l,h)||!Zl(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function dk(e,t,i){let r=ZO(i),n=H(e,t),a=e0(e,t,r),o=j(e,a);await T(o,a);let s=Fl(await t0(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var ls=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Az=64*1024;var _z=3600*1e3;var Tz=o0(a0);var s0=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function fk(e,t){let i=[];for(let r of s0){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function hk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await dk(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 xr=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function c0(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 l0(e){let t=c0(e.bundle.baseline),i=await kh(e.paths,t,{origin:"explicit",now:e.now});return Jh({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function mk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await is(e.paths,e.state.name,e.state.implementation_scope),i=await wa({changeDir:re(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await l0({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function vk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await mk(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 u0(e){let t=await Q({root:re(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Yw(t.text)}}function d0(e){let{receipt:t,implementationScope:i}=e,r=[],n=zh({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function f0(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:Zh(e.implementationScope.scope.declaredArtifacts)}}async function pk(e){let t=await rs(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=fk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new xr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await hk({paths:e.paths,state:e.state,receipt:t});if(n){let a=d0({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function h0(e){let t=f0({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await pk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof xr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await pk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof xr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new xr(i)}function Rp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function eu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Rp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([mk(e),va(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:Rp(e.state.verification_result,"stale"),envelope:null};let r=await u0({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await h0({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Rp(e.state.verification_result,"invalid"),envelope:null}}}function m0(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function wk(e){try{return await p0.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function v0(e,t){try{return(await Q({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function g0(e,t,i){let r=$l(e,i.capability);if(!$(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=gk.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await v0(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Q({root:re(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function w0(e,t){return wk(We(e,t))}async function tu(e){let t=e.now??new Date,i=await $e(e.paths,e.name),r=await wt(e.paths,e.name),n=await Ne(e.paths.projectRoot),a=m0(i.name,t),o=gk.resolve(e.paths.nativeRoot,...a.split("/"));if(!$(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>g0(e.paths,i.name,v))),eu({paths:e.paths,state:i,now:t}),Vl(e.paths,i.name),aa(e.paths,i.name),oa(e.paths,i.name),w0(e.paths,i.name),wk(o)]);return DN({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as xp}from"node:fs";import ji from"node:path";var y0="comet.native.archive-tree.v1",N0={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function bk(e){let t={...N0,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function yk(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function Nk(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function kk(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await pt({root:e,directory:t,label:`Native Archive content directory ${ji.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=yk(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=ji.join(t,u.name),f=ji.relative(e,d).replaceAll("\\","/"),p=await xp.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){Nk(i,{ref:f,kind:"directory"},r,n),await kk(e,d,i,r,n,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await ie({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);Nk(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await pt({root:e,directory:t,label:`Native Archive content directory ${ji.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(yk(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${ji.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function Sk(e,t={}){let i=bk(t);e=ji.resolve(e);let r=await xp.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await kk(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return F(`${y0}\0${o}`)}async function Qt(e,t={}){let i=bk(t);e=ji.resolve(e);let r;try{r=await xp.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ie({root:ji.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${ji.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await Sk(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Xe}from"node:fs";import Pe from"node:path";var Ap=16*1024*1024,b0=256*1024,k0=16*1024,us="comet.native.archive-cas.v1";function S0(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Pe.resolve(n,...a.split("/"));if(!$(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Oe(e,t){let i=S0(e,t);return T(j(e,i),i)}function Cr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function ka(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function lt(e){let t=await Qt(e.target);if(!Cr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ka(t)}`);return t}async function _p(e,t){let i=await si(e,t),r=await ie({root:e.runtimeDir,file:i.journal,maxBytes:b0,label:`Native Archive transaction journal ${t}`}),n=ll(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function iu(e,t,i){let r=ll({...t,status:i}),n=await si(e,r.id);return await te(n.journal,r,{containedRoot:e.runtimeDir}),r}function ru(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function Ek(e){return{...ru(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ar(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function E0(e,t){return Ar(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ee(e){try{return await Xe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vi(e){let t=await Xe.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=Ek(t),r=await ie({root:j(e.paths,e.file),file:e.file,maxBytes:Ap,label:e.label}),n=await Xe.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!E0(i,Ek(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:ru(n),size:r.size}}function P0(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==us||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:us,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function gi(e,t,i,r){let n=await si(e,t.id),a=Pe.join(n.backups,".cas"),o=`.${Pe.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Pe.join(a,`${i.id}.original.json`),postRecord:Pe.join(a,`${i.id}.post.json`),candidate:Pe.join(a,`${i.id}.candidate`),originalQuarantine:Pe.join(Pe.dirname(r),`${o}.original`),rollbackQuarantine:Pe.join(Pe.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Tt(e){if(!await ee(e.file))return null;let t=await ie({root:e.paths.runtimeDir,file:e.file,maxBytes:k0,label:`Archive CAS ${e.operation.id} ${e.role} record`});return P0(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function nu(e){let t=await Tt(e);if(t){if(!Ar(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await oi({root:e.paths.runtimeDir,directory:Pe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:us,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await te(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Tt(e);if(!r||!Ar(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Se(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Ar(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function R0(e){let t=await vi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await nu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Se({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function x0(e){if(!await ee(e.quarantine)||await ee(e.target))return;let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Xe.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([Xe.lstat(e.quarantine),Xe.lstat(e.target)]);if(!Ar(ru(i),ru(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Xe.unlink(e.quarantine),await t.verify()}async function Ck(e){if(await ee(e.quarantine)){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Xe.rename(e.target,e.quarantine),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await x0(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function cn(e){if(!await ee(e.file))return;await Se(e);let t=await Jt({root:j(e.paths,e.file),directory:Pe.dirname(e.file),label:e.label});await t.verify(),await Se(e),await Xe.unlink(e.file),await t.verify()}async function Pk(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Oe(e,t.target),n=await Oe(e,t.backup),a=await Qt(n);if(a!==null){if(!Cr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await lt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await lr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Ap,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await lt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function Ak(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ee(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Se({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await Pk(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ee(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await R0({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await Pk(e.paths,e.operation,e.hooks),await Ck({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function Rk(e){let t=await gi(e.paths,e.journal,e.operation,e.target);return await ee(t.candidate)?(await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await oi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await lr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Ap,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function C0(e){let t=e.operation.stagedHash,i=await gi(e.paths,e.journal,e.operation,e.target),r=await Tt({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ee(e.target))return await Se({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ee(i.candidate)&&await cn({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ee(e.target)){let c=await Rk(e),l=await vi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ar(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await nu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await cn({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await Rk(e),a=await vi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await oi({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Se({paths:e.paths,file:n,operation:e.operation,record:{schema:us,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Xe.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await vi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Ar(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await nu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await cn({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function A0(e,t,i,r){let n=await Oe(e,i.target),a=await Oe(e,i.staged);if(await lt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await gi(e,t,i,n);(!await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ee(n))&&await Ak({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await Qt(n);if(o!==null&&!Cr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${ka(o)}`)}await C0({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await lt({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function _0(e,t,i,r){let n=await Oe(e,i.target);await Ak({paths:e,journal:t,operation:i,target:n,hooks:r}),await lt({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function T0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(n===null&&Cr(a,t.expectedSourceHash,"directory"))){if(!Cr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ka(n)}, target=${ka(a)}`);await Xe.mkdir(Pe.dirname(r),{recursive:!0}),await Xe.rename(i,r),await lt({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function I0(e,t,i,r){return i.type==="write"?A0(e,t,i,r):i.type==="remove"?_0(e,t,i,r):T0(e,i)}function j0(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function $0(e,t,i,r){let n=await Oe(e,i.target);if(i.type==="write"){let a=await Oe(e,i.staged);await lt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await gi(e,t,i,n),s=await Tt({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Se({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await lt({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Tt({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ee(o.originalQuarantine))await Se({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await lt({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await lt({target:await Oe(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await gi(e,t,i,n),o=await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ee(a.originalQuarantine))await Se({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await lt({target:await Oe(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await lt({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function _k(e,t,i){let r=t.status==="prepared"?await iu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await dr(e,r.id),a=j0({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await $0(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Rt(e,r.id,"operation-started",l.id),await I0(e,r,l,i),await Rt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await _p(e,r.id),r}async function O0(e){try{return await Se(e),!0}catch{return!1}}async function H0(e){await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Jt({root:j(e.paths,e.target),directory:Pe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Se({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Xe.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Se({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Cp(e){if(e.operation.type!=="write")return;let t=await gi(e.paths,e.journal,e.operation,e.target);if(!await ee(t.candidate))return;let i=await vi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await cn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:us,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function D0(e,t,i,r){let n=await Oe(e,i.target),a=await gi(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Tt({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Tt({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ee(a.candidate)&&await ee(n)){let l=await vi({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await vi({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Ar(l.identity,u.identity)&&(c=await nu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ee(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Se({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ee(n)&&!(s!==null&&await O0({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Qt(n);if(Cr(u,o)){await Cp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await Ck({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ee(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ee(n)){if(!s||!await ee(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await H0({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ee(a.originalQuarantine)&&await cn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ee(a.rollbackQuarantine)&&await cn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Cp({paths:e,journal:t,operation:i,target:n}),await lt({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function M0(e,t){let i=await Oe(e,t.source),r=await Oe(e,t.target),[n,a]=await Promise.all([Qt(i),Qt(r)]);if(!(Cr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Cr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ka(n)}, target=${ka(a)}`);await Xe.mkdir(Pe.dirname(i),{recursive:!0}),await Xe.rename(r,i)}}async function Tk(e,t,i){let r=await dr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await iu(e,t,"rolling-back");await Rt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await M0(e,o):await D0(e,n,o,i));return await Rt(e,n.id,"rollback-completed"),n=await iu(e,n,"rolled-back"),n}async function xk(e,t,i){let r=await Oe(e,i.target);if(i.type==="write"){let n=await gi(e,t,i,r),a=await Tt({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Se({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await lt({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function F0(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Oe(e,i.target),n=await gi(e,t,i,r);if(await ee(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await xk(e,t,i),i.expectedTargetHash!==null){let a=await Tt({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ee(n.originalQuarantine)&&await cn({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Cp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await xk(e,t,i)}async function au(e,t,i){return i==="commit"&&await F0(e,t),await Rt(e,t.id,i),i==="commit"?iu(e,t,"committed"):t}var EJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as L0}from"fs";import B0 from"path";var Tp="comet.selection.v2",q0=16*1024;function ou(e){return B0.join(e,".comet","current-change.json")}function V0(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ik(e){return e===null||typeof e=="string"}function W0(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(!V0(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&&!Ik(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Tp,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Tp)throw new Error(`current change selection schema must be ${Tp}`);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(!Ik(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 Ip(e){let t;try{let r=ou(e),{bytes:n}=await Wr(r,q0,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...W0(t)}}async function jk(e){await L0.rm(ou(e),{force:!0})}async function $k(e,t,i){let r=await Ip(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await jk(e),!0)}import{promises as ps}from"node:fs";import Ir from"node:path";var Dp=mn(qr(),1);import{promises as Fk}from"node:fs";import It from"node:path";import{execFileSync as z0}from"node:child_process";var J0=3e4,G0=8*1024*1024,jp=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function U0(e,t){try{return z0("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:J0,maxBuffer:G0,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new jp(e,t,r)}}function $p(e,t){return U0(e,t).trim()}var Ok="children.yaml",Op="comet.native.children.v1",ds="comet.native.children.v2",K0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Y0=new Set(["schema","children"]),X0=new Set(["schema","acceptance_index","children"]),Q0=new Set(["name","depends_on","covers"]);function cu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function su(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0)throw new Error(`${i} fields are invalid`)}function Hk(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function Hp(e,t){let i=It.normalize(It.resolve(e)),r=It.normalize(It.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Z0(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function Dk(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Mp(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function eH(e){let t=cu(e,"Native children acceptance_index"),i={};for(let[r,n]of Object.entries(t)){let a=cu(n,`Native children acceptance_index.${r}`);if(su(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function tH(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text)throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog`)}}function iH(e,t,i={}){let r=(0,Dp.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=cu(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a===ds?su(n,X0,"Native children contract"):su(n,Y0,"Native children contract"),a!==Op&&a!==ds)throw new Error(`Native children schema must be ${Op} or ${ds}`);if(!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let o=n.children.map((l,u)=>{let d=cu(l,`Native child ${u}`);if(su(d,Q0,`Native child ${u}`),typeof d.name!="string"||!K0.test(d.name))throw new Error(`Native child ${u} name is invalid`);return{name:d.name,depends_on:Hk(d.depends_on,`Native child ${d.name} depends_on`),covers:Hk(d.covers,`Native child ${d.name} covers`)}}),s=o.map(({name:l})=>l);if(new Set(s).size!==s.length)throw new Error("Native child names must be unique");let c=new Set(s);for(let l of o){let u=l.depends_on.filter(d=>!c.has(d));if(u.length>0)throw new Error(`Native child ${l.name} depends on unknown child: ${u.join(", ")}`)}if(Z0(o),a===ds){let l=eH(n.acceptance_index);if(tH(l,t,i),t){let u=Object.keys(l);Dk(o,u,u)}return{schema:ds,acceptance_index:l,children:o}}return t&&Dk(o,t),{schema:Op,children:o}}async function Fp(e){let t=It.join(e.changeDir,Ok);try{await Fk.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await Q({root:e.changeDir,ref:Ok});return{contract:iH(i.text,e.acceptanceIds,e.validation),size:i.size}}function Lp(e){return M("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function rH(e){let t=Cn(e.projectRoot);t.some(r=>Hp(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>It.resolve(n)))]){let n=await Ne(r);n&&i.push({projectRoot:r,paths:await Le(r,n.native.artifact_root),parent:Hp(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function nH(e,t){let i=It.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ge(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function aH(e,t){let i;try{i=await Fk.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=It.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ge(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function oH(e,t,i){let r=It.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${It.sep}`))return null;let n=r.split(It.sep).join("/");try{let a=(0,Dp.parseDocument)($p(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:rt(a.toJS({mapAsMap:!1}))}catch{return null}}function sH(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Mk(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function fs(e){let t=It.join(e.paths.changesDir,e.state.name),i=await Fp({changeDir:t,validation:Mp(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{}});if(!i)return e.state.children_contract_hash?{contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let r=Lp({acceptance:e.state.acceptance,children:i.contract}),n=e.state.phase!=="shape"&&e.state.children_contract_hash===r,a=await rH(e.paths),o=e.state.workspace.change_branch,s=new Set(i.contract.children.map(({name:h})=>h)),c=new Map,l=new Map;for(let h of a){let m=h.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await aH(h,s)){let y={...N,source:h,committedState:oH(h,N.file,m)};c.set(N.state.name,[...c.get(N.state.name)??[],y])}for(let N of s){let y=await nH(h,N);y&&l.set(N,[...l.get(N)??[],{source:h,state:y}])}}let u=new Map;for(let h of i.contract.children){let m=(c.get(h.name)??[]).find(({source:E,committedState:S})=>E.parent&&S?.name===h.name&&Mk(S,o));if(m){u.set(h.name,{kind:"done",phase:m.state.phase,projectRoot:m.source.projectRoot,message:null});continue}let N=c.get(h.name)?.[0];if(N){u.set(h.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=l.get(h.name)??[];y.length>1?u.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&u.set(h.name,sH(y[0].state,y[0].source,o))}let d=new Map(i.contract.children.map(h=>[h.name,h])),f=new Map,p=h=>{let m=f.get(h);if(m)return m;let N=d.get(h),E=N.depends_on.map(p).every(({status:g})=>g==="done"),S=u.get(h),k=S?.kind==="active"&&E?N.depends_on.filter(g=>!(c.get(g)??[]).some(({source:P,committedState:D})=>Hp(P.projectRoot,S.projectRoot)&&D?.name===g&&Mk(D,o))):[],b,R=S?.message??null;S?.kind==="done"?(b=E?"done":"blocked",E||(R=`Native child ${h} was merged before its dependencies`)):S?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(R=`Native child ${h} does not include merged dependencies: ${k.join(", ")}`):R=`Native child ${h} started before its dependencies merged`):S?.kind==="blocked"?b="blocked":(b=n&&E?"ready":"pending",n||(R="Parent Shape confirmation is required"));let w={name:h,dependsOn:[...N.depends_on],covers:[...N.covers],status:b,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:R};return f.set(h,w),w},v=i.contract.children.map(({name:h})=>p(h));return{contractHash:r,confirmed:n,parentBranch:o,children:v,readyChildren:v.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:v.every(({status:h})=>h==="done")}}var lu="skill-coordinated";function lH(e){return e.state_version+1}function uH(e){return e.map(t=>({...t,result:"pending",reason:null}))}function dH(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:nr(e.summary),completed_at:e.completedAt}}function Bp(e){let t=rt(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Bn(t,dH({state:t,outcome:"recovery",summary:e.reason,completedAt:i}));return rt({...r,phase:"build",status:"active",state_version:lH(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:uH(t.acceptance),loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as Bk}from"node:fs";import hs from"node:path";function uu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function du(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function wi(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function Lk(e,t){return e===null?null:wi(e,t)}function hu(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function fH(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function hH(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function fu(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function qp(e,t){if(e===null)return null;let i=wi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Vp(e,t){let i=wi(e,t);if(!hs.isAbsolute(i))throw new Error(`${t} must be absolute`);return hs.resolve(i)}function pH(e,t){let i=`Native local checks[${t}]`,r=uu(e,i);if(du(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>wi(l,`${i}.argv[${u}]`,!0)),a=fu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=qp(r.startedAt,`${i}.startedAt`),s=qp(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=hu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:wi(r.id,`${i}.id`),name:wi(r.name,`${i}.name`),operationId:wi(r.operationId,`${i}.operationId`),status:a,repeatable:hH(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:hu(r.executionCount,`${i}.executionCount`),argv:n,cwd:Vp(r.cwd,`${i}.cwd`),exitCode:fH(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:wi(r.log,`${i}.log`)}}function Wp(e){let t="Native local execution state",i=uu(e,t);if(du(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ro)throw new Error(`Native local execution schema must be ${Ro}`);let r=uu(i.workspace,"Native local workspace");du(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=uu(i.execution,"Native local execution");du(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=qp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:wi(o.operationId,"Native local execution.operationId"),stage:fu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:fu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Lk(o.executionId,"Native local execution.executionId"),status:fu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:hu(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(pH);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Ro,change:wi(i.change,"Native local change"),basedOnStateVersion:hu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Vp(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Vp(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Lk(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function ln(e){return Wp({schema:Ro,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:hs.resolve(e.projectRoot),worktreeRoot:hs.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function pu(e){let t;try{t=await Bk.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return Wp(i)}async function _r(e,t,i={}){let r=Wp(t);await Bk.mkdir(hs.dirname(e),{recursive:!0}),await te(e,r,i)}import{promises as mH}from"node:fs";function Tr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
199
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function $i(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function vH(e){return e.verification?.assurance==="semantic-verification-unavailable"?"Semantic verification unavailable, user confirmation required":e.verification?.assurance==="user-confirmed-degraded"?"Passed with user-confirmed degraded assurance":e.verification_result==="pass"?e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?"Passed, user confirmation required":"Passed":e.verification_result==="blocked"?"Blocked":e.verification_result==="fail"?"Failed":"Pending"}function gH(e){return e.verification?.assurance??(e.builder_handoff?.identity_provider===lu?lu:"host-attested")}function wH(e){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let t=e.acceptance.map(o=>`| ${$i(o.id)} | ${$i(o.result)} | ${$i(o.source)} | ${$i(o.text)} | ${$i(Tr(o.reason))} |`).join(`
200
+ `),i=e.verification.checks.length===0?"_No Runtime checks were recorded._":["| Check | Command | Working directory | Status | Exit | Duration |","| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(o=>{let s=o.argv_display.map(Tr).join(" ");return`| ${$i(Tr(o.name))} | ${$i(s||"—")} | ${$i(o.cwd_ref)} | ${o.status} | ${o.exit_code??"—"} | ${o.duration_ms} ms |`})].join(`
201
+ `),r=e.blockers.length===0?"_None._":e.blockers.map(o=>`- **${o.owner}**: ${Tr(o.reason)}${o.acceptance_ids.length>0?` (acceptance: ${o.acceptance_ids.join(", ")})`:""} — next: \`${o.resolution_action}\``).join(`
202
+ `),n=e.verification.risks.length===0?"_None reported._":e.verification.risks.map(o=>`- ${Tr(o)}`).join(`
203
+ `),a=e.history.length===0?"_No previous iterations._":["| Goal cycle | Iteration | Attempt | Outcome | Unresolved | Summary | Completed |","| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(o=>`| ${o.goal_cycle} | ${o.iteration} | ${o.attempt} | ${o.outcome} | ${o.unresolved_ids.join(", ")||"—"} | ${$i(Tr(o.summary))} | ${o.completed_at} |`)].join(`
204
204
  `);return`---
205
205
  generated_from_state_version: ${e.state_version}
206
206
  ---
@@ -209,13 +209,13 @@ generated_from_state_version: ${e.state_version}
209
209
 
210
210
  ## Current result
211
211
 
212
- - Result: **${g0(e)}**
213
- - Assurance: **${w0(e)}**
212
+ - Result: **${vH(e)}**
213
+ - Assurance: **${gH(e)}**
214
214
  - Goal cycle: ${e.loop.goal_cycle}
215
215
  - Iteration: ${e.verification.iteration}
216
216
  - Verifier attempt: ${e.verification.attempt}
217
217
  - Completed: ${e.verification.completed_at}
218
- - Summary: ${Cr(e.verification.summary)}
218
+ - Summary: ${Tr(e.verification.summary)}
219
219
 
220
220
  ## Acceptance
221
221
 
@@ -243,21 +243,21 @@ ${e.history_overflow.dropped_entries>0?`Earlier history entries folded into summ
243
243
 
244
244
  `:""}## Conclusion
245
245
 
246
- ${Cr(e.verification.summary)}
247
- `}function N0(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function su(e){let t;try{t=await v0.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=N0(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function cu(e){await ue(e.file,y0(e.state))}var hk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,b0="comet-state.yaml",k0="state.json";function Xt(e,t){if(!hk.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Ar.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function yt(e,t){return Ar.join(Xt(e,t),b0)}function sn(e,t){return Ar.join(tt(e,t),k0)}async function _r(e,t){try{let i=await us.readFile(yt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function S0(e){return Ae(e).currentBranch}async function ga(e,t){return Et(yt(e,t))}async function E0(e){let t=await Wr({file:yt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Ar.join(Xt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await us.rm(i,{force:!0})}return t}async function P0(e){let t=Xt(e.paths,e.state.name),i=Ar.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await us.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!hk.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Ar.join(t,...s.split("/")),l=await us.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Ar.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await us.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function R0(e){let t=Xt(e.paths,e.state.name),i=await ee({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return qc({briefMarkdown:i.text,specs:r})}async function pk(e){let t=await P0(e);if(!(t.length===e.state.spec_changes.length&&t.every((a,o)=>{let s=e.state.spec_changes[o];return s!==void 0&&a.capability===s.capability&&a.source===s.source&&(a.operation===s.operation||e.ignoreSpecOperationFor?.has(a.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let r=await R0({...e,specChanges:t}),n=e.state.acceptance.map(({source:a,text:o})=>({source:a,text:o}));return Tw(n,r)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native confirmed acceptance criteria changed"}}async function mk(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...On(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:tr(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}},n=await E0({paths:e.paths,previous:t,next:r});return await xr(sn(e.paths,t.name),on({portableState:n,projectRoot:e.paths.projectRoot,branch:S0(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function lu(e){if(e.state.verification===null)return"not-applicable";let t=Ar.join(Xt(e.paths,e.state.name),"verification.md");return await su({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await cu({file:t,state:e.state}),"rebuilt")}async function vk(e){let t=await ga(e.paths,e.name),i=sn(e.paths,e.name);try{let r=await ou(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var DJ=16*1024;async function uu(e){let t=await bp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Sl(t.selection.change),t.selection)}function gk(e){return eu(e.projectRoot)}async function ds(e,t){return await _n(e.projectRoot),uk(e.projectRoot,"native",t)}var fG=16*1024*1024,du=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},fs=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function yk(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return wa.resolve(e.nativeRoot,...i.target.split("/"))}async function Nk(e,t,i){let r=await cr(e,t.id);if(r.some(m=>m.type==="archive-finalized"))return;let n=r.some(m=>m.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let m=t.operations.find(y=>y.id==="archive-change");if(!m||m.type!=="move"||!m.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await Yt(yk(e,t));if(b?.kind!=="directory"||b.hash!==m.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=yk(e,t),o=wa.join(a,Re),s=await aN(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await Te(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let m=em(hi,l,new Set,Yh,void 0);if(!m.action)throw new Error(m.reason??"Native archive produced no action");u=tm(hi,m.state,{actionId:m.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Yh,void 0)}let d=D(`archive:${t.id}:${s.name}`),f=await Ke(c,u.trajectoryRef),h=f.filter(m=>m.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(m=>m.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(m=>m.type==="state_transitioned"),p={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!x0(v.data,p)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await Zl(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Ln(e,t,"archive-finalization-started")),!s.archived){let m={...s,archived:!0};await nN(o,m)}v||(v=await yr({changeDir:c,run:u,type:"state_transitioned",data:p,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await rn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Yr(c,u),await ds(e,s.name),t.schema==="comet.native.transaction.v2"?await Zl(e,t,"archive-finalized"):await Ln(e,t,"archive-finalized")}async function Rp(e,t){let i=tt(e,t);try{let r=await wk.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await wk.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function C0(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await cr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Kl({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new fs(c,"Native Archive facts changed before the first transaction operation")}let o=await ok(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await je(e,t.change),u=await Ul({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await Nk(e,o,i);let s=await Zl(e,o,"commit");return{journal:s,runtimeCleanupWarning:await Rp(e,s.change)}}let r=await ty(e,t);await Nk(e,r,i);let n=await Ln(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await Rp(e,n.change):null}}function A0(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(wa.resolve(t.projectRoot)!==wa.resolve(e.projectRoot)||wa.resolve(t.nativeRoot)!==wa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function bk(e){return he(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await Zi(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await ht(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await yp(e.paths,e.transactionId):i;return A0(e.paths,r),r.status==="committed"?(r.change&&await Rp(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await C0(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?sk(e.paths,r):al(e.paths,r)}finally{await er(t)}},{allowedTransactionId:e.transactionId})}import{promises as W0}from"fs";async function kk(e,t){let i=[],r=H(e,t.name),n=Xi(r,pt.stateRef),a;try{a=await Te(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Xi(r,a.trajectoryRef),s=await Un(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 Ke(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=Xi(r,a.checkpointRef);try{let u=await Gn(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var _0=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function T0(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function I0(e){return e?e.map(T0).join(" "):null}function j0(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function It(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function $0(e){return e.map(t=>It(t,[],null))}function O0(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[It("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(It("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(It("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),It("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(It("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(It("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),It("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ze(e,t){let i=t.commandArgs===void 0?j0(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?I0(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??$0(t.requiredInputs??[])}}function fu(e){let i=(e.findings??[]).filter(d=>!Kn(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||_0.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ze(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ze(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[It("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ze(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ze(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ze(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ze(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[It("summary",["--summary"],"<summary>")]});if(n)return ze(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ze(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[It("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ze(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ze(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ze(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ze(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ze(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[It("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ze(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ze(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=O0(e.state);return ze(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import hs from"path";var Sk=8,H0={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function D0(e){let t=H0[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"}:Kn(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 F0(e,t,i){if(!i.path)return null;let r;if(hs.isAbsolute(i.path)?r=hs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=hs.resolve(re(e,t.name),...i.path.split(/[\\/]/u)):r=hs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=hs.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function M0(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 xp(e){return e.findings.map(t=>{let i=D0(t.code);return{code:t.code,message:t.message,severity:i.severity,path:F0(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:M0(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Cp(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,Sk),truncated:t.length>Sk}}var Ek=240,Pk=8,hu=50;function Rk(e){let t=Array.from(e);return t.length<=Ek?e:`${t.slice(0,Ek-1).join("")}…`}function L0(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function B0(e){let t=[...new Set(e.map(L0))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Pk),reasonCount:e.length,codesTruncated:t.length>Pk};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,hu),reasonsTruncated:e.length>hu}}}async function xk(e){let t=null;try{let s=await Sr(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:kr(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:kr(e.paths,e.state.name)}}let i=await Db({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=B0(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:br.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Rk(i.checkpoint.summary),nextAction:Rk(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:br.maxArtifacts}}async function q0(e,t){let i=H(e,t.name),r=await Te(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Gn(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ke(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function V0(e,t){let i=await q0(e,t);return{committed:i,latest:hb(i),history:fb(i)}}async function Ck(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await V0(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var z0=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,ya=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Ap(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function J0(e){return(await uu(e))?.change??null}function G0(e,t,i=!1,r){return fu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function U0(e,t){let i=re(e,t.name),r=[...(await Sh(i,t.brief)).findings,...(await uN(e,t)).findings,...await kk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Jn(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await fl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await fa({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await _i(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Eh(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function _p(e,t,i){let r=await J0(e)===t,n=await wo(e,t),a=await Jy(e,t),o;try{let g=await li(e,t);if(g.status==="migration-required"&&g.state)return{name:t,phase:g.state.phase,revision:"revision"in g.state?g.state.revision:null,approval:g.state.approval,verificationResult:g.state.verification_result,specChanges:g.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,migrationRequired:!0,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message};if(g.status!=="current"||!g.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${t} is incompatible`};o=g.state}catch(g){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:g.message}}if(n.status!=="available"){let g={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},E=xp({paths:e,state:o,findings:[g]}),q=fu({state:o,findings:E});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:q.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Cp(E),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:q,workspace:a,runtime:n,...i?.details?{findings:E}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await xk({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Ck(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let g=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:g,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let g=await fa({changeDir:re(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),E=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let He=await ua(e,o.name,o.verification_evidence);for(let ce of He.acceptanceTrace.entries)E.set(ce.acceptanceId,ce.status==="failed"?"failed":ce.status==="missing"?"missing":"satisfied")}let q=Pw({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:E,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),O=q.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",q.nextCursor,"--project-root",e.projectRoot]:null;u={...q,...O?{nextPageCommand:Ap(O),nextPageArgs:O}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Dl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(E=>({code:E,message:`Native change overlap is visible in the current root: ${E}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await vt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let E=await Xn({paths:e,identity:g});E.state==="drifted"&&E.code&&f.push({code:E.code,message:E.message??"Native workspace binding is no longer valid"})}else{let E=await Fo({paths:e,identity:g});f.push(...E.findingCodes.map(q=>({code:q,message:`Native workspace advisory changed: ${q} (${E.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let g=await Jb({paths:e,state:o});v=g.freshness!=="fresh",h.push(...g.findingCodes.map(E=>({code:E,message:`Native Verify implementation scope is not current: ${E}`})))}let p=null,m=[];if(o.phase==="archive")try{p=await Kl({paths:e,name:o.name}),m.push(...p.findingCodes.map(g=>({code:g,message:`Native Archive is blocked: ${g}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await U0(e,o),...s.findings,...d,...f,...h,...l,...m].filter((g,E,q)=>q.findIndex(O=>O.code===g.code&&O.path===g.path)===E),y=xp({paths:e,state:o,findings:b}),P=y.filter(g=>!Kn(g.code)),S=o.phase==="archive"&&p?.ready===!0&&P.length===0,k=v||o.phase==="archive"&&(p?.findingCodes??[]).some(g=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(g)),N=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",w=y.find(g=>g.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:N||R?null:G0(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:Cp(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:fu({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:hu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...w?{error:w.message}:{}}}async function K0(e){let t;try{t=await Wt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await W0.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>ya.maxChanges))throw new Error(`Native status exceeds ${ya.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function pu(e,t){let i=t.toString(36),r=L("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function Y0(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=z0.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=L("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function X0(e,t){let i=await K0(e),r=L("comet.native.status-names.v1",i),n=Y0({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+ya.maxItems).map(u=>_p(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?pu(r,f):null,nextPageCommand:f<i.length?Ap(["comet","native","status","--cursor",pu(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",pu(r,f)]:null,limits:{...ya}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>ya.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?pu(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?Ap(l):null,nextPageArgs:l,limits:{...ya}}}async function Tp(e,t){return(await X0(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as vH,randomUUID as gH}from"node:crypto";import{constants as Hp,promises as X}from"node:fs";import se from"node:path";var gu=xa(Sn(),1);import{randomUUID as Q0}from"crypto";import{promises as jk}from"fs";import jp from"path";import{isDeepStrictEqual as $p}from"util";var cn=/^[a-f0-9]{64}$/u,Z0=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),eH=new Set(["sourceHash","targetHash","nextJournal"]),tH=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),Ak=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),iH=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function mu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function _k(e){return JSON.stringify(e,null,2)+`
248
- `}function Op(e){return e.schema===we?El(e):Xr(e)}function Ip(e,t){return{...e,schema:we,minimum_runtime_version:2,revision:t}}function rH(e){return{...e,schema:ki,minimum_runtime_version:2,revision:1,previousState:Ip(e.previousState,1),nextState:Ip(e.nextState,2)}}function vu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:ge,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function nH(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?D(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:ir,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:vu(e.previousState),nextState:{...vu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:hi.definition.metadata.version,skillHash:rs}:e.nextRun}}function Tk(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Na(e,t){return JSON.stringify(El(e))===JSON.stringify(El(t))}function Ik(e,t){return JSON.stringify(Xr(e))===JSON.stringify(Xr(t))}function ji(e,t){return $p(e,t)}function aH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(mu(n,tH,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!cn.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!cn.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=fr(n.previousRun),o=fr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!ji(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==Ak.size||u.some(f=>!Ak.has(f))||l.fromSchema!==we||l.toSchema!==ge||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=D(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function ps(e,t){return jp.join(H(e,t),"schema-migration.json")}function oH(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");mu(e,Z0,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===Ge&&i.toSchema===we,n=i.fromSchema===we&&i.toSchema===ge;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!cn.test(i.sourceHash)||typeof i.targetHash!="string"||!cn.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?ni(i.nextState):nt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(D((0,gu.stringify)(Op(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");mu(i.transition,eH,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!cn.test(l.sourceHash)||typeof l.targetHash!="string"||!cn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?np(l.nextJournal,t):rp(l.nextJournal,t);if(D(JSON.stringify(l.nextJournal,null,2)+`
249
- `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===we?Na(a,u.previousState)||Na(a,u.nextState):a.schema===ge&&(Ik(a,u.previousState)||Ik(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==ge)throw new Error("Schema migration transition supersede target schema is invalid");s=aH(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");mu(i.runRetreat,iH,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=fr(l.previousRun),d=fr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!cn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==ge||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function ms(e,t){let i=ps(e,t),r=j(e,i);await T(r,i);try{let n=await Qc({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return oH(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function sH(e,t,i){let r=await Jn(e,t),n=r?await fl(e,r):await hl(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=lh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new Qn(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await fh(e,t,n)}async function $k(e){try{return await zt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function cH(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function Ok(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await Ke(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!$p(o.event,cH(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function lH(e,t,i){if(!t.transitionSupersede)return;let r=We(e,t.change),n=await $k(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await Te(a),s=await Ok(e,t),c=await Gn(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!ji(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==D(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function uH(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await Te(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ji(a,r.nextRun)){if(!ji(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Yr(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!ji(await Te(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await Ok(e,t);if(o.sequence===null){let l=await yr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await rn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=We(e,t.change),c=await $k(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await jk.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function dH(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await Te(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ji(n,t.runRetreat.nextRun)){if(!ji(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Yr(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await Ke(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await yr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await rn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function fH(e,t,i){let r=await ms(e,t);if(!r)return null;if(await ea(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=jp.join(re(e,t),Re),a=await zt(n);if(await lH(e,r,a===r.targetHash),await sH(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await ue(n,(0,gu.stringify)(Op(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=We(e,t),s=await zt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await te(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await uH(e,r,i),await dH(e,r,i),await jk.rm(ps(e,t),{force:!0}),r.nextState}async function hH(e){let t=H(e.paths,e.state.name),i=await Te(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=D(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:we,toSchema:ge,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function pH(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Na(i,t.previousState),a=Na(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await Te(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&ji(s,t.previousRun),l=ji(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await Ke(o,t.nextRun.trajectoryRef)).map((b,y)=>({event:b,index:y})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!$p(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...vu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,m=D(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await zt(We(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:p,evidenceHash:m,eventData:{fromSchema:we,toSchema:ge,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function mH(e){let t,i,r,n;if(e.state.schema===Ge){if(t=Ip(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==zr)throw new Error("Native v1 change has a transition from another schema generation");let s=rH(e.pendingTransition.journal);if(Tk(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(Tk(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=We(e.paths,e.name);i={sourceHash:await zt(c),targetHash:D(_k(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==ki)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await pH({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=nH(s);if(Na(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Na(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=We(e.paths,e.name);i={sourceHash:await zt(u),targetHash:D(_k(l)),nextJournal:l}}}else t=vu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await hH({paths:e.paths,state:e.state,migrationId:e.id}));let a=jp.join(re(e.paths,e.name),Re),o=(0,gu.stringify)(Op(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Ge?we:ge,sourceHash:await zt(a),targetHash:D(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function Hk(e){return he(e.paths,`migrate schema for ${e.name}`,()=>nn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await fH(e.paths,e.name,e.hooks);if(i?.schema===ge)return i;let r=await li(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await ea(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==Ge&&n.schema!==we)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await ap(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await mH({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??Q0()}),s=ps(e.paths,e.name),c=j(e.paths,s);await T(c,s),await te(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var $i=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),wH=512*1024,ln=/^([a-f0-9]{64})\.json$/u,yH=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,NH=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,wu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Fp(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wi(e,t){return Fp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Bk(e,t){return Fp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function ba(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Xe(e,t){return e<t?-1:e>t?1:0}function bH(e,t){let i=se.relative(e.projectRoot,t);if(i.length===0||se.isAbsolute(i)||i===".."||i.startsWith(`..${se.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(se.sep).join("/")}function qk(e,t){return se.join(H(e,t),"evidence")}function yu(e,t){return bH(e,qk(e,t))}async function Nu(e,t){let i=se.resolve(e),r=se.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=se.relative(i,r).split(se.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=se.join(o,s));let c=await X.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await X.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...ba(c)})}return a}async function jt(e){for(let t of e){let i=await X.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Fp(t,i)||await X.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function Vk(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:la(e,t)}function Dk(e){return e!==null&&NH.test(e)?[e]:[]}function kH(e,t,i,r){if(e==="snapshots")return{canonical:ra(i,t),dependencies:[]};if(e==="scopes"){let a=na(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Il(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[la("scopes",a.scopeHash)]}}if(e==="verifications"){let a=Qo(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(Dk));return{canonical:a,dependencies:[a.implementationScopeRef,ib(a.reportHash),...Dk(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||vH("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=$l(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=jl(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Tr(e){let t=await X.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?wH:wr;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await X.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Hp.O_RDONLY|Hp.O_NOFOLLOW|Hp.O_NONBLOCK,a=await X.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await jt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!wi(ba(t),o)||!wi(ba(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,P=await a.read(u,0,Math.min(u.length,y),null);if(P.bytesRead===0)break;if(d+=P.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,P.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await jt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!wi(ba(o),f)||!wi(ba(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),m;try{m=JSON.parse(p)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let b=kH(e.kind,e.hash,m,e.name);if(p!==JSON.stringify(b.canonical,null,2)+`
250
- `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:ba(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(Xe)}}finally{await a.close()}}async function Fk(e){try{return await X.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function SH(e){let t=H(e.paths,e.name),i=t,r=qk(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Nu(t,r);n=await X.readdir(r,{withFileTypes:!0}),await jt(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of wu){if(!n.some(f=>f.name===s))continue;let c=se.join(r,s),l=await Nu(t,c),u=(await X.readdir(c,{withFileTypes:!0})).sort((f,h)=>Xe(f.name,h.name)),d=new Map;for(let f of u){let h=yH.exec(f.name);if(!h)continue;let v=d.get(h[1])??[];v.push(f),d.set(h[1],v)}for(let[f,h]of[...d.entries()].sort(([v],[p])=>Xe(v,p))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=h[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let p=se.join(c,f),m=ln.exec(f)?.[1];if(!m)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=Vk(s,m),y=se.join(c,v.name),P=await Tr({changeRoot:i,file:y,ref:b,kind:s,hash:m,name:e.name,directoryChain:l}),S=await Fk(p),k=S?null:await Tr({changeRoot:i,file:p,ref:b,kind:s,hash:m,name:e.name,directoryChain:l});a.push({ref:b,original:p,quarantine:y,document:P,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Xe);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:ka(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${bu(o)}`),path:yu(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Xe(c.ref,l.ref))){if(await jt(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Tr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ln.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Tr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ln.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!wi(s.originalDocument.identity,d.identity)||!wi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await X.rm(s.quarantine),await jt(s.document.directoryChain);continue}if(!await Fk(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await X.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!wi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await X.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Tr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:ln.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Tr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:ln.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!Bk(s.document.identity,l.identity)||!wi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await X.rm(s.quarantine),await jt(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:ka(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${bu(o)}`),path:yu(e.paths,e.name)}]}}async function EH(e,t){let i=H(e,t),r=i,n=se.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Nu(i,n);a=await X.readdir(n,{withFileTypes:!0}),await jt(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!wu.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Xe);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${bu(o)}`);let s=[],c=0;for(let l of wu){if(!a.some(h=>h.name===l))continue;let u=se.join(n,l),d=await Nu(r,u),f=(await X.readdir(u,{withFileTypes:!0})).sort((h,v)=>Xe(h.name,v.name));await jt(d);for(let h of f){if(s.length>=$i.maxDocuments)throw new Error(`Native evidence store exceeds ${$i.maxDocuments} documents`);let v=ln.exec(h.name);if(!v||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let p=Vk(l,v[1]),m=se.join(u,h.name);await T(j(e,m),m);let b=await Tr({changeRoot:r,file:m,ref:p,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>$i.maxScannedBytes)throw new Error(`Native evidence store exceeds ${$i.maxScannedBytes} scanned bytes`);s.push(b)}await jt(d)}return s}function Mk(e,t){let i=new Set,r=[...e].sort(Xe).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Xe).reverse())i.has(o)||r.push(o)}return i}function PH(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Xe),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Xe))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function RH(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=Mk(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<$i.minimumAgeMs&&a.add(c.ref);for(let c of wu){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Xe(u.ref,d.ref)).slice(0,$i.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=Mk(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=$i.minimumAgeMs).sort((c,l)=>Xe(c.ref,l.ref));return{candidates:PH(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function bu(e){let t=e.slice(0,$i.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function ka(e){let t=$i.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Dp(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Xe);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:ka(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${bu(n)}`),path:r}}async function Lk(e,t){try{await X.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await X.rename(e,t)}catch{}}async function xH(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await jt(e.directoryChain);let i=await Tr({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:ln.exec(se.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await X.lstat(e.file),n=await X.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!wi(e.identity,r)||!wi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=se.join(se.dirname(e.file),`.${se.basename(e.file)}.${gH()}.gc`);await X.rename(e.file,a);try{let[o,s]=await Promise.all([X.lstat(a),X.realpath(a)]);if(await jt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!Bk(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await Lk(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await X.rm(a),await jt(e.directoryChain)}catch(o){throw await Lk(a,e.file),o}}async function CH(e){if((await Pe(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await X.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await ht(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function AH(e,t){if(t)return[t];let i;try{i=await X.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Xe)}async function _H(e,t){let i=await li(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([_i(e,t),ms(e,t),Sr(e,t)]);return r!==null||n!==null||a!==null}async function TH(e){if(await _H(e.paths,e.name))return[];let t=await li(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await SH({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await EH(e.paths,e.name),a=RH(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=yu(e.paths,e.name);if(!e.repair)return[...i.findings,Dp(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await xH(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Dp(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:ka(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Dp(e.name,a,!0,o)]}async function Wk(e){if(e.deferAll||await CH(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await AH(e.paths,e.name))try{a.push(...await TH({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:ka(`Native evidence retention refused to clean ${o}: ${s.message}`),path:yu(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await he(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:ka(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as IH,randomUUID as zU}from"crypto";import{promises as ws}from"fs";import ne from"path";var Lp=64*1024*1024,jH=256*1024,Uk=16*1024*1024;async function Qe(e){try{return await ws.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $H(e){let t;try{t=await ws.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await vt(e,i.name);if(r){await bl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function gs(e,t){let i=[];async function r(n){let a=await ft({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(n,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await ws.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ie({root:e,file:c,maxBytes:Lp,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function OH(e,t,i,r){await ai({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await ft({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await ws.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await ai({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await or({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Lp,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Sa(e,t,i,r){let n=await gs(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await gs(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ne.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function HH(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function DH(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function FH(e){return`${e}.removing`}function zk(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function Kk(e,t,i){return ne.join(nl(e,t).directory,`root-move-cleanup-${i}.json`)}function MH(e){return JSON.stringify(e,null,2)+`
251
- `}function LH(e){return IH("sha256").update(e).digest("hex")}function BH(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function qH(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(BH);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function VH(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=MH(t);if(Buffer.byteLength(i,"utf8")>Uk)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await ue(Kk(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),LH(i)}async function WH(e){let t=await ie({root:e.paths.runtimeDir,file:Kk(e.paths,e.id,e.cleanup.kind),maxBytes:Uk,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return qH(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Mp(e){let t=await gs(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function Jk(e){return e.ref.split("/").length}async function zH(e){let i=[...await Mp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>Jk(a)-Jk(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ne.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Zc({root:e.projectRoot,file:a,maxBytes:Lp,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Gf({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Mp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Gf({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function Yk(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function JH(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function GH(e,t,i,r){for(let a of[e,t])try{let o=await ht(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ne.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ie({root:i,file:n,maxBytes:jH,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function Gk(e){let t=Yk(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Qi(e.projectRoot,t),t}async function vs(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=Yk(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Qi(e.projectRoot,i),i}async function ku(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await Qe(e.target),a=await Qe(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await VH({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await gs(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await vs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await WH({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await Qe(e.target),a=await Qe(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Vw({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return vs({projectRoot:e.projectRoot,config:t,id:e.id})}return await Mp({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await vs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await vs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await zH({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),vs({projectRoot:e.projectRoot,config:t,id:e.id})}async function UH(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Qe(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=FH(e.staging);t=await ku({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await gs(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await OH(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Sa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await Gk({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Qe(e.destinationPaths.nativeRoot)){if(await Qe(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Sa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Qe(e.staging))throw new Error("Native move staging tree is missing");await Sa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await ws.rename(e.staging,e.destinationPaths.nativeRoot)}t=await Gk({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Qe(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=DH(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Qe(e.sourcePaths.nativeRoot)&&await Sa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await ku({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await $H(e.destinationPaths);let n=await ht(e.destinationPaths,e.pending.id);await Ln(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Qi(e.projectRoot,o),o}async function Xk(e){let t=await Pe(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await dt(e.projectRoot,i.fromArtifactRoot),n=await dt(e.projectRoot,i.toArtifactRoot),a=HH(n,i.id),o=await Qe(r.nativeRoot)?r:n,s=await Zi(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await GH(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await Qe(r.nativeRoot))throw v;let p=JH({id:i.id,paths:r,now:new Date});await Zw(r,p),c={journal:p,paths:r}}if(e.strategy==="continue"){let v=await UH({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await Qe(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=zk(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Qe(n.nativeRoot)&&await Sa(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await ku({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=zk(a,i.id);!t.native.pending_root_move?.cleanup&&await Qe(a)&&await Sa(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await ku({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await ht(r,i.id);await al(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await Qi(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await er(s)}}var Ea=4096,KH=4096,YH=1024;async function Ir(e,t,i){try{let r=await ft({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Eu(e,t){let i=new Map(e.map(r=>[xe.resolve(r.file),{...r,file:xe.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await No(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Of(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function XH(e,t){let i=gk(e),r;try{await T(e.projectRoot,i);let n=await uu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await _r(e,r.change)?[]:(await je(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await Su.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function QH(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function ZH(e,t){let i=[],r=[];for(let n of await Ir(e,e.transactionsDir,KH)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await ht(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:xe.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await yo([e],`doctor archive recovery ${a.id}`,async()=>await Eu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,"archive.lock")}],i)?(await bk({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function eD(e,t,i){let r=[];for(let n of await Ir(e,e.locksDir,YH)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=xe.join(e.locksDir,n.name);try{let o=await No(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await Of(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function tD(e,t,i=5){let r=[],n=t?await Tp(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Tp(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:xe.join(e.changesDir,a.name,Re)});continue}let o=await _p(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:xe.join(e.projectRoot,s.path)}:{}})}return r}async function iD(e,t){let i=[],r=t.name?[t.name]:(await Ir(e,e.changesDir,Ea)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await Un(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Dy(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:xe.join(H(e,n),"trajectory.jsonl")})}return i}async function rD(e,t){let i=[],r=t.name?[t.name]:(await Ir(e,e.changesDir,Ea)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await wo(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=qr(e,n),s=tt(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await yo([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Wt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await Su.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Wt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Su.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await Su.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function nD(e,t){let i=[],r=t.name?[t.name]:(await Ir(e,e.changesDir,Ea)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await wh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:Yn(e,n),repair:"migrate"});continue}let a=await je(e,n);await Uy({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:Yn(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Yn(e,n)})}return i}async function aD(e,t){let i=[],r=t.name?[t.name]:(await Ir(e,e.changesDir,Ea)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=ps(e,n);try{let o=await ms(e,n),s=await li(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:xe.join(e.changesDir,n,Re)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:xe.join(e.changesDir,n,Re),repair:"migrate"});continue}await Hk({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:xe.join(e.changesDir,n,Re)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function oD(e,t){let i=[],r=t.name?[t.name]:(await Ir(e,e.changesDir,Ea)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await _i(e,n)}catch(o){if(o instanceof ns)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:We(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await yo([e],`doctor transition recovery ${n}`,async()=>await Eu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await xb(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:We(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:We(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:We(e,n),repair:"continue"})}}return i}async function sD(e,t){let i=[],r=t.name?[t.name]:(await Ir(e,e.changesDir,Ea)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=kr(e,n),o;try{o=await Sr(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await yo([e],`doctor checkpoint recovery ${n}`,async()=>await Eu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Mb(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function ys(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Pe(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([dt(r.projectRoot,c.fromArtifactRoot),dt(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Eu([{paths:l,file:xe.join(l.locksDir,"root-move.lock")},{paths:u,file:xe.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await Xk({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await dt(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await QH(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await ZH(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await rD(r,{name:e.name,repair:t})),i.push(...await aD(r,{name:e.name,repair:t})),i.push(...await nD(r,{name:e.name,repair:t})),i.push(...await iD(r,{name:e.name,repair:t})),i.push(...await oD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await sD(r,{name:e.name,repair:t})),i.push(...await Wk({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await eD(r,t,s.unfinished)),i.push(...await XH(r,t)),e.projectOnly||i.push(...await tD(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as cD}from"node:crypto";import{promises as Oe}from"node:fs";import ct from"node:path";var Bp=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function Qk(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Zk(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ct.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function Pu(e){try{return await Oe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function eS(e,t){let i=ct.normalize(ct.resolve(e)),r=ct.normalize(ct.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function lD(e,t){let i;try{i=await Oe.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ct.join(e.archiveDir,n.name);try{let o=await Et(ct.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function uD(e,t){let i=await Yc(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function un(e,t){await Oe.mkdir(e.transactionsDir,{recursive:!0}),await te(rr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function dD(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=bc(e.paths.projectRoot);i.some(a=>eS(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Pe(a);if(!o)continue;let s=await dt(a,o.native.artifact_root);r.some(c=>eS(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await Oe.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Et(ct.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Rl(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function fD(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function hD(e){let t=ct.join(e.paths.specsDir,e.change.capability),i=ct.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Oe.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Oe.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Oe.realpath(e.paths.specsDir),Oe.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Oe.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Oe.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Oe.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ct.join(Xt(e.paths,e.state.name),e.change.source);await ue(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Oe.mkdir(t,{recursive:!0}),await ue(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function tS(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function pD(e,t){let i=Xt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await ee({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function mD(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(tS(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function qp(e){return he(e.paths,`archive portable change ${e.name}`,async()=>{let t=fD(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await uD(e.paths,e.name),r=Xt(e.paths,e.name),n=await Pu(r),a=n?null:await lD(e.paths,e.name),o;if(n)o=await ga(e.paths,e.name);else if(i)o=await Et(ct.join(Zk(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await pk({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await mk({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=Zk(e.paths,i?.archive_ref??Qk(o)),c=await Pu(s);if(i&&mD(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await ds(e.paths,o.name),await Oe.rm(tt(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)tS(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await dD({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new Bp(l);i={schema:Kc,id:cD(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Qk(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await pD(e.paths,o),created_at:new Date().toISOString()},await un(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await un(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await hD({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await un(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await un(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Wr({file:yt(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await un(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await Pu(r)?r:s;if(await cu({file:ct.join(l,"verification.md"),state:o}),await su({file:ct.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await un(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await Oe.mkdir(e.paths.archiveDir,{recursive:!0}),await Pu(s))throw new Error(`Native Archive target already exists: ${s}`);await Oe.rename(r,s),i={...i,status:"moved"},await un(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await ds(e.paths,o.name),await Oe.rm(tt(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Oe.rm(rr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function jr(e){let t={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},i=r=>({kind:r,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...t,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:i("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...t,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...t,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...t,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--resolve-verifier-blocker"],requiredInputs:["summary","user-resolution"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...t,disposition:"await-user",action:"resolve-loop-stop",commandArgs:["comet","native","next",e.name,"--return-to-build","--summary","<summary>"],requiredInputs:["summary","user-decision"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:i("none")}:{...t,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:i("none")};if(e.status==="blocked"){let r=e.blockers.some(({resolution_action:n})=>n==="retry-verifier");return{...t,disposition:"blocked",action:r?"retry-verifier":"none",commandArgs:r?["comet","native","next",e.name,"--retry-verifier","--summary","<summary>"]:null,requiredInputs:r?["summary"]:["repair-runtime"],inputOptions:r?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:i(r?"retry-verifier":"none")}}if(e.phase==="shape")return{...t,disposition:"continue",action:"confirm-shape",commandArgs:["comet","native","next",e.name,"--summary","<summary>","--confirmed"],requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:i("none")};if(e.phase==="build")return{...t,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:i("builder-handoff")};if(e.phase==="verify"){let r=e.loop.next_action==="await-verifier-result";return{...t,disposition:"continue",action:r?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[r?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:r?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:i(r?"await-verifier":"dispatch-verifier")}}return{...t,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:i("none")}}import{randomUUID as vD}from"node:crypto";import{promises as Pa}from"node:fs";import cS from"node:path";var lS=["evidence.md","verification.md","repair.md","archive.md","checkpoint.md"];async function gD(e){try{return await Pa.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Vp(e,t){let i=re(e,t),r=[rr(e,{kind:"migration",change:t}),qr(e,t),...lS.map(n=>cS.join(i,n))];return(await Promise.all(r.map(gD))).some(Boolean)}async function wD(e,t){let i=await Yc(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function iS(e,t){await Pa.mkdir(e.transactionsDir,{recursive:!0}),await te(rr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function rS(e,t){await Promise.all([Pa.rm(tt(e,t),{recursive:!0,force:!0}),Pa.rm(qr(e,t),{recursive:!0,force:!0}),...lS.map(i=>Pa.rm(cS.join(re(e,t),i),{force:!0}))])}async function nS(e,t){await xr(sn(e,t.name),on({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function aS(e,t){try{let i=await vt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function oS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=Ae(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function yD(e){let t=re(e.paths,e.state.name),i=await ee({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await ee({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return qc({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function sS(e,t){let i=await Rl(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Ns(e){return he(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await wD(e.paths,e.name),i=await _r(e.paths,e.name)?await Et(yt(e.paths,e.name)):null;if(!t&&i)return await rS(e.paths,e.name),await nS(e.paths,i),i;let r=null,n=null;for(t||(r=await sS(e.paths,e.name),n=await aS(e.paths,e.name),oS(e.paths,n),t={schema:Uc,id:vD(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await iS(e.paths,t));;){let a=$w(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await sS(e.paths,e.name),n??=await aS(e.paths,e.name),oS(e.paths,n),i=jw({state:r,acceptance:await yD({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Gc(yt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await rS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Et(yt(e.paths,e.name)),await nS(e.paths,i)),t={...t,status:a.nextStatus},await iS(e.paths,t)}return await Pa.rm(rr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Et(yt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as uS}from"node:fs";import dS from"node:path";function ND(e,t){let i=Ae(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function bD(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function kD(e,t){let i=new Date().toISOString(),r=e.verification===null?e:On(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:tr(t),completed_at:i});return St({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:bD(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function SD(e){try{let t=await ou(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function fS(e){return he(e.paths,`recover portable change ${e.name}`,async()=>{let t=await ga(e.paths,e.name);if(t.status==="done")return await lu({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=ND(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=sn(e.paths,e.name),n=await SD(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await xr(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await lu({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=kp({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Wr({file:yt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await uS.rm(dS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=on({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await xr(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=kD(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await Wr({file:yt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=on({portableState:t,projectRoot:e.paths.projectRoot,branch:Ae(e.paths.projectRoot).currentBranch});return await uS.mkdir(dS.dirname(sn(e.paths,t.name)),{recursive:!0}),await xr(r,d,{containedRoot:e.paths.runtimeDir}),await lu({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as hS}from"node:fs";function ED(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function PD(e,t){let i=Ae(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function Ra(e){let t=await vk(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=PD(e.paths,t.state),n=jr(t.state),a=r.bindingState==="mismatch"?{...n,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...n.runnerAction,kind:"none"}}:n;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:ED(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},continuation:a,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function pS(e){let t;try{t=await hS.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await hS.readFile(`${Xt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import Jp from"path";var wY=8*1024*1024;var Ru=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var mS=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],zp=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:mS,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries or inspect the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--return-to-build|--retry-verifier|--resolve-verifier-blocker]
252
- comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape, a completed skill-coordinated pass, or an explicitly degraded verifier-unavailable fallback before Archive.","--return-to-build Return Verify or Archive to Build after invalidation or user choice.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Implementation changed" --return-to-build','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
253
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Wp(e,t){return`${e}:
246
+ ${Tr(e.verification.summary)}
247
+ `}function yH(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function mu(e){let t;try{t=await mH.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=yH(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function vu(e){await ue(e.file,wH(e.state))}var qk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NH="comet-state.yaml",bH="state.json";function jt(e,t){if(!qk.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Ir.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}function bt(e,t){return Ir.join(jt(e,t),NH)}function un(e,t){return Ir.join(it(e,t),bH)}async function jr(e,t){try{let i=await ps.readFile(bt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function kH(e){return Ae(e).currentBranch}async function Sa(e,t){return Ge(bt(e,t))}async function SH(e){let t=await Gr({file:bt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Ir.join(jt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await ps.rm(i,{force:!0})}return t}async function EH(e){let t=jt(e.paths,e.state.name),i=Ir.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ps.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!qk.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Ir.join(t,...s.split("/")),l=await ps.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Ir.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await ps.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function PH(e){let t=jt(e.paths,e.state.name),i=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return Uc({briefMarkdown:i.text,specs:r})}async function Vk(e){let t=await EH(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await PH({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!ey(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Fp({changeDir:jt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Mp({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Lp({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Wk(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Bn(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:nr(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await SH({paths:e.paths,previous:t,next:r});return await _r(un(e.paths,t.name),ln({portableState:n,projectRoot:e.paths.projectRoot,branch:kH(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function gu(e){if(e.state.verification===null)return"not-applicable";let t=Ir.join(jt(e.paths,e.state.name),"verification.md");return await mu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await vu({file:t,state:e.state}),"rebuilt")}async function zk(e){let t=await Sa(e.paths,e.name),i=un(e.paths,e.name);try{let r=await pu(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var aU=16*1024;async function wu(e){let t=await Ip(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Al(t.selection.change),t.selection)}function Jk(e){return ou(e.projectRoot)}async function ms(e,t){return await On(e.projectRoot),$k(e.projectRoot,"native",t)}var $U=16*1024*1024,yu=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},vs=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function Uk(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Ea.resolve(e.nativeRoot,...i.target.split("/"))}async function Kk(e,t,i){let r=await dr(e,t.id);if(r.some(m=>m.type==="archive-finalized"))return;let n=r.some(m=>m.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let m=t.operations.find(y=>y.id==="archive-change");if(!m||m.type!=="move"||!m.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let N=await Qt(Uk(e,t));if(N?.kind!=="directory"||N.hash!==m.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Uk(e,t),o=Ea.join(a,Re),s=await AN(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await Ie(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let m=bm(pi,l,new Set,sp,void 0);if(!m.action)throw new Error(m.reason??"Native archive produced no action");u=km(pi,m.state,{actionId:m.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},sp,void 0)}let d=F(`archive:${t.id}:${s.name}`),f=await Ye(c,u.trajectoryRef),p=f.filter(m=>m.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(m=>m.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=p.find(m=>m.type==="state_transitioned"),h={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!RH(v.data,h)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||p.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await au(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Jn(e,t,"archive-finalization-started")),!s.archived){let m={...s,archived:!0};await CN(o,m)}v||(v=await kr({changeDir:c,run:u,type:"state_transitioned",data:h,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await on({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Zr(c,u),await ms(e,s.name),t.schema==="comet.native.transaction.v2"?await au(e,t,"archive-finalized"):await Jn(e,t,"archive-finalized")}async function zp(e,t){let i=it(e,t);try{let r=await Gk.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await Gk.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function xH(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await dr(e,t.id)).some(c=>c.type==="operation-started")){let c=await tu({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new vs(c,"Native Archive facts changed before the first transaction operation")}let o=await _k(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await $e(e,t.change),u=await eu({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await Kk(e,o,i);let s=await au(e,o,"commit");return{journal:s,runtimeCleanupWarning:await zp(e,s.change)}}let r=await Ey(e,t);await Kk(e,r,i);let n=await Jn(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await zp(e,n.change):null}}function CH(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Ea.resolve(t.projectRoot)!==Ea.resolve(e.projectRoot)||Ea.resolve(t.nativeRoot)!==Ea.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Yk(e){return he(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await ir(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await mt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await _p(e.paths,e.transactionId):i;return CH(e.paths,r),r.status==="committed"?(r.change&&await zp(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await xH(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?Tk(e.paths,r):dl(e.paths,r)}finally{await rr(t)}},{allowedTransactionId:e.transactionId})}import{promises as VH}from"fs";async function Xk(e,t){let i=[],r=H(e,t.name),n=er(r,vt.stateRef),a;try{a=await Ie(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=er(r,a.trajectoryRef),s=await ea(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 Ye(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=er(r,a.checkpointRef);try{let u=await Zn(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var AH=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function _H(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function TH(e){return e?e.map(_H).join(" "):null}function IH(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function $t(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function jH(e){return e.map(t=>$t(t,[],null))}function $H(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[$t("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push($t("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push($t("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),$t("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push($t("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push($t("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),$t("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ze(e,t){let i=t.commandArgs===void 0?IH(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?TH(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??jH(t.requiredInputs??[])}}function Nu(e){let i=(e.findings??[]).filter(d=>!ta(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||AH.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return ze(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ze(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[$t("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ze(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ze(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ze(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ze(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"<summary>")]});if(n)return ze(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ze(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[$t("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ze(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ze(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ze(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ze(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ze(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[$t("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ze(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ze(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=$H(e.state);return ze(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import gs from"path";var Qk=8,OH={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function HH(e){let t=OH[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"}:ta(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 DH(e,t,i){if(!i.path)return null;let r;if(gs.isAbsolute(i.path)?r=gs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=gs.resolve(re(e,t.name),...i.path.split(/[\\/]/u)):r=gs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,r))return null;let n=gs.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function MH(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 Jp(e){return e.findings.map(t=>{let i=HH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:DH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:MH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function Gp(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,Qk),truncated:t.length>Qk}}var Zk=240,eS=8,bu=50;function tS(e){let t=Array.from(e);return t.length<=Zk?e:`${t.slice(0,Zk-1).join("")}…`}function FH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function LH(e){let t=[...new Set(e.map(FH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,eS),reasonCount:e.length,codesTruncated:t.length>eS};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,bu),reasonsTruncated:e.length>bu}}}async function iS(e){let t=null;try{let s=await Rr(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Pr(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:Pr(e.paths,e.state.name)}}let i=await sk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=LH(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Er.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:tS(i.checkpoint.summary),nextAction:tS(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Er.maxArtifacts}}async function BH(e,t){let i=H(e,t.name),r=await Ie(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Zn(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Ye(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function qH(e,t){let i=await BH(e,t);return{committed:i,latest:Db(i),history:Hb(i)}}async function rS(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await qH(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var WH=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Pa=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Up(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function zH(e){return(await wu(e))?.change??null}function JH(e,t,i=!1,r){return Nu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function GH(e,t){let i=re(e,t.name),r=[...(await $h(i,t.brief)).findings,...(await $N(e,t)).findings,...await Xk(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Qn(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await wl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await wa({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Ii(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await Oh(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function Kp(e,t,i){let r=await zH(e)===t,n=await bo(e,t),a=await vN(e,t),o;try{let g=await ui(e,t);if(g.status==="migration-required"&&g.state)return{name:t,phase:g.state.phase,revision:"revision"in g.state?g.state.revision:null,approval:g.state.approval,verificationResult:g.state.verification_result,specChanges:g.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,migrationRequired:!0,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message};if(g.status!=="current"||!g.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:g.schema,minimumRuntimeVersion:g.minimumRuntimeVersion,error:g.message??`Native change ${t} is incompatible`};o=g.state}catch(g){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:g.message}}if(n.status!=="available"){let g={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=Jp({paths:e,state:o,findings:[g]}),D=Nu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:D.command,archiveReady:!1,inspection:{freshness:"stale",codes:[g.code],reasonCount:1,codesTruncated:!1},findingSummary:Gp(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:D,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:g.message}:{}}}let s=await iS({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await rS(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let g=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:g,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let g=await wa({changeDir:re(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let De=await va(e,o.name,o.verification_evidence);for(let ce of De.acceptanceTrace.entries)P.set(ce.acceptanceId,ce.status==="failed"?"failed":ce.status==="missing"?"missing":"satisfied")}let D=Uw({criteria:g.contract.acceptance,acceptanceHash:g.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),O=D.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",D.nextCursor,"--project-root",e.projectRoot]:null;u={...D,...O?{nextPageCommand:Up(O),nextPageArgs:O}:{}}}catch(g){if(i.acceptanceCursor)throw g;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let g=await Vl(e,o.name,{tolerateInvalidSiblings:!0});d.push(...g.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let g=await wt(e,o.name);if(g)if(g.schema==="comet.native.workspace.v3"){let P=await ra({paths:e,identity:g});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Lo({paths:e,identity:g});f.push(...P.findingCodes.map(D=>({code:D,message:`Native workspace advisory changed: ${D} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let g=await vk({paths:e,state:o});v=g.freshness!=="fresh",p.push(...g.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await tu({paths:e,name:o.name}),m.push(...h.findingCodes.map(g=>({code:g,message:`Native Archive is blocked: ${g}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let N=[...await GH(e,o),...s.findings,...d,...f,...p,...l,...m].filter((g,P,D)=>D.findIndex(O=>O.code===g.code&&O.path===g.path)===P),y=Jp({paths:e,state:o,findings:N}),E=y.filter(g=>!ta(g.code)),S=o.phase==="archive"&&h?.ready===!0&&E.length===0,k=v||o.phase==="archive"&&(h?.findingCodes??[]).some(g=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(g)),b=y.some(g=>g.code==="trajectory-tail-incomplete"||g.code==="trajectory-invalid"||g.requiredAction==="return-to-bound-working-directory"||g.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",w=y.find(g=>g.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:b||R?null:JH(o,S,k,i?.clarificationMode),archiveReady:S,inspection:s.inspection,findingSummary:Gp(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Nu({state:o,findings:y,archiveReady:S,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:bu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...w?{error:w.message}:{}}}async function UH(e){let t;try{t=await Jt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await VH.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Pa.maxChanges))throw new Error(`Native status exceeds ${Pa.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function ku(e,t){let i=t.toString(36),r=M("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function KH(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=WH.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=M("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function YH(e,t){let i=await UH(e),r=M("comet.native.status-names.v1",i),n=KH({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Pa.maxItems).map(u=>Kp(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,p={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?ku(r,f):null,nextPageCommand:f<i.length?Up(["comet","native","status","--cursor",ku(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",ku(r,f)]:null,limits:{...Pa}};if(Buffer.byteLength(JSON.stringify(p),"utf8")>Pa.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?ku(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?Up(l):null,nextPageArgs:l,limits:{...Pa}}}async function Yp(e,t){return(await YH(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as mD,randomUUID as vD}from"node:crypto";import{constants as tm,promises as X}from"node:fs";import se from"node:path";var Pu=mn(qr(),1);import{randomUUID as XH}from"crypto";import{promises as cS}from"fs";import Qp from"path";import{isDeepStrictEqual as Zp}from"util";var dn=/^[a-f0-9]{64}$/u,QH=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),ZH=new Set(["sourceHash","targetHash","nextJournal"]),eD=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),nS=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),tD=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Su(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function aS(e){return JSON.stringify(e,null,2)+`
248
+ `}function em(e){return e.schema===we?_l(e):en(e)}function Xp(e,t){return{...e,schema:we,minimum_runtime_version:2,revision:t}}function iD(e){return{...e,schema:Ei,minimum_runtime_version:2,revision:1,previousState:Xp(e.previousState,1),nextState:Xp(e.nextState,2)}}function Eu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:ge,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function rD(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?F(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:ar,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Eu(e.previousState),nextState:{...Eu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:pi.definition.metadata.version,skillHash:as}:e.nextRun}}function oS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ra(e,t){return JSON.stringify(_l(e))===JSON.stringify(_l(t))}function sS(e,t){return JSON.stringify(en(e))===JSON.stringify(en(t))}function Oi(e,t){return Zp(e,t)}function nD(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Su(n,eD,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!dn.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!dn.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=mr(n.previousRun),o=mr(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Oi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==nS.size||u.some(f=>!nS.has(f))||l.fromSchema!==we||l.toSchema!==ge||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function ws(e,t){return Qp.join(H(e,t),"schema-migration.json")}function aD(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Su(e,QH,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===Ue&&i.toSchema===we,n=i.fromSchema===we&&i.toSchema===ge;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!dn.test(i.sourceHash)||typeof i.targetHash!="string"||!dn.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?ai(i.nextState):ot(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(F((0,Pu.stringify)(em(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Su(i.transition,ZH,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!dn.test(l.sourceHash)||typeof l.targetHash!="string"||!dn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?mp(l.nextJournal,t):pp(l.nextJournal,t);if(F(JSON.stringify(l.nextJournal,null,2)+`
249
+ `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===we?Ra(a,u.previousState)||Ra(a,u.nextState):a.schema===ge&&(sS(a,u.previousState)||sS(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==ge)throw new Error("Schema migration transition supersede target schema is invalid");s=nD(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Su(i.runRetreat,tD,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=mr(l.previousRun),d=mr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!dn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==ge||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function ys(e,t){let i=ws(e,t),r=j(e,i);await T(r,i);try{let n=await nl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return aD(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function oD(e,t,i){let r=await Qn(e,t),n=r?await wl(e,r):await yl(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Nh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new na(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Sh(e,t,n)}async function lS(e){try{return await Gt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function sD(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function uS(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await Ye(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Zp(o.event,sD(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function cD(e,t,i){if(!t.transitionSupersede)return;let r=We(e,t.change),n=await lS(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await Ie(a),s=await uS(e,t),c=await Zn(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Oi(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==F(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function lD(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await Ie(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Oi(a,r.nextRun)){if(!Oi(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Zr(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Oi(await Ie(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await uS(e,t);if(o.sequence===null){let l=await kr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await on({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=We(e,t.change),c=await lS(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await cS.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function uD(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await Ie(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Oi(n,t.runRetreat.nextRun)){if(!Oi(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Zr(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await Ye(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await kr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await on({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function dD(e,t,i){let r=await ys(e,t);if(!r)return null;if(await oa(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Qp.join(re(e,t),Re),a=await Gt(n);if(await cD(e,r,a===r.targetHash),await oD(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await ue(n,(0,Pu.stringify)(em(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=We(e,t),s=await Gt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await te(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await lD(e,r,i),await uD(e,r,i),await cS.rm(ws(e,t),{force:!0}),r.nextState}async function fD(e){let t=H(e.paths,e.state.name),i=await Ie(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:we,toSchema:ge,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function hD(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Ra(i,t.previousState),a=Ra(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await Ie(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Oi(s,t.previousRun),l=Oi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await Ye(o,t.nextRun.trajectoryRef)).map((N,y)=>({event:N,index:y})).filter(({event:N})=>N.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let N={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Zp(f.event,N)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Eu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,m=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await Gt(We(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:h,evidenceHash:m,eventData:{fromSchema:we,toSchema:ge,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function pD(e){let t,i,r,n;if(e.state.schema===Ue){if(t=Xp(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Ur)throw new Error("Native v1 change has a transition from another schema generation");let s=iD(e.pendingTransition.journal);if(oS(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(oS(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=We(e.paths,e.name);i={sourceHash:await Gt(c),targetHash:F(aS(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Ei)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await hD({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=rD(s);if(Ra(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Ra(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=We(e.paths,e.name);i={sourceHash:await Gt(u),targetHash:F(aS(l)),nextJournal:l}}}else t=Eu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await fD({paths:e.paths,state:e.state,migrationId:e.id}));let a=Qp.join(re(e.paths,e.name),Re),o=(0,Pu.stringify)(em(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Ue?we:ge,sourceHash:await Gt(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function dS(e){return he(e.paths,`migrate schema for ${e.name}`,()=>sn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await dD(e.paths,e.name,e.hooks);if(i?.schema===ge)return i;let r=await ui(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await oa(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==Ue&&n.schema!==we)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await vp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await pD({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??XH()}),s=ws(e.paths,e.name),c=j(e.paths,s);await T(c,s),await te(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Hi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),gD=512*1024,fn=/^([a-f0-9]{64})\.json$/u,wD=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,yD=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Ru=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function rm(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function yi(e,t){return rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function vS(e,t){return rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function xa(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Qe(e,t){return e<t?-1:e>t?1:0}function ND(e,t){let i=se.relative(e.projectRoot,t);if(i.length===0||se.isAbsolute(i)||i===".."||i.startsWith(`..${se.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(se.sep).join("/")}function gS(e,t){return se.join(H(e,t),"evidence")}function xu(e,t){return ND(e,gS(e,t))}async function Cu(e,t){let i=se.resolve(e),r=se.resolve(t);if(!$(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=se.relative(i,r).split(se.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=se.join(o,s));let c=await X.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await X.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...xa(c)})}return a}async function Ot(e){for(let t of e){let i=await X.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!rm(t,i)||await X.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function wS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:ma(e,t)}function fS(e){return e!==null&&yD.test(e)?[e]:[]}function bD(e,t,i,r){if(e==="snapshots")return{canonical:la(i,t),dependencies:[]};if(e==="scopes"){let a=ua(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Ml(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[ma("scopes",a.scopeHash)]}}if(e==="verifications"){let a=es(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(fS));return{canonical:a,dependencies:[a.implementationScopeRef,Rb(a.reportHash),...fS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||mD("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Ll(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=Fl(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function $r(e){let t=await X.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?gD:br;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await X.realpath(e.file);if(!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":tm.O_RDONLY|tm.O_NOFOLLOW|tm.O_NONBLOCK,a=await X.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!yi(xa(t),o)||!yi(xa(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let y=i+1-d,E=await a.read(u,0,Math.min(u.length,y),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,p,v]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Ot(e.directoryChain),!p.isFile()||p.isSymbolicLink()||v!==r||!yi(xa(o),f)||!yi(xa(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),m;try{m=JSON.parse(h)}catch(y){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:y})}let N=bD(e.kind,e.hash,m,e.name);if(h!==JSON.stringify(N.canonical,null,2)+`
250
+ `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:xa(f),directoryChain:e.directoryChain,dependencies:[...new Set(N.dependencies)].sort(Qe)}}finally{await a.close()}}async function hS(e){try{return await X.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function kD(e){let t=H(e.paths,e.name),i=t,r=gS(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Cu(t,r);n=await X.readdir(r,{withFileTypes:!0}),await Ot(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Ru){if(!n.some(f=>f.name===s))continue;let c=se.join(r,s),l=await Cu(t,c),u=(await X.readdir(c,{withFileTypes:!0})).sort((f,p)=>Qe(f.name,p.name)),d=new Map;for(let f of u){let p=wD.exec(f.name);if(!p)continue;let v=d.get(p[1])??[];v.push(f),d.set(p[1],v)}for(let[f,p]of[...d.entries()].sort(([v],[h])=>Qe(v,h))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=p[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let h=se.join(c,f),m=fn.exec(f)?.[1];if(!m)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let N=wS(s,m),y=se.join(c,v.name),E=await $r({changeRoot:i,file:y,ref:N,kind:s,hash:m,name:e.name,directoryChain:l}),S=await hS(h),k=S?null:await $r({changeRoot:i,file:h,ref:N,kind:s,hash:m,name:e.name,directoryChain:l});a.push({ref:N,original:h,quarantine:y,document:E,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Qe);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ca(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Au(o)}`),path:xu(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Qe(c.ref,l.ref))){if(await Ot(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await $r({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:fn.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await $r({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:fn.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!yi(s.originalDocument.identity,d.identity)||!yi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain);continue}if(!await hS(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await X.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!yi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await X.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await $r({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:fn.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await $r({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:fn.exec(se.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!vS(s.document.identity,l.identity)||!yi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await X.rm(s.quarantine),await Ot(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ca(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Au(o)}`),path:xu(e.paths,e.name)}]}}async function SD(e,t){let i=H(e,t),r=i,n=se.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Cu(i,n);a=await X.readdir(n,{withFileTypes:!0}),await Ot(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Ru.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Qe);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Au(o)}`);let s=[],c=0;for(let l of Ru){if(!a.some(p=>p.name===l))continue;let u=se.join(n,l),d=await Cu(r,u),f=(await X.readdir(u,{withFileTypes:!0})).sort((p,v)=>Qe(p.name,v.name));await Ot(d);for(let p of f){if(s.length>=Hi.maxDocuments)throw new Error(`Native evidence store exceeds ${Hi.maxDocuments} documents`);let v=fn.exec(p.name);if(!v||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let h=wS(l,v[1]),m=se.join(u,p.name);await T(j(e,m),m);let N=await $r({changeRoot:r,file:m,ref:h,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=N.size,c>Hi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Hi.maxScannedBytes} scanned bytes`);s.push(N)}await Ot(d)}return s}function pS(e,t){let i=new Set,r=[...e].sort(Qe).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(Qe).reverse())i.has(o)||r.push(o)}return i}function ED(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Qe),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(Qe))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function PD(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=pS(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Hi.minimumAgeMs&&a.add(c.ref);for(let c of Ru){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Qe(u.ref,d.ref)).slice(0,Hi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=pS(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Hi.minimumAgeMs).sort((c,l)=>Qe(c.ref,l.ref));return{candidates:ED(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Au(e){let t=e.slice(0,Hi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Ca(e){let t=Hi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function im(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(Qe);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ca(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Au(n)}`),path:r}}async function mS(e,t){try{await X.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await X.rename(e,t)}catch{}}async function RD(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ot(e.directoryChain);let i=await $r({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:fn.exec(se.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await X.lstat(e.file),n=await X.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!yi(e.identity,r)||!yi(e.identity,i.identity)||!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=se.join(se.dirname(e.file),`.${se.basename(e.file)}.${vD()}.gc`);await X.rename(e.file,a);try{let[o,s]=await Promise.all([X.lstat(a),X.realpath(a)]);if(await Ot(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!vS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await mS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await X.rm(a),await Ot(e.directoryChain)}catch(o){throw await mS(a,e.file),o}}async function xD(e){if((await Ne(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await X.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await mt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function CD(e,t){if(t)return[t];let i;try{i=await X.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(Qe)}async function AD(e,t){let i=await ui(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Ii(e,t),ys(e,t),Rr(e,t)]);return r!==null||n!==null||a!==null}async function _D(e){if(await AD(e.paths,e.name))return[];let t=await ui(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await kD({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await SD(e.paths,e.name),a=PD(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=xu(e.paths,e.name);if(!e.repair)return[...i.findings,im(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await RD(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[im(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ca(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,im(e.name,a,!0,o)]}async function yS(e){if(e.deferAll||await xD(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await CD(e.paths,e.name))try{a.push(...await _D({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ca(`Native evidence retention refused to clean ${o}: ${s.message}`),path:xu(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await he(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ca(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as TD,randomUUID as hY}from"crypto";import{promises as ks}from"fs";import ne from"path";var am=64*1024*1024,ID=256*1024,SS=16*1024*1024;async function Ze(e){try{return await ks.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jD(e){let t;try{t=await ks.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await wt(e,i.name);if(r){await xl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function bs(e,t){let i=[];async function r(n){let a=await pt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(n,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await ks.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ie({root:e,file:c,maxBytes:am,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function $D(e,t,i,r){await oi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await pt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await ks.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await oi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await lr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:am,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Aa(e,t,i,r){let n=await bs(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await bs(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ne.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function OD(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function HD(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function DD(e){return`${e}.removing`}function NS(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function ES(e,t,i){return ne.join(ul(e,t).directory,`root-move-cleanup-${i}.json`)}function MD(e){return JSON.stringify(e,null,2)+`
251
+ `}function FD(e){return TD("sha256").update(e).digest("hex")}function LD(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function BD(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(LD);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function qD(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=MD(t);if(Buffer.byteLength(i,"utf8")>SS)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await ue(ES(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),FD(i)}async function VD(e){let t=await ie({root:e.paths.runtimeDir,file:ES(e.paths,e.id,e.cleanup.kind),maxBytes:SS,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return BD(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function nm(e){let t=await bs(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function bS(e){return e.ref.split("/").length}async function WD(e){let i=[...await nm({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>bS(a)-bS(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ne.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await al({root:e.projectRoot,file:a,maxBytes:am,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await nh({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await nm({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await nh({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function PS(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function zD(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function JD(e,t,i,r){for(let a of[e,t])try{let o=await mt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ne.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ie({root:i,file:n,maxBytes:ID,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function kS(e){let t=PS(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await tr(e.projectRoot,t),t}async function Ns(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=PS(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await tr(e.projectRoot,i),i}async function _u(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await Ze(e.target),a=await Ze(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await qD({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await bs(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Ns({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await VD({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await Ze(e.target),a=await Ze(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await fy({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Ns({projectRoot:e.projectRoot,config:t,id:e.id})}return await nm({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Ns({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Ns({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await WD({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Ns({projectRoot:e.projectRoot,config:t,id:e.id})}async function GD(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Ze(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=DD(e.staging);t=await _u({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await bs(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await $D(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Aa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await kS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Ze(e.destinationPaths.nativeRoot)){if(await Ze(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Aa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Ze(e.staging))throw new Error("Native move staging tree is missing");await Aa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await ks.rename(e.staging,e.destinationPaths.nativeRoot)}t=await kS({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Ze(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=HD(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Ze(e.sourcePaths.nativeRoot)&&await Aa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await _u({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await jD(e.destinationPaths);let n=await mt(e.destinationPaths,e.pending.id);await Jn(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await tr(e.projectRoot,o),o}async function RS(e){let t=await Ne(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await Le(e.projectRoot,i.fromArtifactRoot),n=await Le(e.projectRoot,i.toArtifactRoot),a=OD(n,i.id),o=await Ze(r.nativeRoot)?r:n,s=await ir(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await JD(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await Ze(r.nativeRoot))throw v;let h=zD({id:i.id,paths:r,now:new Date});await ky(r,h),c={journal:h,paths:r}}if(e.strategy==="continue"){let v=await GD({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await Ze(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=NS(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Ze(n.nativeRoot)&&await Aa(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await _u({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=NS(a,i.id);!t.native.pending_root_move?.cleanup&&await Ze(a)&&await Aa(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await _u({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await mt(r,i.id);await dl(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await tr(e.projectRoot,p),{activeNativeRoot:r.nativeRoot,config:p}}finally{await rr(s)}}var _a=4096,UD=4096,KD=1024;async function Or(e,t,i){try{let r=await pt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Iu(e,t){let i=new Map(e.map(r=>[xe.resolve(r.file),{...r,file:xe.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await ko(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Jf(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function YD(e,t){let i=Jk(e),r;try{await T(e.projectRoot,i);let n=await wu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await jr(e,r.change)?[]:(await $e(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await Tu.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function XD(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function QD(e,t){let i=[],r=[];for(let n of await Or(e,e.transactionsDir,UD)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await mt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:xe.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Hn([e],`doctor archive recovery ${a.id}`,async()=>await Iu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,"archive.lock")}],i)?(await Yk({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function ZD(e,t,i){let r=[];for(let n of await Or(e,e.locksDir,KD)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=xe.join(e.locksDir,n.name);try{let o=await ko(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await Jf(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function eM(e,t,i=5){let r=[],n=t?await Yp(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Yp(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:xe.join(e.changesDir,a.name,Re)});continue}let o=await Kp(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:xe.join(e.projectRoot,s.path)}:{}})}return r}async function tM(e,t){let i=[],r=t.name?[t.name]:(await Or(e,e.changesDir,_a)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await ea(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await sN(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:xe.join(H(e,n),"trajectory.jsonl")})}return i}async function iM(e,t){let i=[],r=t.name?[t.name]:(await Or(e,e.changesDir,_a)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await bo(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=zr(e,n),s=it(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Hn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Jt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await Tu.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Jt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Tu.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await Tu.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function rM(e,t){let i=[],r=t.name?[t.name]:(await Or(e,e.changesDir,_a)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Ah(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:ia(e,n),repair:"migrate"});continue}let a=await $e(e,n);await wN({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:ia(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:ia(e,n)})}return i}async function nM(e,t){let i=[],r=t.name?[t.name]:(await Or(e,e.changesDir,_a)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=ws(e,n);try{let o=await ys(e,n),s=await ui(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:xe.join(e.changesDir,n,Re)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:xe.join(e.changesDir,n,Re),repair:"migrate"});continue}await dS({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:xe.join(e.changesDir,n,Re)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function aM(e,t){let i=[],r=t.name?[t.name]:(await Or(e,e.changesDir,_a)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Ii(e,n)}catch(o){if(o instanceof os)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:We(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Hn([e],`doctor transition recovery ${n}`,async()=>await Iu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Xb(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:We(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:We(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:We(e,n),repair:"continue"})}}return i}async function oM(e,t){let i=[],r=t.name?[t.name]:(await Or(e,e.changesDir,_a)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Pr(e,n),o;try{o=await Rr(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Hn([e],`doctor checkpoint recovery ${n}`,async()=>await Iu([{paths:e,file:xe.join(e.locksDir,"root-move.lock")},{paths:e,file:xe.join(e.locksDir,`transition-${n}.lock`)}],i)?(await lk(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Ss(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await Ne(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([Le(r.projectRoot,c.fromArtifactRoot),Le(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Iu([{paths:l,file:xe.join(l.locksDir,"root-move.lock")},{paths:u,file:xe.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await RS({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await Le(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await XD(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await QD(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await iM(r,{name:e.name,repair:t})),i.push(...await nM(r,{name:e.name,repair:t})),i.push(...await rM(r,{name:e.name,repair:t})),i.push(...await tM(r,{name:e.name,repair:t})),i.push(...await aM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await oM(r,{name:e.name,repair:t})),i.push(...await yS({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await ZD(r,t,s.unfinished)),i.push(...await YD(r,t)),e.projectOnly||i.push(...await eM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as sM}from"node:crypto";import{promises as He}from"node:fs";import ut from"node:path";var om=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function xS(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function CS(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ut.join(e.archiveDir,t);if(!$(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ju(e){try{return await He.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function AS(e,t){let i=ut.normalize(ut.resolve(e)),r=ut.normalize(ut.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function cM(e,t){let i;try{i=await He.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ut.join(e.archiveDir,n.name);try{let o=await Ge(ut.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function lM(e,t){let i=await il(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function hn(e,t){await He.mkdir(e.transactionsDir,{recursive:!0}),await te(or(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function uM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Cn(e.paths.projectRoot);i.some(a=>AS(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await Ne(a);if(!o)continue;let s=await Le(a,o.native.artifact_root);r.some(c=>AS(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await He.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Ge(ut.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Il(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function dM(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function fM(e){let t=ut.join(e.paths.specsDir,e.change.capability),i=ut.join(t,"spec.md");if(!$(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await He.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await He.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([He.realpath(e.paths.specsDir),He.realpath(t)]);if(!$(o,s))throw new Error("Native canonical capability path escaped");try{let c=await He.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await He.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await He.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ut.join(jt(e.paths,e.state.name),e.change.source);await ue(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await He.mkdir(t,{recursive:!0}),await ue(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function _S(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function hM(e,t){let i=jt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Q({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function pM(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(_S(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function sm(e){return he(e.paths,`archive portable change ${e.name}`,async()=>{let t=dM(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await lM(e.paths,e.name),r=jt(e.paths,e.name),n=await ju(r),a=n?null:await cM(e.paths,e.name),o;if(n)o=await Sa(e.paths,e.name);else if(i)o=await Ge(ut.join(CS(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);if(n&&!o.archived&&i===null){let l=await Vk({paths:e.paths,state:o});if(l.drifted){let u=l.reason??"Native confirmed requirements changed";throw await Wk({paths:e.paths,state:o,reason:u}),new Error(`${u}; Native change returned to Shape and requires confirmation`)}}let s=CS(e.paths,i?.archive_ref??xS(o)),c=await ju(s);if(i&&pM(i,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await ms(e.paths,o.name),await He.rm(it(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)_S(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let l=await uM({paths:e.paths,state:o});if(!o.archived&&l.length>0&&t!==o.name)throw new om(l);i={schema:tl,id:sM(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:xS(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await hM(e.paths,o),created_at:new Date().toISOString()},await hn(e.paths,i)}if(!n&&c&&i.status==="report-aligned")i={...i,status:"moved"},await hn(e.paths,i);else if(!n&&c&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);if(i.status==="prepared"){for(let l=i.next_spec_index;l<i.spec_changes.length;l+=1)await fM({paths:e.paths,state:o,change:i.spec_changes[l]}),i={...i,next_spec_index:l+1},await hn(e.paths,i),await e.hooks?.afterSpecApplied?.(l);i={...i,status:"specs-applied"},await hn(e.paths,i)}if(i.status==="specs-applied"){if(!o.archived){let l={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Gr({file:bt(e.paths,o.name),expectedStateVersion:o.state_version,next:l,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await hn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let l=await ju(r)?r:s;if(await vu({file:ut.join(l,"verification.md"),state:o}),await mu({file:ut.join(l,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await hn(e.paths,i),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(await He.mkdir(e.paths.archiveDir,{recursive:!0}),await ju(s))throw new Error(`Native Archive target already exists: ${s}`);await He.rename(r,s),i={...i,status:"moved"},await hn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await ms(e.paths,o.name),await He.rm(it(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await He.rm(or(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:s,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function $u(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ou(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function mM(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Hu(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:$u({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ou("summary","--summary"),mM(e.name,e.flag)]}}function cm(e){return[Hu({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Hu({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Du(e,t){let i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[]},r=n=>({kind:n,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:r("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ou("summary","--summary")],commandAlternatives:[Hu({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...cm({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:$u({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ou("summary","--summary")],commandAlternatives:[Hu({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...cm({change:e.name,stateVersion:e.state_version})],runnerAction:r("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ou("summary","--summary")],commandAlternatives:cm({change:e.name,stateVersion:e.state_version}),runnerAction:r("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:r("none")};if(e.status==="blocked"){let n=e.blockers.some(({resolution_action:a})=>a==="retry-verifier");return{...i,disposition:"blocked",action:n?"retry-verifier":"none",commandArgs:n?$u({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:n?["summary"]:["repair-runtime"],inputOptions:n?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:r(n?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:"continue",action:"confirm-shape",commandArgs:$u({change:e.name,stateVersion:e.state_version,action:"confirm-shape",flag:"--confirmed"}),requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:r("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:r("none")};if(t.allDone)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:r("none")};let n=t.children.some(({status:o})=>o==="blocked"),a=t.children.some(({status:o})=>o==="ready"||o==="active");return{...i,disposition:n&&!a?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:n&&!a?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:r("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[]}}],runnerAction:r("builder-handoff")}}if(e.phase==="verify"){let n=e.loop.next_action==="await-verifier-result";return{...i,disposition:"continue",action:n?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[n?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:n?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:[]}}],runnerAction:r(n?"await-verifier":"dispatch-verifier")}}return{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:r("none")}}import{randomUUID as vM}from"node:crypto";import{promises as Ta}from"node:fs";import DS from"node:path";var lm=["evidence.md","repair.md","archive.md","checkpoint.md"],gM="verification.md";async function wM(e){try{return await Ta.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function um(e,t){let i=re(e,t),r=[or(e,{kind:"migration",change:t}),zr(e,t),...lm.map(n=>DS.join(i,n))];return(await Promise.all(r.map(wM))).some(Boolean)}async function yM(e,t){let i=await il(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function TS(e,t){await Ta.mkdir(e.transactionsDir,{recursive:!0}),await te(or(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function IS(e,t,i={}){let r=i.removeVerificationReport===!1?lm:[...lm,gM];await Promise.all([Ta.rm(it(e,t),{recursive:!0,force:!0}),Ta.rm(zr(e,t),{recursive:!0,force:!0}),...r.map(n=>Ta.rm(DS.join(re(e,t),n),{force:!0}))])}async function jS(e,t){await _r(un(e,t.name),ln({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function $S(e,t){try{let i=await wt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function OS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=Ae(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function NM(e){let t=re(e.paths,e.state.name),i=await Q({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Uc({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function HS(e,t){let i=await Il(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Es(e){return he(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await yM(e.paths,e.name),i=await jr(e.paths,e.name)?await Ge(bt(e.paths,e.name)):null;if(!t&&i)return await IS(e.paths,e.name,{removeVerificationReport:!1}),await jS(e.paths,i),i;let r=null,n=null;for(t||(r=await HS(e.paths,e.name),n=await $S(e.paths,e.name),OS(e.paths,n),t={schema:el,id:vM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await TS(e.paths,t));;){let a=ry(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await HS(e.paths,e.name),n??=await $S(e.paths,e.name),OS(e.paths,n),i=iy({state:r,acceptance:await NM({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await Zc(bt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await IS(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ge(bt(e.paths,e.name)),await jS(e.paths,i)),t={...t,status:a.nextStatus},await TS(e.paths,t)}return await Ta.rm(or(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ge(bt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as MS}from"node:fs";import FS from"node:path";function bM(e,t){let i=Ae(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function kM(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function SM(e,t){let i=new Date().toISOString(),r=e.verification===null?e:Bn(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:nr(t),completed_at:i});return rt({...r,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:kM(e),verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function EM(e){try{let t=await pu(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function LS(e){return he(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Sa(e.paths,e.name);if(t.status==="done")return await gu({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=bM(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=un(e.paths,e.name),n=await EM(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await _r(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await gu({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=Bp({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Gr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await MS.rm(FS.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=ln({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await _r(r,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=SM(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.");t=await Gr({file:bt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=ln({portableState:t,projectRoot:e.paths.projectRoot,branch:Ae(e.paths.projectRoot).currentBranch});return await MS.mkdir(FS.dirname(un(e.paths,t.name)),{recursive:!0}),await _r(r,d,{containedRoot:e.paths.runtimeDir}),await gu({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as BS}from"node:fs";function PM(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function RM(e,t){let i=Ae(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:e.projectRoot,isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}async function Ia(e){let t=await zk(e),i=t.state.status==="active"&&t.state.loop.stage!=="done",r=RM(e.paths,t.state),n=await fs({paths:e.paths,state:t.state}),a=Du(t.state,n),o=r.bindingState==="mismatch"?{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...a.runnerAction,kind:"none"}}:a;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,loop:t.state.loop,acceptance:PM(t.state),verificationResult:t.state.verification_result,blockers:t.state.blockers,builderHandoff:t.state.builder_handoff,verification:t.state.verification,history:t.state.history,historyOverflow:t.state.history_overflow,workspace:r,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{children:n.children,readyChildren:n.readyChildren}:{},continuation:o,...e.details?{details:{acceptance:t.state.acceptance,specChanges:t.state.spec_changes,workspace:t.state.workspace,verificationReport:t.state.verification_report}}:{}}}async function qS(e){let t;try{t=await BS.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await BS.readFile(`${jt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import Ps from"path";import{realpathSync as _M}from"fs";var Mu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var VS=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],fm=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:VS,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page.","--details Include acceptance, Spec, workspace, and report details."],output:"A v2 status page or one portable Loop projection with local execution availability and continuation.runnerAction; parent changes also expose children and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker]
252
+ comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."],output:"The portable state, explicit skill-coordinated label, Runtime-owned check results, complete verifierDispatch, bounded request-check response, continuation.runnerAction, and machine-readable continuation.inputOptions. This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.",examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
253
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function dm(e,t){return`${e}:
254
254
  ${t.map(i=>` ${i}`).join(`
255
- `)}`}function RD(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return zp[i]||t.length>1&&zp[t[0]]?.subcommands?i:t[0]}function xD(e=[]){let t=RD(e),i=zp[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Wp("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...mS];return n&&n.length>0&&r.push("",Wp("Options",n)),r.push("",`Output:
256
- ${i.output}`),i.examples&&r.push("",Wp("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
255
+ `)}`}function xM(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return fm[i]||t.length>1&&fm[t[0]]?.subcommands?i:t[0]}function CM(e=[]){let t=xM(e),i=fm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",dm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...VS];return n&&n.length>0&&r.push("",dm("Options",n)),r.push("",`Output:
256
+ ${i.output}`),i.examples&&r.push("",dm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
257
257
  `)}
258
- `}}var CD=xD().usage;var MY=10*1024*1024,$t=class extends Error{};function xu(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new $t(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Cu(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new $t(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new $t(`${t} requires a value`);return e.splice(r,2),n}function gS(e){if(e.length>0)throw new $t(`Unexpected argument: ${e[0]}`)}function vS(e,t){let i=Jp.normalize(e),r=Jp.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function AD(e){let t=Jp.resolve(e),i=Ae(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ae(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!vS(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||vS(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:i.currentWorktreeRoot}async function wS(e){return e?AD(e):_f(process.cwd())}async function yS(e){let t=await Pe(e);return dt(e,t?.native.artifact_root??"docs")}function Oi(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
259
- `}}function NS(e,t){if(t instanceof $t)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof du)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 fs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Lo)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 Bo)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 Ru)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Qn)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 Er)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ss)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function bS(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
260
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function _D(e){let t;try{t=await ES.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function TD(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function kS(e,t){let i;try{i=await ES.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${TD(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:_u.join(e.archiveDir,n.name)}:null}function ID(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function Au(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function SS(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:_u.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function jD(e,t){let i=[],r=[];for(let n of await Mw(e)){let a=Gr(n);if(t&&a.change!==t)continue;let o=_u.join(e.transactionsDir,n);try{let s=await Po(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function Gp(e,t){let i=xu(e,"--repair"),r=Cu(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new $t("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();gS(e);let a=await yS(t),o=await jD(a,n);if(n&&o.findings.length>0){if(r)throw new $t("--strategy is only available to the legacy transaction doctor");let d=await _r(a,n)?await Ra({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await qp({paths:a,name:n});return Oi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:jr(v.state)})}let h=await Ns({paths:a,name:n});return Oi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:jr(h)})}return Au({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await _r(a,n)){if(r)throw new $t("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([kS(a,n),Vp(a,n)]);if(u){let h=await Ra({paths:a,name:n,details:!0});return Au({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await Ra({paths:a,name:n,details:!0});return Au({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[SS(a,n)],continuation:h.continuation})}if(i){if(d){let v=await Ns({paths:a,name:n});return Oi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:jr(v)})}let h=await fS({paths:a,name:n});return Oi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:jr(h.state)})}let f=await Ra({paths:a,name:n,details:!0});return Oi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await Ns({paths:a,name:n});return Oi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:jr(u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await pS(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new $t("--strategy is only available to the legacy transaction doctor");if(i){let k=await ys({paths:a,repair:!0,projectOnly:!0}),N=[];for(let g of c.transactions)g.kind==="archive"?await qp({paths:a,name:g.change}):await Ns({paths:a,name:g.change}),N.push({kind:g.kind,change:g.change,transactionId:g.journal.id});let R=await Gp([],t),w=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...w,repaired:!0,repairedPortableTransactions:N,repairFindings:k.findings}}}let u=await _D(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[v,p,m,b,y]=await Promise.all([Promise.all(s.map(k=>Ra({paths:a,name:k}))),Promise.all(s.map(k=>kS(a,k))),Promise.all(s.map(k=>Vp(a,k))),Promise.all(h.map(k=>ys({paths:a,name:k}))),ys({paths:a,projectOnly:!0})]),P=ID([...p.filter(k=>k!==null),...s.flatMap((k,N)=>m[N]&&!f.has(k)?[SS(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:_u.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...b.flatMap(({findings:k})=>k),...y.findings]),S={healthy:P.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:h,findings:P};return S.healthy?Oi("doctor",S):Au(S)}let l=await ys({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Oi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}function $D(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
261
- `}}async function PS(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{xu(n,"--json"),s=Cu(n,"--project-root");let u=[...n,...a],d=await wS(s);c=await t(u,d)}catch(u){c=NS(e,u)}let l=o?$D(c):bS(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
258
+ `}}var AM=CM().usage;var d4=10*1024*1024,Ht=class extends Error{};function Fu(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Ht(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function Lu(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Ht(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new Ht(`${t} requires a value`);return e.splice(r,2),n}function zS(e){if(e.length>0)throw new Ht(`Unexpected argument: ${e[0]}`)}function hm(e,t){let i=Ps.normalize(WS(e)),r=Ps.normalize(WS(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function WS(e){let t=Ps.resolve(e);try{return _M.native(t)}catch{return t}}function TM(e){let t=Ps.resolve(e),i=Ae(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ae(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!hm(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||hm(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:hm(process.cwd(),i.currentWorktreeRoot)?Ps.resolve(process.cwd()):i.currentWorktreeRoot}async function JS(e){return e?TM(e):Bf(process.cwd())}async function GS(e){let t=await Ne(e);return Le(e,t?.native.artifact_root??"docs")}function Di(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
259
+ `}}function US(e,t){if(t instanceof Ht)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof yu)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 vs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof qo)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 Vo)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 Mu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof na)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 xr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ls)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function KS(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
260
+ `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function Rs(e,t){let i=await fs({paths:e,state:t});return Du(t,i)}async function IM(e){let t;try{t=await QS.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function jM(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function YS(e,t){let i;try{i=await QS.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${jM(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:qu.join(e.archiveDir,n.name)}:null}function $M(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function Bu(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function XS(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:qu.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function OM(e,t){let i=[],r=[];for(let n of await cy(e)){let a=Yr(n);if(t&&a.change!==t)continue;let o=qu.join(e.transactionsDir,n);try{let s=await xo(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function pm(e,t){let i=Fu(e,"--repair"),r=Lu(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Ht("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();zS(e);let a=await GS(t),o=await OM(a,n);if(n&&o.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let d=await jr(a,n)?await Ia({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await sm({paths:a,name:n});return Di("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Rs(a,v.state)})}let p=await Es({paths:a,name:n});return Di("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:p.schema,stateVersion:p.state_version},state:p,continuation:await Rs(a,p)})}return Bu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await jr(a,n)){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([YS(a,n),um(a,n)]);if(u){let p=await Ia({paths:a,name:n,details:!0});return Bu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[u],continuation:p.continuation})}if(d&&!i){let p=await Ia({paths:a,name:n,details:!0});return Bu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[XS(a,n)],continuation:p.continuation})}if(i){if(d){let v=await Es({paths:a,name:n});return Di("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Rs(a,v)})}let p=await LS({paths:a,name:n});return Di("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:p,continuation:await Rs(a,p.state)})}let f=await Ia({paths:a,name:n,details:!0});return Di("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await Es({paths:a,name:n});return Di("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Rs(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await qS(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Ht("--strategy is only available to the legacy transaction doctor");if(i){let k=await Ss({paths:a,repair:!0,projectOnly:!0}),b=[];for(let g of c.transactions)g.kind==="archive"?await sm({paths:a,name:g.change}):await Es({paths:a,name:g.change}),b.push({kind:g.kind,change:g.change,transactionId:g.journal.id});let R=await pm([],t),w=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...w,repaired:!0,repairedPortableTransactions:b,repairFindings:k.findings}}}let u=await IM(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),p=u.filter(k=>!d.has(k)),[v,h,m,N,y]=await Promise.all([Promise.all(s.map(k=>Ia({paths:a,name:k}))),Promise.all(s.map(k=>YS(a,k))),Promise.all(s.map(k=>um(a,k))),Promise.all(p.map(k=>Ss({paths:a,name:k}))),Ss({paths:a,projectOnly:!0})]),E=$M([...h.filter(k=>k!==null),...s.flatMap((k,b)=>m[b]&&!f.has(k)?[XS(a,k)]:[]),...c.findings,...p.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:qu.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...N.flatMap(({findings:k})=>k),...y.findings]),S={healthy:E.every(k=>k.severity==="info"),workflow:p.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:p,findings:E};return S.healthy?Di("doctor",S):Bu(S)}let l=await Ss({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Di("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}function HM(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
261
+ `}}async function ZS(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{Fu(n,"--json"),s=Lu(n,"--project-root");let u=[...n,...a],d=await JS(s);c=await t(u,d)}catch(u){c=US(e,u)}let l=o?HM(c):KS(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
262
262
  `)?"":`
263
- `)),l.exitCode}process.exitCode=await PS("doctor",Gp);
263
+ `)),l.exitCode}process.exitCode=await ZS("doctor",pm);