@rpamis/comet 0.4.0-rc.2 → 0.4.0-rc.4

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 (419) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +2 -1
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-archive.mjs +55 -55
  5. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +56 -56
  6. package/assets/skills/comet/scripts/comet-guard.mjs +80 -80
  7. package/assets/skills/comet/scripts/comet-handoff.mjs +69 -69
  8. package/assets/skills/comet/scripts/comet-hook-guard.mjs +47 -47
  9. package/assets/skills/comet/scripts/comet-hook-router.mjs +140 -137
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +57 -57
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +133 -133
  12. package/assets/skills/comet/scripts/comet-state.mjs +73 -73
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
  14. package/assets/skills/comet-native/SKILL.md +8 -9
  15. package/assets/skills/comet-native/reference/artifacts.md +1 -2
  16. package/assets/skills/comet-native/reference/clarification.md +6 -6
  17. package/assets/skills/comet-native/reference/commands.md +5 -2
  18. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +120 -119
  19. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +136 -135
  20. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +77 -76
  21. package/assets/skills/comet-native/scripts/comet-native-init.mjs +61 -60
  22. package/assets/skills/comet-native/scripts/comet-native-new.mjs +128 -127
  23. package/assets/skills/comet-native/scripts/comet-native-next.mjs +133 -132
  24. package/assets/skills/comet-native/scripts/comet-native-root.mjs +70 -69
  25. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +170 -169
  26. package/assets/skills/comet-native/scripts/comet-native-select.mjs +112 -111
  27. package/assets/skills/comet-native/scripts/comet-native-show.mjs +102 -101
  28. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +110 -109
  29. package/assets/skills/comet-native/scripts/comet-native-status.mjs +108 -107
  30. package/assets/skills-zh/comet-native/SKILL.md +8 -9
  31. package/assets/skills-zh/comet-native/reference/artifacts.md +1 -2
  32. package/assets/skills-zh/comet-native/reference/clarification.md +6 -6
  33. package/assets/skills-zh/comet-native/reference/commands.md +5 -2
  34. package/dist/app/commands/bundle.d.ts.map +1 -1
  35. package/dist/app/commands/bundle.js.map +1 -1
  36. package/dist/app/commands/dashboard.d.ts +1 -1
  37. package/dist/app/commands/dashboard.js +1 -1
  38. package/dist/app/commands/doctor.d.ts.map +1 -1
  39. package/dist/app/commands/doctor.js +1 -1
  40. package/dist/app/commands/doctor.js.map +1 -1
  41. package/dist/app/commands/init.js +2 -2
  42. package/dist/app/commands/init.js.map +1 -1
  43. package/dist/app/commands/platform-select-prompt.d.ts.map +1 -1
  44. package/dist/app/commands/platform-select-prompt.js +1 -0
  45. package/dist/app/commands/platform-select-prompt.js.map +1 -1
  46. package/dist/app/commands/update.d.ts.map +1 -1
  47. package/dist/app/commands/update.js +12 -5
  48. package/dist/app/commands/update.js.map +1 -1
  49. package/dist/domains/agent-learning/policy-compiler.d.ts.map +1 -1
  50. package/dist/domains/agent-learning/policy-compiler.js.map +1 -1
  51. package/dist/domains/agent-learning/types.d.ts.map +1 -1
  52. package/dist/domains/agent-learning/types.js.map +1 -1
  53. package/dist/domains/bundle/authoring.d.ts.map +1 -1
  54. package/dist/domains/bundle/authoring.js.map +1 -1
  55. package/dist/domains/bundle/next-action.d.ts.map +1 -1
  56. package/dist/domains/bundle/next-action.js.map +1 -1
  57. package/dist/domains/bundle/readiness-user-summary.d.ts.map +1 -1
  58. package/dist/domains/bundle/readiness-user-summary.js.map +1 -1
  59. package/dist/domains/bundle/types.d.ts.map +1 -1
  60. package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
  61. package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
  62. package/dist/domains/comet-entry/current-selection.d.ts.map +1 -1
  63. package/dist/domains/comet-entry/current-selection.js.map +1 -1
  64. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  65. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  66. package/dist/domains/comet-entry/types.d.ts.map +1 -1
  67. package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
  68. package/dist/domains/comet-memory/personal-memory.js +41 -0
  69. package/dist/domains/comet-memory/personal-memory.js.map +1 -1
  70. package/dist/domains/comet-memory/types.d.ts +7 -0
  71. package/dist/domains/comet-memory/types.d.ts.map +1 -1
  72. package/dist/domains/comet-memory/types.js.map +1 -1
  73. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  74. package/dist/domains/comet-native/native-archive-command.js +114 -19
  75. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  76. package/dist/domains/comet-native/native-artifacts.d.ts +1 -0
  77. package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
  78. package/dist/domains/comet-native/native-artifacts.js +53 -2
  79. package/dist/domains/comet-native/native-artifacts.js.map +1 -1
  80. package/dist/domains/comet-native/native-atomic-file.d.ts +1 -0
  81. package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
  82. package/dist/domains/comet-native/native-atomic-file.js +19 -0
  83. package/dist/domains/comet-native/native-atomic-file.js.map +1 -1
  84. package/dist/domains/comet-native/native-children.d.ts +2 -0
  85. package/dist/domains/comet-native/native-children.d.ts.map +1 -1
  86. package/dist/domains/comet-native/native-children.js +16 -4
  87. package/dist/domains/comet-native/native-children.js.map +1 -1
  88. package/dist/domains/comet-native/native-cli-help.js +7 -7
  89. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  90. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  91. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  92. package/dist/domains/comet-native/native-doctor-command.js +41 -1
  93. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  94. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  95. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  96. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  97. package/dist/domains/comet-native/native-lock.js +10 -1
  98. package/dist/domains/comet-native/native-lock.js.map +1 -1
  99. package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -0
  100. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  101. package/dist/domains/comet-native/native-loop-runtime.js +50 -5
  102. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  103. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  104. package/dist/domains/comet-native/native-next-command.js +64 -7
  105. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  106. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
  107. package/dist/domains/comet-native/native-output-language.js.map +1 -1
  108. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
  109. package/dist/domains/comet-native/native-portable-archive.js +17 -1
  110. package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
  111. package/dist/domains/comet-native/native-portable-continuation.d.ts +11 -4
  112. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  113. package/dist/domains/comet-native/native-portable-continuation.js +201 -44
  114. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  115. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -1
  116. package/dist/domains/comet-native/native-portable-migration.js.map +1 -1
  117. package/dist/domains/comet-native/native-portable-recovery.d.ts +2 -1
  118. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
  119. package/dist/domains/comet-native/native-portable-recovery.js +28 -3
  120. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
  121. package/dist/domains/comet-native/native-portable-runtime.d.ts +28 -1
  122. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  123. package/dist/domains/comet-native/native-portable-runtime.js +276 -14
  124. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  125. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  126. package/dist/domains/comet-native/native-portable-state.js +6 -0
  127. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  128. package/dist/domains/comet-native/native-portable-status.d.ts +5 -0
  129. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
  130. package/dist/domains/comet-native/native-portable-status.js +21 -1
  131. package/dist/domains/comet-native/native-portable-status.js.map +1 -1
  132. package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
  133. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  134. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  135. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  136. package/dist/domains/comet-native/native-runner-input.js +26 -31
  137. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  138. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  139. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  140. package/dist/domains/comet-native/native-supervisor-overlay.d.ts +30 -0
  141. package/dist/domains/comet-native/native-supervisor-overlay.d.ts.map +1 -0
  142. package/dist/domains/comet-native/native-supervisor-overlay.js +202 -0
  143. package/dist/domains/comet-native/native-supervisor-overlay.js.map +1 -0
  144. package/dist/domains/comet-native/native-supervisor.d.ts +11 -1
  145. package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
  146. package/dist/domains/comet-native/native-supervisor.js +68 -3
  147. package/dist/domains/comet-native/native-supervisor.js.map +1 -1
  148. package/dist/domains/comet-native/native-types.d.ts +1 -0
  149. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  150. package/dist/domains/comet-native/native-verification-receipt.d.ts.map +1 -1
  151. package/dist/domains/comet-native/native-verification-receipt.js.map +1 -1
  152. package/dist/domains/comet-native/native-workspace-finish.d.ts +12 -1
  153. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
  154. package/dist/domains/comet-native/native-workspace-finish.js +77 -22
  155. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
  156. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  157. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  158. package/dist/domains/comet-plugin/integration.d.ts +2 -0
  159. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  160. package/dist/domains/comet-plugin/integration.js +10 -6
  161. package/dist/domains/comet-plugin/integration.js.map +1 -1
  162. package/dist/domains/dashboard/collector.js +1 -1
  163. package/dist/domains/dashboard/default-plugin-host.d.ts +3 -0
  164. package/dist/domains/dashboard/default-plugin-host.d.ts.map +1 -1
  165. package/dist/domains/dashboard/default-plugin-host.js +38 -4
  166. package/dist/domains/dashboard/default-plugin-host.js.map +1 -1
  167. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  168. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  169. package/dist/domains/dashboard/web/assets/abnfDiagram-VCTEODGH-Bql0JkFh.js +1 -0
  170. package/dist/domains/dashboard/web/assets/arc-CCUY9L8x.js +1 -0
  171. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-F2w5dggy.js +1 -0
  172. package/dist/domains/dashboard/web/assets/architectureDiagram-5GKGNRK7-iYP_D3CC.js +36 -0
  173. package/dist/domains/dashboard/web/assets/array-BifhSqXX.js +1 -0
  174. package/dist/domains/dashboard/web/assets/blockDiagram-I7D4REHJ-DyW07-ad.js +129 -0
  175. package/dist/domains/dashboard/web/assets/browser-CgwPGwaV.js +107 -0
  176. package/dist/domains/dashboard/web/assets/c4Diagram-7LVT6UL2-DDD_Y9Gj.js +38 -0
  177. package/dist/domains/dashboard/web/assets/channel-DLABCQMO.js +1 -0
  178. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  179. package/dist/domains/dashboard/web/assets/chunk-4HAMMTFA-cZryt4d4.js +62 -0
  180. package/dist/domains/dashboard/web/assets/{chunk-5VM5RSS4-CopXcnFA.js → chunk-5VM5RSS4-ZNzvKenW.js} +2 -2
  181. package/dist/domains/dashboard/web/assets/chunk-75Z2AOVW-Ciqzt_fM.js +2 -0
  182. package/dist/domains/dashboard/web/assets/chunk-DU6HZSFF-0EtIdyLT.js +125 -0
  183. package/dist/domains/dashboard/web/assets/chunk-F27PBJKO-B09yMHfO.js +1 -0
  184. package/dist/domains/dashboard/web/assets/chunk-FOHPRMQF-DHwB1DNv.js +161 -0
  185. package/dist/domains/dashboard/web/assets/chunk-GMAD6QVW-D_hJqXpD.js +72 -0
  186. package/dist/domains/dashboard/web/assets/chunk-GVQU2GXP-DIvLb3as.js +1 -0
  187. package/dist/domains/dashboard/web/assets/chunk-IMKFNOWR-B_oII0H5.js +231 -0
  188. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  189. package/dist/domains/dashboard/web/assets/chunk-L3NEJ4N5-BALKwnUb.js +1 -0
  190. package/dist/domains/dashboard/web/assets/chunk-OSK3NFVY-zA0G74ff.js +10 -0
  191. package/dist/domains/dashboard/web/assets/chunk-P2QGCYS3-B9FFBdWw.js +1 -0
  192. package/dist/domains/dashboard/web/assets/chunk-POPQ4Y6H-Fwh05sRj.js +1 -0
  193. package/dist/domains/dashboard/web/assets/chunk-PWAF6VOD-cCaczJjE.js +1 -0
  194. package/dist/domains/dashboard/web/assets/chunk-SHT3W25Y-ffjS5Q53.js +168 -0
  195. package/dist/domains/dashboard/web/assets/chunk-SVP7TREG-IDmA7lw7.js +88 -0
  196. package/dist/domains/dashboard/web/assets/chunk-TICWLB2K-8Gmmm4In.js +206 -0
  197. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-DS9V6N2-.js +1 -0
  198. package/dist/domains/dashboard/web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  199. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DJ9Y8TBe.js +1 -0
  200. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DJ9Y8TBe.js +1 -0
  201. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DTBreOtW.js +1 -0
  202. package/dist/domains/dashboard/web/assets/cynefin-OW5HDTMX-DQuEyCa9.js +1 -0
  203. package/dist/domains/dashboard/web/assets/cynefinDiagram-5FMLGOSQ-Bb0YxnR5.js +62 -0
  204. package/dist/domains/dashboard/web/assets/cytoscape.esm-CGd-uY3x.js +321 -0
  205. package/dist/domains/dashboard/web/assets/dagre-GXQ25YYZ-DCdqnZ1z.js +4 -0
  206. package/dist/domains/dashboard/web/assets/dagre-PrKaheQc.js +1 -0
  207. package/dist/domains/dashboard/web/assets/defaultLocale-BFoDCU3G.js +1 -0
  208. package/dist/domains/dashboard/web/assets/demo-DrJ2uuUL.js +456 -0
  209. package/dist/domains/dashboard/web/assets/diagram-S7CK7UJ4-CBO5Oebq.js +30 -0
  210. package/dist/domains/dashboard/web/assets/diagram-UQ7AKVKN-Do5KGiae.js +41 -0
  211. package/dist/domains/dashboard/web/assets/diagram-VSXAHHWV-4Xskky28.js +3 -0
  212. package/dist/domains/dashboard/web/assets/diagram-VX7I27RA-DHaxCMg1.js +24 -0
  213. package/dist/domains/dashboard/web/assets/diagram-Z3DM3KII-_b0C8RCs.js +24 -0
  214. package/dist/domains/dashboard/web/assets/dist-D_v6faRz.js +1 -0
  215. package/dist/domains/dashboard/web/assets/ebnfDiagram-PWID7BFC-BlWWQsBx.js +1 -0
  216. package/dist/domains/dashboard/web/assets/erDiagram-RLTQ6QDP-CaZks0yu.js +99 -0
  217. package/dist/domains/dashboard/web/assets/es-DMM6Y5Bv.js +10 -0
  218. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-LE_eXkBk.js +1 -0
  219. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Dhg9N1uf.js +1 -0
  220. package/dist/domains/dashboard/web/assets/ganttDiagram-EL5Y4UJY-BSjOQ_Cg.js +292 -0
  221. package/dist/domains/dashboard/web/assets/gitGraph-4MIJSDKK-DYwq3-1L.js +1 -0
  222. package/dist/domains/dashboard/web/assets/gitGraphDiagram-WWUBYQGX-oVngpACZ.js +106 -0
  223. package/dist/domains/dashboard/web/assets/graphlib-DS17s2tU.js +1 -0
  224. package/dist/domains/dashboard/web/assets/index-7epoYLF6.js +261 -0
  225. package/dist/domains/dashboard/web/assets/index-C5iz4lns.css +1 -0
  226. package/dist/domains/dashboard/web/assets/info-A6RAGUB7-CLoje88f.js +1 -0
  227. package/dist/domains/dashboard/web/assets/infoDiagram-27XIBGKW-sS6zp9EL.js +2 -0
  228. package/dist/domains/dashboard/web/assets/init-C-OQMol4.js +1 -0
  229. package/dist/domains/dashboard/web/assets/ishikawaDiagram-5VMMS53U-kETJqqgb.js +70 -0
  230. package/dist/domains/dashboard/web/assets/journeyDiagram-3NMN7TZE-ByJPB5Tw.js +139 -0
  231. package/dist/domains/dashboard/web/assets/kanban-definition-UXKFOSKX-JKqPn1FZ.js +89 -0
  232. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +257 -0
  233. package/dist/domains/dashboard/web/assets/line-CnHo6lWD.js +1 -0
  234. package/dist/domains/dashboard/web/assets/linear-B2pLEjo4.js +1 -0
  235. package/dist/domains/dashboard/web/assets/marked.esm-BtJme7Pf.js +65 -0
  236. package/dist/domains/dashboard/web/assets/mermaid-parser.core-OtNk5rQN.js +7 -0
  237. package/dist/domains/dashboard/web/assets/mermaid.core-D1ElL3aM.js +44 -0
  238. package/dist/domains/dashboard/web/assets/mindmap-definition-YA3MSWOX-BxJqN_qn.js +96 -0
  239. package/dist/domains/dashboard/web/assets/ordinal-BDEzSJ7C.js +1 -0
  240. package/dist/domains/dashboard/web/assets/packet-AYTQ26CC-DM9DL0wE.js +1 -0
  241. package/dist/domains/dashboard/web/assets/path-fybaL0A-.js +1 -0
  242. package/dist/domains/dashboard/web/assets/pegDiagram-XKGWAZYB-BDe-x6aH.js +1 -0
  243. package/dist/domains/dashboard/web/assets/pie-WAS4IAKB-ClmkkApZ.js +1 -0
  244. package/dist/domains/dashboard/web/assets/pieDiagram-E7YTZNPT-DSFQ6yQn.js +39 -0
  245. package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +3 -0
  246. package/dist/domains/dashboard/web/assets/quadrantDiagram-AXDQQJYC-CV2lLCpu.js +7 -0
  247. package/dist/domains/dashboard/web/assets/radar-RG4KPBEZ-BduOvwgQ.js +1 -0
  248. package/dist/domains/dashboard/web/assets/railroad-74A4TZTK-BYnUo_HE.js +1 -0
  249. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CPiOAGi2.js +1 -0
  250. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-DOuNY-jw.js +1 -0
  251. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DjNccNww.js +1 -0
  252. package/dist/domains/dashboard/web/assets/railroadDiagram-O6MQD6OU-Y0OnScVm.js +1 -0
  253. package/dist/domains/dashboard/web/assets/requirementDiagram-BXWQKSXE-Dqs0b-_F.js +84 -0
  254. package/dist/domains/dashboard/web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  255. package/dist/domains/dashboard/web/assets/sankeyDiagram-P5KCCOFB-DafYyCgJ.js +40 -0
  256. package/dist/domains/dashboard/web/assets/sequenceDiagram-WJ2MYXX4-DEu4sb48.js +162 -0
  257. package/dist/domains/dashboard/web/assets/sizeCapture-INFHLROL-B0uUizjq.js +1 -0
  258. package/dist/domains/dashboard/web/assets/src-je_XM8Ul.js +1 -0
  259. package/dist/domains/dashboard/web/assets/stateDiagram-D77RDMKH-vHbZoYCK.js +1 -0
  260. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-C4dywNHK.js +1 -0
  261. package/dist/domains/dashboard/web/assets/swimlanes-42K2YHIH-DxEqhoUX.js +1 -0
  262. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CHhHUVep.js +8 -0
  263. package/dist/domains/dashboard/web/assets/timeline-definition-24CTP7MA-B4XpTytf.js +120 -0
  264. package/dist/domains/dashboard/web/assets/treeView-Q6P3EWNA-CrismRW3.js +1 -0
  265. package/dist/domains/dashboard/web/assets/treemap-WGGIJYW6-BGFmknIY.js +1 -0
  266. package/dist/domains/dashboard/web/assets/vennDiagram-4TSXK5OY-DphMzj7N.js +34 -0
  267. package/dist/domains/dashboard/web/assets/wardley-WFR3VGLG-DmeLufag.js +1 -0
  268. package/dist/domains/dashboard/web/assets/wardleyDiagram-VM6X3IG4-BUDxONKk.js +78 -0
  269. package/dist/domains/dashboard/web/assets/xychartDiagram-S5SC5T6Z-BjqVHkW2.js +7 -0
  270. package/dist/domains/dashboard/web/index.html +16 -16
  271. package/dist/domains/factory/artifacts.d.ts.map +1 -1
  272. package/dist/domains/factory/artifacts.js.map +1 -1
  273. package/dist/domains/factory/types.d.ts.map +1 -1
  274. package/dist/domains/integrations/codegraph.d.ts.map +1 -1
  275. package/dist/domains/integrations/codegraph.js.map +1 -1
  276. package/dist/domains/project-knowledge/deterministic-extractors.d.ts.map +1 -1
  277. package/dist/domains/project-knowledge/deterministic-extractors.js +7 -6
  278. package/dist/domains/project-knowledge/deterministic-extractors.js.map +1 -1
  279. package/dist/domains/project-knowledge/index-store.d.ts +1 -1
  280. package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
  281. package/dist/domains/project-knowledge/index-store.js +19 -10
  282. package/dist/domains/project-knowledge/index-store.js.map +1 -1
  283. package/dist/domains/project-knowledge/learning.d.ts +1 -0
  284. package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
  285. package/dist/domains/project-knowledge/learning.js +27 -8
  286. package/dist/domains/project-knowledge/learning.js.map +1 -1
  287. package/dist/domains/project-knowledge/local-provider.d.ts +1 -0
  288. package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
  289. package/dist/domains/project-knowledge/local-provider.js +26 -1
  290. package/dist/domains/project-knowledge/local-provider.js.map +1 -1
  291. package/dist/domains/project-knowledge/local-store.d.ts +23 -1
  292. package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
  293. package/dist/domains/project-knowledge/local-store.js +179 -22
  294. package/dist/domains/project-knowledge/local-store.js.map +1 -1
  295. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  296. package/dist/domains/project-knowledge/plugin.js +55 -8
  297. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  298. package/dist/domains/project-knowledge/records.d.ts +2 -0
  299. package/dist/domains/project-knowledge/records.d.ts.map +1 -1
  300. package/dist/domains/project-knowledge/records.js +8 -0
  301. package/dist/domains/project-knowledge/records.js.map +1 -1
  302. package/dist/domains/project-knowledge/types.d.ts +16 -0
  303. package/dist/domains/project-knowledge/types.d.ts.map +1 -1
  304. package/dist/domains/skill/platform-inspect.d.ts +1 -1
  305. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  306. package/dist/domains/skill/platform-inspect.js +50 -10
  307. package/dist/domains/skill/platform-inspect.js.map +1 -1
  308. package/dist/domains/skill/platform-install.d.ts +10 -5
  309. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  310. package/dist/domains/skill/platform-install.js +107 -17
  311. package/dist/domains/skill/platform-install.js.map +1 -1
  312. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  313. package/dist/domains/skill/uninstall.js +38 -61
  314. package/dist/domains/skill/uninstall.js.map +1 -1
  315. package/dist/domains/workflow-contract/contained-atomic-write.d.ts +1 -0
  316. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  317. package/dist/domains/workflow-contract/contained-atomic-write.js +19 -0
  318. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  319. package/dist/domains/workflow-contract/global-config.d.ts +8 -0
  320. package/dist/domains/workflow-contract/global-config.d.ts.map +1 -1
  321. package/dist/domains/workflow-contract/global-config.js +25 -0
  322. package/dist/domains/workflow-contract/global-config.js.map +1 -1
  323. package/dist/domains/workflow-contract/index.d.ts +1 -1
  324. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  325. package/dist/domains/workflow-contract/index.js +1 -1
  326. package/dist/domains/workflow-contract/index.js.map +1 -1
  327. package/dist/domains/workflow-contract/project-config.d.ts +1 -1
  328. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  329. package/dist/domains/workflow-contract/project-config.js +1 -0
  330. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  331. package/dist/domains/workflow-contract/protected-project-path.d.ts +4 -1
  332. package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
  333. package/dist/domains/workflow-contract/protected-project-path.js +25 -1
  334. package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
  335. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  336. package/dist/platform/fs/race-safe-read.d.ts +14 -0
  337. package/dist/platform/fs/race-safe-read.d.ts.map +1 -1
  338. package/dist/platform/fs/race-safe-read.js +81 -0
  339. package/dist/platform/fs/race-safe-read.js.map +1 -1
  340. package/dist/platform/install/platforms.d.ts +4 -0
  341. package/dist/platform/install/platforms.d.ts.map +1 -1
  342. package/dist/platform/install/platforms.js +15 -3
  343. package/dist/platform/install/platforms.js.map +1 -1
  344. package/dist/platform/paths/project-knowledge-storage.d.ts +1 -1
  345. package/dist/platform/paths/project-knowledge-storage.d.ts.map +1 -1
  346. package/dist/platform/paths/project-knowledge-storage.js +9 -4
  347. package/dist/platform/paths/project-knowledge-storage.js.map +1 -1
  348. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +13 -13
  349. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +13 -13
  350. package/package.json +24 -24
  351. package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BkUJc7LK.js +0 -1
  352. package/dist/domains/dashboard/web/assets/arc-DY4Y9tSO.js +0 -1
  353. package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-7wC9YZS-.js +0 -36
  354. package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-Biqe-SaL.js +0 -132
  355. package/dist/domains/dashboard/web/assets/c4Diagram-5PPSVZJV-CccUFD1S.js +0 -10
  356. package/dist/domains/dashboard/web/assets/channel-DnRvSkOm.js +0 -1
  357. package/dist/domains/dashboard/web/assets/chunk-2GRJ4B5K-BUL4dDxo.js +0 -1
  358. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-BnKtDH9O.js +0 -1
  359. package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-C9pHQ1n3.js +0 -231
  360. package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-CxrbngCi.js +0 -88
  361. package/dist/domains/dashboard/web/assets/chunk-GF5L2VYU-01mzgCUh.js +0 -206
  362. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-wTiZVDvw.js +0 -1
  363. package/dist/domains/dashboard/web/assets/chunk-KBJHAD2P-Bxdv5bl-.js +0 -1
  364. package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-B5vF9l9A.js +0 -1
  365. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-Dra3NnDp.js +0 -1
  366. package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-D3E-rgaQ.js +0 -1
  367. package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-D3E-rgaQ.js +0 -1
  368. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DC96ge-n.js +0 -1
  369. package/dist/domains/dashboard/web/assets/cynefin-VYW2F7L2-Tt_NiopT.js +0 -166
  370. package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-BQ5__1hv.js +0 -62
  371. package/dist/domains/dashboard/web/assets/cytoscape.esm-D3_iZ_3b.js +0 -321
  372. package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-Cr2zq3ro.js +0 -4
  373. package/dist/domains/dashboard/web/assets/defaultLocale-DX6XiGOO.js +0 -1
  374. package/dist/domains/dashboard/web/assets/demo-lxXhgJ9-.js +0 -456
  375. package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-BRpYDwPl.js +0 -30
  376. package/dist/domains/dashboard/web/assets/diagram-B4RE2ZJO-D7u-VBxW.js +0 -3
  377. package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-CHYuv2JD.js +0 -24
  378. package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-CV3ZE8Q3.js +0 -24
  379. package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-co_OsTiQ.js +0 -41
  380. package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-CETcWswS.js +0 -1
  381. package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-edkItb7Z.js +0 -85
  382. package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-D_oFJtSf.js +0 -156
  383. package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-CFjLVoA1.js +0 -292
  384. package/dist/domains/dashboard/web/assets/gitGraphDiagram-DS77QQ5N-BfD0tiKH.js +0 -106
  385. package/dist/domains/dashboard/web/assets/graph-DOmOIIwC.js +0 -1
  386. package/dist/domains/dashboard/web/assets/index-BzyqCfMb.css +0 -1
  387. package/dist/domains/dashboard/web/assets/index-CCKHH_A9.js +0 -10
  388. package/dist/domains/dashboard/web/assets/index-D8dxsTJY.js +0 -271
  389. package/dist/domains/dashboard/web/assets/index-DlSYK56b.js +0 -139
  390. package/dist/domains/dashboard/web/assets/infoDiagram-6WML65LV-Cx6xa9DS.js +0 -2
  391. package/dist/domains/dashboard/web/assets/init-Gi6I4Gst.js +0 -1
  392. package/dist/domains/dashboard/web/assets/ishikawaDiagram-WSZJBQD7-BjNLyyv_.js +0 -70
  393. package/dist/domains/dashboard/web/assets/journeyDiagram-NVQOT4AX-D2n9vrhx.js +0 -139
  394. package/dist/domains/dashboard/web/assets/kanban-definition-27J2QSJJ-kJL7v018.js +0 -89
  395. package/dist/domains/dashboard/web/assets/katex-HP8lGamR.js +0 -257
  396. package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +0 -1
  397. package/dist/domains/dashboard/web/assets/linear-CeHtd5-l.js +0 -1
  398. package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +0 -1
  399. package/dist/domains/dashboard/web/assets/marked.esm-DECB3bxB.js +0 -64
  400. package/dist/domains/dashboard/web/assets/mermaid.core-B0EPSHs2.js +0 -306
  401. package/dist/domains/dashboard/web/assets/mindmap-definition-FAOFIHXS-bQQWINF4.js +0 -96
  402. package/dist/domains/dashboard/web/assets/ordinal-Cboi1Yqb.js +0 -1
  403. package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-LxLY1W7W.js +0 -1
  404. package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-BMDQqvuT.js +0 -39
  405. package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +0 -3
  406. package/dist/domains/dashboard/web/assets/quadrantDiagram-CIZ2JOQS-XWYjcuZN.js +0 -7
  407. package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-p-OlQTa7.js +0 -1
  408. package/dist/domains/dashboard/web/assets/requirementDiagram-LRYGKXZP-BL4N8Vsl.js +0 -84
  409. package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-Btu-o6LN.js +0 -40
  410. package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-9HpdQQ47.js +0 -162
  411. package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-5AnBiBHD.js +0 -1
  412. package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-Dv8IDsai.js +0 -1
  413. package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-DxOMyFOm.js +0 -1
  414. package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-BfJcN7dK.js +0 -2
  415. package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-BnHRSbDk.js +0 -8
  416. package/dist/domains/dashboard/web/assets/timeline-definition-Z64GVDOM-DEOuEHi5.js +0 -120
  417. package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BqsGpwgo.js +0 -34
  418. package/dist/domains/dashboard/web/assets/wardleyDiagram-T6FBY63Y-CXlOp9so.js +0 -78
  419. package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DyqqtC9X.js +0 -7
@@ -1,77 +1,77 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var hP=Object.create;var Wm=Object.defineProperty;var pP=Object.getOwnPropertyDescriptor;var mP=Object.getOwnPropertyNames;var vP=Object.getPrototypeOf,gP=Object.prototype.hasOwnProperty;var Js=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var wP=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mP(t))!gP.call(e,n)&&n!==i&&Wm(e,n,{get:()=>t[n],enumerable:!(r=pP(t,n))||r.enumerable});return e};var Rn=(e,t,i)=>(i=e!=null?hP(vP(e)):{},wP(t||!e||!e.__esModule?Wm(i,"default",{value:e,enumerable:!0}):i,e));var G=C(je=>{"use strict";var hd=Symbol.for("yaml.alias"),ev=Symbol.for("yaml.document"),Ks=Symbol.for("yaml.map"),tv=Symbol.for("yaml.pair"),pd=Symbol.for("yaml.scalar"),Ys=Symbol.for("yaml.seq"),Ri=Symbol.for("yaml.node.type"),SP=e=>!!e&&typeof e=="object"&&e[Ri]===hd,EP=e=>!!e&&typeof e=="object"&&e[Ri]===ev,PP=e=>!!e&&typeof e=="object"&&e[Ri]===Ks,RP=e=>!!e&&typeof e=="object"&&e[Ri]===tv,iv=e=>!!e&&typeof e=="object"&&e[Ri]===pd,CP=e=>!!e&&typeof e=="object"&&e[Ri]===Ys;function rv(e){if(e&&typeof e=="object")switch(e[Ri]){case Ks:case Ys:return!0}return!1}function xP(e){if(e&&typeof e=="object")switch(e[Ri]){case hd:case Ks:case pd:case Ys:return!0}return!1}var AP=e=>(iv(e)||rv(e))&&!!e.anchor;je.ALIAS=hd;je.DOC=ev;je.MAP=Ks;je.NODE_TYPE=Ri;je.PAIR=tv;je.SCALAR=pd;je.SEQ=Ys;je.hasAnchor=AP;je.isAlias=SP;je.isCollection=rv;je.isDocument=EP;je.isMap=PP;je.isNode=xP;je.isPair=RP;je.isScalar=iv;je.isSeq=CP});var Wa=C(md=>{"use strict";var Ce=G(),ot=Symbol("break visit"),nv=Symbol("skip children"),oi=Symbol("remove node");function Xs(e,t){let i=av(t);Ce.isDocument(e)?Cn(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):Cn(null,e,i,Object.freeze([]))}Xs.BREAK=ot;Xs.SKIP=nv;Xs.REMOVE=oi;function Cn(e,t,i,r){let n=ov(e,t,i,r);if(Ce.isNode(n)||Ce.isPair(n))return sv(e,r,n),Cn(e,n,i,r);if(typeof n!="symbol"){if(Ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Cn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===oi&&(t.items.splice(a,1),a-=1)}}}else if(Ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Cn("key",t.key,i,r);if(a===ot)return ot;a===oi&&(t.key=null);let o=Cn("value",t.value,i,r);if(o===ot)return ot;o===oi&&(t.value=null)}}return n}async function Qs(e,t){let i=av(t);Ce.isDocument(e)?await xn(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):await xn(null,e,i,Object.freeze([]))}Qs.BREAK=ot;Qs.SKIP=nv;Qs.REMOVE=oi;async function xn(e,t,i,r){let n=await ov(e,t,i,r);if(Ce.isNode(n)||Ce.isPair(n))return sv(e,r,n),xn(e,n,i,r);if(typeof n!="symbol"){if(Ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await xn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===oi&&(t.items.splice(a,1),a-=1)}}}else if(Ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await xn("key",t.key,i,r);if(a===ot)return ot;a===oi&&(t.key=null);let o=await xn("value",t.value,i,r);if(o===ot)return ot;o===oi&&(t.value=null)}}return n}function av(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 ov(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(Ce.isMap(t))return i.Map?.(e,t,r);if(Ce.isSeq(t))return i.Seq?.(e,t,r);if(Ce.isPair(t))return i.Pair?.(e,t,r);if(Ce.isScalar(t))return i.Scalar?.(e,t,r);if(Ce.isAlias(t))return i.Alias?.(e,t,r)}function sv(e,t,i){let r=t[t.length-1];if(Ce.isCollection(r))r.items[e]=i;else if(Ce.isPair(r))e==="key"?r.key=i:r.value=i;else if(Ce.isDocument(r))r.contents=i;else{let n=Ce.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}md.visit=Xs;md.visitAsync=Qs});var vd=C(lv=>{"use strict";var cv=G(),_P=Wa(),TP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},IP=e=>e.replace(/[!,[\]{}]/g,t=>TP[t]),za=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+IP(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&&cv.isNode(t.contents)){let a={};_P.visit(t.contents,(o,s)=>{cv.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
- `)}};za.defaultYaml={explicit:!1,version:"1.2"};za.defaultTags={"!!":"tag:yaml.org,2002:"};lv.Directives=za});var Zs=C(Ja=>{"use strict";var uv=G(),jP=Wa();function $P(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 dv(e){let t=new Set;return jP.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function fv(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function OP(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=dv(e));let o=fv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(uv.isScalar(o.node)||uv.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}}Ja.anchorIsValid=$P;Ja.anchorNames=dv;Ja.createNodeAnchors=OP;Ja.findNewAnchor=fv});var gd=C(hv=>{"use strict";function Ga(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=Ga(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=Ga(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=Ga(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=Ga(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}hv.applyReviver=Ga});var Gi=C(mv=>{"use strict";var HP=G();function pv(e,t,i){if(Array.isArray(e))return e.map((r,n)=>pv(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!HP.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}mv.toJS=pv});var ec=C(gv=>{"use strict";var DP=gd(),vv=G(),LP=Gi(),wd=class{constructor(t){Object.defineProperty(this,vv.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(!vv.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=LP.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?DP.applyReviver(a,{"":s},"",s):s}};gv.NodeBase=wd});var Ua=C(wv=>{"use strict";var MP=Zs(),FP=Wa(),An=G(),BP=ec(),VP=Gi(),yd=class extends BP.NodeBase{constructor(t){super(An.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],FP.visit(t,{Node:(a,o)=>{(An.isAlias(o)||An.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||(VP.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=tc(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(MP.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 tc(e,t,i){if(An.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(An.isCollection(t)){let r=0;for(let n of t.items){let a=tc(e,n,i);a>r&&(r=a)}return r}else if(An.isPair(t)){let r=tc(e,t.key,i),n=tc(e,t.value,i);return Math.max(r,n)}return 1}wv.Alias=yd});var ke=C(Nd=>{"use strict";var qP=G(),WP=ec(),zP=Gi(),JP=e=>!e||typeof e!="function"&&typeof e!="object",Ui=class extends WP.NodeBase{constructor(t){super(qP.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:zP.toJS(this.value,t,i)}toString(){return String(this.value)}};Ui.BLOCK_FOLDED="BLOCK_FOLDED";Ui.BLOCK_LITERAL="BLOCK_LITERAL";Ui.PLAIN="PLAIN";Ui.QUOTE_DOUBLE="QUOTE_DOUBLE";Ui.QUOTE_SINGLE="QUOTE_SINGLE";Nd.Scalar=Ui;Nd.isScalarValue=JP});var Ka=C(Nv=>{"use strict";var GP=Ua(),Jr=G(),yv=ke(),UP="tag:yaml.org,2002:";function KP(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 YP(e,t,i){if(Jr.isDocument(e)&&(e=e.contents),Jr.isNode(e))return e;if(Jr.isPair(e)){let d=i.schema[Jr.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 GP.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=UP+t.slice(2));let l=KP(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new yv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Jr.MAP]:Symbol.iterator in Object(e)?o[Jr.SEQ]:o[Jr.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 yv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Nv.createNode=YP});var rc=C(ic=>{"use strict";var XP=Ka(),si=G(),QP=ec();function bd(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 XP.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 bv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,kd=class extends QP.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=>si.isNode(r)||si.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(bv(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(si.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,bd(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(si.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&&si.isScalar(a)?a.value:a:si.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!si.isPair(i))return!1;let r=i.value;return r==null||t&&si.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 si.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(si.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,bd(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ic.Collection=kd;ic.collectionFromPath=bd;ic.isEmptyPath=bv});var Ya=C(nc=>{"use strict";var ZP=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Sd(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var eR=(e,t,i)=>e.endsWith(`
6
- `)?Sd(i,t):i.includes(`
4
+ var RP=Object.create;var Qm=Object.defineProperty;var CP=Object.getOwnPropertyDescriptor;var xP=Object.getOwnPropertyNames;var AP=Object.getPrototypeOf,_P=Object.prototype.hasOwnProperty;var Zs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var IP=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of xP(t))!_P.call(e,n)&&n!==i&&Qm(e,n,{get:()=>t[n],enumerable:!(r=CP(t,n))||r.enumerable});return e};var $n=(e,t,i)=>(i=e!=null?RP(AP(e)):{},IP(t||!e||!e.__esModule?Qm(i,"default",{value:e,enumerable:!0}):i,e));var G=C($e=>{"use strict";var Ed=Symbol.for("yaml.alias"),cv=Symbol.for("yaml.document"),ic=Symbol.for("yaml.map"),lv=Symbol.for("yaml.pair"),Pd=Symbol.for("yaml.scalar"),rc=Symbol.for("yaml.seq"),Ci=Symbol.for("yaml.node.type"),HP=e=>!!e&&typeof e=="object"&&e[Ci]===Ed,DP=e=>!!e&&typeof e=="object"&&e[Ci]===cv,LP=e=>!!e&&typeof e=="object"&&e[Ci]===ic,MP=e=>!!e&&typeof e=="object"&&e[Ci]===lv,uv=e=>!!e&&typeof e=="object"&&e[Ci]===Pd,FP=e=>!!e&&typeof e=="object"&&e[Ci]===rc;function dv(e){if(e&&typeof e=="object")switch(e[Ci]){case ic:case rc:return!0}return!1}function BP(e){if(e&&typeof e=="object")switch(e[Ci]){case Ed:case ic:case Pd:case rc:return!0}return!1}var VP=e=>(uv(e)||dv(e))&&!!e.anchor;$e.ALIAS=Ed;$e.DOC=cv;$e.MAP=ic;$e.NODE_TYPE=Ci;$e.PAIR=lv;$e.SCALAR=Pd;$e.SEQ=rc;$e.hasAnchor=VP;$e.isAlias=HP;$e.isCollection=dv;$e.isDocument=DP;$e.isMap=LP;$e.isNode=BP;$e.isPair=MP;$e.isScalar=uv;$e.isSeq=FP});var Qa=C(Rd=>{"use strict";var xe=G(),ot=Symbol("break visit"),fv=Symbol("skip children"),ci=Symbol("remove node");function nc(e,t){let i=hv(t);xe.isDocument(e)?On(null,e.contents,i,Object.freeze([e]))===ci&&(e.contents=null):On(null,e,i,Object.freeze([]))}nc.BREAK=ot;nc.SKIP=fv;nc.REMOVE=ci;function On(e,t,i,r){let n=pv(e,t,i,r);if(xe.isNode(n)||xe.isPair(n))return mv(e,r,n),On(e,n,i,r);if(typeof n!="symbol"){if(xe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=On(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===ci&&(t.items.splice(a,1),a-=1)}}}else if(xe.isPair(t)){r=Object.freeze(r.concat(t));let a=On("key",t.key,i,r);if(a===ot)return ot;a===ci&&(t.key=null);let o=On("value",t.value,i,r);if(o===ot)return ot;o===ci&&(t.value=null)}}return n}async function ac(e,t){let i=hv(t);xe.isDocument(e)?await Hn(null,e.contents,i,Object.freeze([e]))===ci&&(e.contents=null):await Hn(null,e,i,Object.freeze([]))}ac.BREAK=ot;ac.SKIP=fv;ac.REMOVE=ci;async function Hn(e,t,i,r){let n=await pv(e,t,i,r);if(xe.isNode(n)||xe.isPair(n))return mv(e,r,n),Hn(e,n,i,r);if(typeof n!="symbol"){if(xe.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===ot)return ot;o===ci&&(t.items.splice(a,1),a-=1)}}}else if(xe.isPair(t)){r=Object.freeze(r.concat(t));let a=await Hn("key",t.key,i,r);if(a===ot)return ot;a===ci&&(t.key=null);let o=await Hn("value",t.value,i,r);if(o===ot)return ot;o===ci&&(t.value=null)}}return n}function hv(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 pv(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(xe.isMap(t))return i.Map?.(e,t,r);if(xe.isSeq(t))return i.Seq?.(e,t,r);if(xe.isPair(t))return i.Pair?.(e,t,r);if(xe.isScalar(t))return i.Scalar?.(e,t,r);if(xe.isAlias(t))return i.Alias?.(e,t,r)}function mv(e,t,i){let r=t[t.length-1];if(xe.isCollection(r))r.items[e]=i;else if(xe.isPair(r))e==="key"?r.key=i:r.value=i;else if(xe.isDocument(r))r.contents=i;else{let n=xe.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Rd.visit=nc;Rd.visitAsync=ac});var Cd=C(gv=>{"use strict";var vv=G(),qP=Qa(),WP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},zP=e=>e.replace(/[!,[\]{}]/g,t=>WP[t]),Za=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+zP(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&&vv.isNode(t.contents)){let a={};qP.visit(t.contents,(o,s)=>{vv.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
+ `)}};Za.defaultYaml={explicit:!1,version:"1.2"};Za.defaultTags={"!!":"tag:yaml.org,2002:"};gv.Directives=Za});var oc=C(eo=>{"use strict";var wv=G(),JP=Qa();function GP(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 yv(e){let t=new Set;return JP.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Nv(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function UP(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=yv(e));let o=Nv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(wv.isScalar(o.node)||wv.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}}eo.anchorIsValid=GP;eo.anchorNames=yv;eo.createNodeAnchors=UP;eo.findNewAnchor=Nv});var xd=C(bv=>{"use strict";function to(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=to(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=to(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=to(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=to(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}bv.applyReviver=to});var Qi=C(Sv=>{"use strict";var KP=G();function kv(e,t,i){if(Array.isArray(e))return e.map((r,n)=>kv(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!KP.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}Sv.toJS=kv});var sc=C(Pv=>{"use strict";var YP=xd(),Ev=G(),XP=Qi(),Ad=class{constructor(t){Object.defineProperty(this,Ev.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(!Ev.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=XP.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?YP.applyReviver(a,{"":s},"",s):s}};Pv.NodeBase=Ad});var io=C(Rv=>{"use strict";var QP=oc(),ZP=Qa(),Dn=G(),eR=sc(),tR=Qi(),_d=class extends eR.NodeBase{constructor(t){super(Dn.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=[],ZP.visit(t,{Node:(a,o)=>{(Dn.isAlias(o)||Dn.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||(tR.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=cc(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(QP.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 cc(e,t,i){if(Dn.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Dn.isCollection(t)){let r=0;for(let n of t.items){let a=cc(e,n,i);a>r&&(r=a)}return r}else if(Dn.isPair(t)){let r=cc(e,t.key,i),n=cc(e,t.value,i);return Math.max(r,n)}return 1}Rv.Alias=_d});var ke=C(Id=>{"use strict";var iR=G(),rR=sc(),nR=Qi(),aR=e=>!e||typeof e!="function"&&typeof e!="object",Zi=class extends rR.NodeBase{constructor(t){super(iR.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:nR.toJS(this.value,t,i)}toString(){return String(this.value)}};Zi.BLOCK_FOLDED="BLOCK_FOLDED";Zi.BLOCK_LITERAL="BLOCK_LITERAL";Zi.PLAIN="PLAIN";Zi.QUOTE_DOUBLE="QUOTE_DOUBLE";Zi.QUOTE_SINGLE="QUOTE_SINGLE";Id.Scalar=Zi;Id.isScalarValue=aR});var ro=C(xv=>{"use strict";var oR=io(),Xr=G(),Cv=ke(),sR="tag:yaml.org,2002:";function cR(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 lR(e,t,i){if(Xr.isDocument(e)&&(e=e.contents),Xr.isNode(e))return e;if(Xr.isPair(e)){let d=i.schema[Xr.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 oR.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=sR+t.slice(2));let l=cR(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Cv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Xr.MAP]:Symbol.iterator in Object(e)?o[Xr.SEQ]:o[Xr.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 Cv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}xv.createNode=lR});var uc=C(lc=>{"use strict";var uR=ro(),li=G(),dR=sc();function Td(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 uR.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 Av=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,jd=class extends dR.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=>li.isNode(r)||li.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(Av(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(li.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Td(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(li.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&&li.isScalar(a)?a.value:a:li.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!li.isPair(i))return!1;let r=i.value;return r==null||t&&li.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 li.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(li.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Td(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};lc.Collection=jd;lc.collectionFromPath=Td;lc.isEmptyPath=Av});var no=C(dc=>{"use strict";var fR=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function $d(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var hR=(e,t,i)=>e.endsWith(`
6
+ `)?$d(i,t):i.includes(`
7
7
  `)?`
8
- `+Sd(i,t):(e.endsWith(" ")?"":" ")+i;nc.indentComment=Sd;nc.lineComment=eR;nc.stringifyComment=ZP});var Sv=C(Xa=>{"use strict";var tR="flow",Ed="block",ac="quoted";function iR(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,m=-1,p=-1,b=-1;i===Ed&&(m=kv(e,m,t.length),m!==-1&&(d=m+c));for(let y;y=e[m+=1];){if(i===ac&&y==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(y===`
9
- `)i===Ed&&(m=kv(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(y===" "&&h&&h!==" "&&h!==`
10
- `&&h!==" "){let E=e[m+1];E&&E!==" "&&E!==`
11
- `&&E!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===ac){for(;h===" "||h===" ";)h=y,y=e[m+=1],v=!0;let E=m>b+1?m-2:p-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else v=!0}h=y}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let E=l[y],k=l[y+1]||e.length;E===0?g=`
12
- ${t}${e.slice(0,k)}`:(i===ac&&u[E]&&(g+=`${e[E]}\\`),g+=`
13
- ${t}${e.slice(E+1,k)}`)}return g}function kv(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}Xa.FOLD_BLOCK=Ed;Xa.FOLD_FLOW=tR;Xa.FOLD_QUOTED=ac;Xa.foldFlowLines=iR});var Za=C(Ev=>{"use strict";var Wt=ke(),Ki=Sv(),sc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),cc=e=>/^(%|---|\.\.\.)/m.test(e);function rR(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 Qa(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(cc(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
+ `+$d(i,t):(e.endsWith(" ")?"":" ")+i;dc.indentComment=$d;dc.lineComment=hR;dc.stringifyComment=fR});var Iv=C(ao=>{"use strict";var pR="flow",Od="block",fc="quoted";function mR(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,m=-1,p=-1,b=-1;i===Od&&(m=_v(e,m,t.length),m!==-1&&(d=m+c));for(let S;S=e[m+=1];){if(i===fc&&S==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(S===`
9
+ `)i===Od&&(m=_v(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(S===" "&&h&&h!==" "&&h!==`
10
+ `&&h!==" "){let N=e[m+1];N&&N!==" "&&N!==`
11
+ `&&N!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===fc){for(;h===" "||h===" ";)h=S,S=e[m+=1],v=!0;let N=m>b+1?m-2:p-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,f=void 0}else v=!0}h=S}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let S=0;S<l.length;++S){let N=l[S],k=l[S+1]||e.length;N===0?g=`
12
+ ${t}${e.slice(0,k)}`:(i===fc&&u[N]&&(g+=`${e[N]}\\`),g+=`
13
+ ${t}${e.slice(N+1,k)}`)}return g}function _v(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}ao.FOLD_BLOCK=Od;ao.FOLD_FLOW=pR;ao.FOLD_QUOTED=fc;ao.foldFlowLines=mR});var so=C(Tv=>{"use strict";var zt=ke(),er=Iv(),pc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),mc=e=>/^(%|---|\.\.\.)/m.test(e);function vR(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 oo(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(mc(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:Ki.foldFlowLines(o,a,Ki.FOLD_QUOTED,sc(t,!1))}function Pd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Qa(e,t);let i=t.indent||(cc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?r:Ki.foldFlowLines(r,i,Ki.FOLD_FLOW,sc(t,!1))}function _n(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Qa;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Pd:a&&!n?r=Qa:r=i?Pd:Qa}return r(e,t)}var Rd;try{Rd=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:er.foldFlowLines(o,a,er.FOLD_QUOTED,pc(t,!1))}function Hd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return oo(e,t);let i=t.indent||(mc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?r:er.foldFlowLines(r,i,er.FOLD_FLOW,pc(t,!1))}function Ln(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=oo;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Hd:a&&!n?r=oo:r=i?Hd:oo}return r(e,t)}var Dd;try{Dd=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Rd=/\n+(?!\n|$)/g}function oc({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 _n(i,r);let l=r.indent||(r.forceBlockIndent||cc(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Wt.Scalar.BLOCK_FOLDED?!1:t===Wt.Scalar.BLOCK_LITERAL?!0:!rR(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{Dd=/\n+(?!\n|$)/g}function hc({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 Ln(i,r);let l=r.indent||(r.forceBlockIndent||mc(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===zt.Scalar.BLOCK_FOLDED?!1:t===zt.Scalar.BLOCK_LITERAL?!0:!vR(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
26
  `&&k!==" "&&k!==" ")break}let h=i.substring(f),v=h.indexOf(`
27
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(Rd,`$&${l}`));let m=!1,p,b=-1;for(p=0;p<i.length;++p){let k=i[p];if(k===" ")m=!0;else if(k===`
29
- `)b=p;else break}let g=i.substring(0,b<p?b+1:p);g&&(i=i.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let E=(m?l?"2":"1":"")+d;if(e&&(E+=" "+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}`),S=!1,R=sc(r,!0);o!=="folded"&&t!==Wt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{S=!0});let N=Ki.foldFlowLines(`${g}${k}${h}`,l,Ki.FOLD_BLOCK,R);if(!S)return`>${E}
31
- ${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${E}
32
- ${l}${g}${i}${h}`}function nR(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 _n(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?_n(a,t):oc(e,t,i,r);if(!s&&!u&&n!==Wt.Scalar.PLAIN&&a.includes(`
35
- `))return oc(e,t,i,r);if(cc(a)){if(c==="")return t.forceBlockIndent=!0,oc(e,t,i,r);if(s&&c===l)return _n(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return _n(a,t)}return s?d:Ki.foldFlowLines(d,c,Ki.FOLD_FLOW,sc(t,!1))}function aR(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!==Wt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Wt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Wt.Scalar.BLOCK_FOLDED:case Wt.Scalar.BLOCK_LITERAL:return n||a?_n(o.value,t):oc(o,t,i,r);case Wt.Scalar.QUOTE_DOUBLE:return Qa(o.value,t);case Wt.Scalar.QUOTE_SINGLE:return Pd(o.value,t);case Wt.Scalar.PLAIN:return nR(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}Ev.stringifyString=aR});var eo=C(Cd=>{"use strict";var oR=Zs(),Yi=G(),sR=Ya(),cR=Za();function lR(e,t){let i=Object.assign({blockQuote:!0,commentString:sR.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 uR(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(Yi.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 dR(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Yi.isScalar(e)||Yi.isCollection(e))&&e.anchor;a&&oR.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 fR(e,t,i,r){if(Yi.isPair(e))return e.toString(t,i,r);if(Yi.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=Yi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=uR(t.doc.schema.tags,a));let o=dR(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):Yi.isScalar(a)?cR.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Yi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Cd.createStringifyContext=lR;Cd.stringify=fR});var xv=C(Cv=>{"use strict";var Ci=G(),Pv=ke(),Rv=eo(),to=Ya();function hR({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=Ci.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ci.isCollection(e)||!Ci.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||Ci.isCollection(e)||(Ci.isScalar(e)?e.type===Pv.Scalar.BLOCK_FOLDED||e.type===Pv.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=Rv.stringify(e,i,()=>v=!0,()=>m=!0);if(!h&&!i.inFlow&&p.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(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,f&&!v?p+=to.lineComment(p,i.indent,l(f)):m&&n&&n(),p;v&&(f=null),h?(f&&(p+=to.lineComment(p,i.indent,l(f))),p=`? ${p}
38
- ${s}:`):(p=`${p}:`,f&&(p+=to.lineComment(p,i.indent,l(f))));let b,g,y;Ci.isNode(t)?(b=!!t.spaceBefore,g=t.commentBefore,y=t.comment):(b=!1,g=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&Ci.isScalar(t)&&(i.indentAtStart=p.length+1),m=!1,!u&&c.length>=2&&!i.inFlow&&!h&&Ci.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let E=!1,k=Rv.stringify(t,i,()=>E=!0,()=>m=!0),S=" ";if(f||b||g){if(S=b?`
39
- `:"",g){let R=l(g);S+=`
40
- ${to.indentComment(R,i.indent)}`}k===""&&!i.inFlow?S===`
41
- `&&y&&(S=`
28
+ `&&(h=h.slice(0,-1)),h=h.replace(Dd,`$&${l}`));let m=!1,p,b=-1;for(p=0;p<i.length;++p){let k=i[p];if(k===" ")m=!0;else if(k===`
29
+ `)b=p;else break}let g=i.substring(0,b<p?b+1:p);g&&(i=i.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let N=(m?l?"2":"1":"")+d;if(e&&(N+=" "+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}`),E=!1,R=pc(r,!0);o!=="folded"&&t!==zt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{E=!0});let y=er.foldFlowLines(`${g}${k}${h}`,l,er.FOLD_BLOCK,R);if(!E)return`>${N}
31
+ ${l}${y}`}return i=i.replace(/\n+/g,`$&${l}`),`|${N}
32
+ ${l}${g}${i}${h}`}function gR(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 Ln(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?Ln(a,t):hc(e,t,i,r);if(!s&&!u&&n!==zt.Scalar.PLAIN&&a.includes(`
35
+ `))return hc(e,t,i,r);if(mc(a)){if(c==="")return t.forceBlockIndent=!0,hc(e,t,i,r);if(s&&c===l)return Ln(a,t)}let d=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return Ln(a,t)}return s?d:er.foldFlowLines(d,c,er.FOLD_FLOW,pc(t,!1))}function wR(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!==zt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=zt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case zt.Scalar.BLOCK_FOLDED:case zt.Scalar.BLOCK_LITERAL:return n||a?Ln(o.value,t):hc(o,t,i,r);case zt.Scalar.QUOTE_DOUBLE:return oo(o.value,t);case zt.Scalar.QUOTE_SINGLE:return Hd(o.value,t);case zt.Scalar.PLAIN:return gR(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}Tv.stringifyString=wR});var co=C(Ld=>{"use strict";var yR=oc(),tr=G(),NR=no(),bR=so();function kR(e,t){let i=Object.assign({blockQuote:!0,commentString:NR.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 SR(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(tr.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 ER(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(tr.isScalar(e)||tr.isCollection(e))&&e.anchor;a&&yR.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 PR(e,t,i,r){if(tr.isPair(e))return e.toString(t,i,r);if(tr.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=tr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=SR(t.doc.schema.tags,a));let o=ER(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):tr.isScalar(a)?bR.stringifyString(a,t,i,r):a.toString(t,i,r);return o?tr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Ld.createStringifyContext=kR;Ld.stringify=PR});var Hv=C(Ov=>{"use strict";var xi=G(),jv=ke(),$v=co(),lo=no();function RR({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=xi.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(xi.isCollection(e)||!xi.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||xi.isCollection(e)||(xi.isScalar(e)?e.type===jv.Scalar.BLOCK_FOLDED||e.type===jv.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=$v.stringify(e,i,()=>v=!0,()=>m=!0);if(!h&&!i.inFlow&&p.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(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,f&&!v?p+=lo.lineComment(p,i.indent,l(f)):m&&n&&n(),p;v&&(f=null),h?(f&&(p+=lo.lineComment(p,i.indent,l(f))),p=`? ${p}
38
+ ${s}:`):(p=`${p}:`,f&&(p+=lo.lineComment(p,i.indent,l(f))));let b,g,S;xi.isNode(t)?(b=!!t.spaceBefore,g=t.commentBefore,S=t.comment):(b=!1,g=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&xi.isScalar(t)&&(i.indentAtStart=p.length+1),m=!1,!u&&c.length>=2&&!i.inFlow&&!h&&xi.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let N=!1,k=$v.stringify(t,i,()=>N=!0,()=>m=!0),E=" ";if(f||b||g){if(E=b?`
39
+ `:"",g){let R=l(g);E+=`
40
+ ${lo.indentComment(R,i.indent)}`}k===""&&!i.inFlow?E===`
41
+ `&&S&&(E=`
42
42
 
43
- `):S+=`
44
- ${i.indent}`}else if(!h&&Ci.isCollection(t)){let R=k[0],N=k.indexOf(`
45
- `),w=N!==-1,P=i.inFlow??t.flow??t.items.length===0;if(w||!P){let F=!1;if(w&&(R==="&"||R==="!")){let $=k.indexOf(" ");R==="&"&&$!==-1&&$<N&&k[$+1]==="!"&&($=k.indexOf(" ",$+1)),($===-1||N<$)&&(F=!0)}F||(S=`
43
+ `):E+=`
44
+ ${i.indent}`}else if(!h&&xi.isCollection(t)){let R=k[0],y=k.indexOf(`
45
+ `),w=y!==-1,P=i.inFlow??t.flow??t.items.length===0;if(w||!P){let F=!1;if(w&&(R==="&"||R==="!")){let $=k.indexOf(" ");R==="&"&&$!==-1&&$<y&&k[$+1]==="!"&&($=k.indexOf(" ",$+1)),($===-1||y<$)&&(F=!0)}F||(E=`
46
46
  ${i.indent}`)}}else(k===""||k[0]===`
47
- `)&&(S="");return p+=S+k,i.inFlow?E&&r&&r():y&&!E?p+=to.lineComment(p,i.indent,l(y)):m&&n&&n(),p}Cv.stringifyPair=hR});var Ad=C(xd=>{"use strict";var Av=Js("process");function pR(e,...t){e==="debug"&&console.log(...t)}function mR(e,t){(e==="debug"||e==="warn")&&(typeof Av.emitWarning=="function"?Av.emitWarning(t):console.warn(t))}xd.debug=pR;xd.warn=mR});var hc=C(fc=>{"use strict";var dc=G(),_v=ke(),lc="<<",uc={identify:e=>e===lc||typeof e=="symbol"&&e.description===lc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new _v.Scalar(Symbol(lc)),{addToJSMap:Tv}),stringify:()=>lc},vR=(e,t)=>(uc.identify(t)||dc.isScalar(t)&&(!t.type||t.type===_v.Scalar.PLAIN)&&uc.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===uc.tag&&i.default);function Tv(e,t,i){let r=Iv(e,i);if(dc.isSeq(r))for(let n of r.items)_d(e,t,n);else if(Array.isArray(r))for(let n of r)_d(e,t,n);else _d(e,t,r)}function _d(e,t,i){let r=Iv(e,i);if(!dc.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 Iv(e,t){return e&&dc.isAlias(t)?t.resolve(e.doc,e):t}fc.addMergeToJSMap=Tv;fc.isMergeKey=vR;fc.merge=uc});var Id=C(Ov=>{"use strict";var gR=Ad(),jv=hc(),wR=eo(),$v=G(),Td=Gi();function yR(e,t,{key:i,value:r}){if($v.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(jv.isMergeKey(e,i))jv.addMergeToJSMap(e,t,r);else{let n=Td.toJS(i,"",e);if(t instanceof Map)t.set(n,Td.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=NR(i,n,e),o=Td.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 NR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if($v.isNode(e)&&i?.doc){let r=wR.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)+'..."'),gR.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)}Ov.addPairToJSMap=yR});var Xi=C(jd=>{"use strict";var Hv=Ka(),bR=xv(),kR=Id(),pc=G();function SR(e,t,i){let r=Hv.createNode(e,void 0,i),n=Hv.createNode(t,void 0,i);return new mc(r,n)}var mc=class e{constructor(t,i=null){Object.defineProperty(this,pc.NODE_TYPE,{value:pc.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return pc.isNode(i)&&(i=i.clone(t)),pc.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return kR.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?bR.stringifyPair(this,t,i,r):JSON.stringify(this)}};jd.Pair=mc;jd.createPair=SR});var $d=C(Lv=>{"use strict";var Gr=G(),Dv=eo(),vc=Ya();function ER(e,t,i){return(t.inFlow??e.flow?RR:PR)(e,t,i)}function PR({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 m=t[v],p=null;if(Gr.isNode(m))!d&&m.spaceBefore&&f.push(""),gc(i,f,m.commentBefore,d),m.comment&&(p=m.comment);else if(Gr.isPair(m)){let g=Gr.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&f.push(""),gc(i,f,g.commentBefore,d))}d=!1;let b=Dv.stringify(m,u,()=>p=null,()=>d=!0);p&&(b+=vc.lineComment(b,a,l(p))),d&&p&&(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 m=f[v];h+=m?`
47
+ `)&&(E="");return p+=E+k,i.inFlow?N&&r&&r():S&&!N?p+=lo.lineComment(p,i.indent,l(S)):m&&n&&n(),p}Ov.stringifyPair=RR});var Fd=C(Md=>{"use strict";var Dv=Zs("process");function CR(e,...t){e==="debug"&&console.log(...t)}function xR(e,t){(e==="debug"||e==="warn")&&(typeof Dv.emitWarning=="function"?Dv.emitWarning(t):console.warn(t))}Md.debug=CR;Md.warn=xR});var Nc=C(yc=>{"use strict";var wc=G(),Lv=ke(),vc="<<",gc={identify:e=>e===vc||typeof e=="symbol"&&e.description===vc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Lv.Scalar(Symbol(vc)),{addToJSMap:Mv}),stringify:()=>vc},AR=(e,t)=>(gc.identify(t)||wc.isScalar(t)&&(!t.type||t.type===Lv.Scalar.PLAIN)&&gc.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===gc.tag&&i.default);function Mv(e,t,i){let r=Fv(e,i);if(wc.isSeq(r))for(let n of r.items)Bd(e,t,n);else if(Array.isArray(r))for(let n of r)Bd(e,t,n);else Bd(e,t,r)}function Bd(e,t,i){let r=Fv(e,i);if(!wc.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 Fv(e,t){return e&&wc.isAlias(t)?t.resolve(e.doc,e):t}yc.addMergeToJSMap=Mv;yc.isMergeKey=AR;yc.merge=gc});var qd=C(qv=>{"use strict";var _R=Fd(),Bv=Nc(),IR=co(),Vv=G(),Vd=Qi();function TR(e,t,{key:i,value:r}){if(Vv.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(Bv.isMergeKey(e,i))Bv.addMergeToJSMap(e,t,r);else{let n=Vd.toJS(i,"",e);if(t instanceof Map)t.set(n,Vd.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=jR(i,n,e),o=Vd.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 jR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(Vv.isNode(e)&&i?.doc){let r=IR.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)+'..."'),_R.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)}qv.addPairToJSMap=TR});var ir=C(Wd=>{"use strict";var Wv=ro(),$R=Hv(),OR=qd(),bc=G();function HR(e,t,i){let r=Wv.createNode(e,void 0,i),n=Wv.createNode(t,void 0,i);return new kc(r,n)}var kc=class e{constructor(t,i=null){Object.defineProperty(this,bc.NODE_TYPE,{value:bc.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return bc.isNode(i)&&(i=i.clone(t)),bc.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return OR.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?$R.stringifyPair(this,t,i,r):JSON.stringify(this)}};Wd.Pair=kc;Wd.createPair=HR});var zd=C(Jv=>{"use strict";var Qr=G(),zv=co(),Sc=no();function DR(e,t,i){return(t.inFlow??e.flow?MR:LR)(e,t,i)}function LR({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 m=t[v],p=null;if(Qr.isNode(m))!d&&m.spaceBefore&&f.push(""),Ec(i,f,m.commentBefore,d),m.comment&&(p=m.comment);else if(Qr.isPair(m)){let g=Qr.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&f.push(""),Ec(i,f,g.commentBefore,d))}d=!1;let b=zv.stringify(m,u,()=>p=null,()=>d=!0);p&&(b+=Sc.lineComment(b,a,l(p))),d&&p&&(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 m=f[v];h+=m?`
48
48
  ${c}${m}`:`
49
49
  `}}return e?(h+=`
50
- `+vc.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function RR({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 m=e[v],p=null;if(Gr.isNode(m))m.spaceBefore&&d.push(""),gc(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Gr.isPair(m)){let g=Gr.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),gc(t,d,g.commentBefore,!1),g.comment&&(l=!0));let y=Gr.isNode(m.value)?m.value:null;y?(y.comment&&(p=y.comment),y.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let b=Dv.stringify(m,c,()=>p=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((g,y)=>g+y.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),p&&(b+=vc.lineComment(b,r,s(p))),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((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let m of d)v+=m?`
50
+ `+Sc.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function MR({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 m=e[v],p=null;if(Qr.isNode(m))m.spaceBefore&&d.push(""),Ec(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Qr.isPair(m)){let g=Qr.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),Ec(t,d,g.commentBefore,!1),g.comment&&(l=!0));let S=Qr.isNode(m.value)?m.value:null;S?(S.comment&&(p=S.comment),S.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let b=zv.stringify(m,c,()=>p=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((g,S)=>g+S.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),p&&(b+=Sc.lineComment(b,r,s(p))),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((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let m of d)v+=m?`
52
52
  ${a}${n}${m}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function gc({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=vc.indentComment(t(r),e);i.push(a.trimStart())}}Lv.stringifyCollection=ER});var Zi=C(Hd=>{"use strict";var CR=$d(),xR=Id(),AR=rc(),Qi=G(),wc=Xi(),_R=ke();function io(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 Od=class extends AR.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(wc.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 wc.Pair(t,t?.value):r=new wc.Pair(t.key,t.value);let n=io(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Qi.isScalar(n.value)&&_R.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=io(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=io(this.items,t)?.value;return(!i&&Qi.isScalar(n)?n.value:n)??void 0}has(t){return!!io(this.items,t)}set(t,i){this.add(new wc.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)xR.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})),CR.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Hd.YAMLMap=Od;Hd.findPair=io});var Tn=C(Fv=>{"use strict";var TR=G(),Mv=Zi(),IR={collection:"map",default:!0,nodeClass:Mv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return TR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Mv.YAMLMap.from(e,t,i)};Fv.map=IR});var er=C(Bv=>{"use strict";var jR=Ka(),$R=$d(),OR=rc(),Nc=G(),HR=ke(),DR=Gi(),Dd=class extends OR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Nc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=yc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=yc(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Nc.isScalar(n)?n.value:n}has(t){let i=yc(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=yc(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Nc.isScalar(n)&&HR.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(DR.toJS(a,String(n++),i));return r}toString(t,i,r){return t?$R.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(jR.createNode(s,void 0,r))}}return a}};function yc(e){let t=Nc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Bv.YAMLSeq=Dd});var In=C(qv=>{"use strict";var LR=G(),Vv=er(),MR={collection:"seq",default:!0,nodeClass:Vv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return LR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Vv.YAMLSeq.from(e,t,i)};qv.seq=MR});var ro=C(Wv=>{"use strict";var FR=Za(),BR={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),FR.stringifyString(e,t,i,r)}};Wv.string=BR});var bc=C(Gv=>{"use strict";var zv=ke(),Jv={identify:e=>e==null,createNode:()=>new zv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Jv.test.test(e)?e:t.options.nullStr};Gv.nullTag=Jv});var Ld=C(Kv=>{"use strict";var VR=ke(),Uv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new VR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Uv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Kv.boolTag=Uv});var jn=C(Yv=>{"use strict";function qR({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=qR});var Fd=C(kc=>{"use strict";var WR=ke(),Md=jn(),zR={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:Md.stringifyNumber},JR={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():Md.stringifyNumber(e)}},GR={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 WR.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Md.stringifyNumber};kc.float=GR;kc.floatExp=JR;kc.floatNaN=zR});var Vd=C(Ec=>{"use strict";var Xv=jn(),Sc=e=>typeof e=="bigint"||Number.isInteger(e),Bd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Qv(e,t,i){let{value:r}=e;return Sc(r)&&r>=0?i+r.toString(t):Xv.stringifyNumber(e)}var UR={identify:e=>Sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Bd(e,2,8,i),stringify:e=>Qv(e,8,"0o")},KR={identify:Sc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Bd(e,0,10,i),stringify:Xv.stringifyNumber},YR={identify:e=>Sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Bd(e,2,16,i),stringify:e=>Qv(e,16,"0x")};Ec.int=KR;Ec.intHex=YR;Ec.intOct=UR});var eg=C(Zv=>{"use strict";var XR=Tn(),QR=bc(),ZR=In(),eC=ro(),tC=Ld(),qd=Fd(),Wd=Vd(),iC=[XR.map,ZR.seq,eC.string,QR.nullTag,tC.boolTag,Wd.intOct,Wd.int,Wd.intHex,qd.floatNaN,qd.floatExp,qd.float];Zv.schema=iC});var rg=C(ig=>{"use strict";var rC=ke(),nC=Tn(),aC=In();function tg(e){return typeof e=="bigint"||Number.isInteger(e)}var Pc=({value:e})=>JSON.stringify(e),oC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Pc},{identify:e=>e==null,createNode:()=>new rC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Pc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Pc},{identify:tg,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})=>tg(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:Pc}],sC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},cC=[nC.map,aC.seq].concat(oC,sC);ig.schema=cC});var Jd=C(ng=>{"use strict";var no=Js("buffer"),zd=ke(),lC=Za(),uC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof no.Buffer=="function")return no.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 no.Buffer=="function")s=o instanceof no.Buffer?o.toString("base64"):no.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=zd.Scalar.BLOCK_LITERAL),t!==zd.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===zd.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return lC.stringifyString({comment:e,type:t,value:s},r,n,a)}};ng.binary=uC});var xc=C(Cc=>{"use strict";var Rc=G(),Gd=Xi(),dC=ke(),fC=er();function ag(e,t){if(Rc.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Rc.isPair(r)){if(Rc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Gd.Pair(new dC.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
54
+ ${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function Ec({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Sc.indentComment(t(r),e);i.push(a.trimStart())}}Jv.stringifyCollection=DR});var nr=C(Gd=>{"use strict";var FR=zd(),BR=qd(),VR=uc(),rr=G(),Pc=ir(),qR=ke();function uo(e,t){let i=rr.isScalar(t)?t.value:t;for(let r of e)if(rr.isPair(r)&&(r.key===t||r.key===i||rr.isScalar(r.key)&&r.key.value===i))return r}var Jd=class extends VR.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(rr.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(Pc.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;rr.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Pc.Pair(t,t?.value):r=new Pc.Pair(t.key,t.value);let n=uo(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);rr.isScalar(n.value)&&qR.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=uo(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=uo(this.items,t)?.value;return(!i&&rr.isScalar(n)?n.value:n)??void 0}has(t){return!!uo(this.items,t)}set(t,i){this.add(new Pc.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)BR.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!rr.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})),FR.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Gd.YAMLMap=Jd;Gd.findPair=uo});var Mn=C(Uv=>{"use strict";var WR=G(),Gv=nr(),zR={collection:"map",default:!0,nodeClass:Gv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return WR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Gv.YAMLMap.from(e,t,i)};Uv.map=zR});var ar=C(Kv=>{"use strict";var JR=ro(),GR=zd(),UR=uc(),Cc=G(),KR=ke(),YR=Qi(),Ud=class extends UR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Cc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Rc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Rc(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Cc.isScalar(n)?n.value:n}has(t){let i=Rc(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Rc(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Cc.isScalar(n)&&KR.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(YR.toJS(a,String(n++),i));return r}toString(t,i,r){return t?GR.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(JR.createNode(s,void 0,r))}}return a}};function Rc(e){let t=Cc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Kv.YAMLSeq=Ud});var Fn=C(Xv=>{"use strict";var XR=G(),Yv=ar(),QR={collection:"seq",default:!0,nodeClass:Yv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return XR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Yv.YAMLSeq.from(e,t,i)};Xv.seq=QR});var fo=C(Qv=>{"use strict";var ZR=so(),eC={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),ZR.stringifyString(e,t,i,r)}};Qv.string=eC});var xc=C(tg=>{"use strict";var Zv=ke(),eg={identify:e=>e==null,createNode:()=>new Zv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Zv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&eg.test.test(e)?e:t.options.nullStr};tg.nullTag=eg});var Kd=C(rg=>{"use strict";var tC=ke(),ig={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new tC.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&ig.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};rg.boolTag=ig});var Bn=C(ng=>{"use strict";function iC({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}ng.stringifyNumber=iC});var Xd=C(Ac=>{"use strict";var rC=ke(),Yd=Bn(),nC={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},aC={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():Yd.stringifyNumber(e)}},oC={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 rC.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Yd.stringifyNumber};Ac.float=oC;Ac.floatExp=aC;Ac.floatNaN=nC});var Zd=C(Ic=>{"use strict";var ag=Bn(),_c=e=>typeof e=="bigint"||Number.isInteger(e),Qd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function og(e,t,i){let{value:r}=e;return _c(r)&&r>=0?i+r.toString(t):ag.stringifyNumber(e)}var sC={identify:e=>_c(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Qd(e,2,8,i),stringify:e=>og(e,8,"0o")},cC={identify:_c,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Qd(e,0,10,i),stringify:ag.stringifyNumber},lC={identify:e=>_c(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Qd(e,2,16,i),stringify:e=>og(e,16,"0x")};Ic.int=cC;Ic.intHex=lC;Ic.intOct=sC});var cg=C(sg=>{"use strict";var uC=Mn(),dC=xc(),fC=Fn(),hC=fo(),pC=Kd(),ef=Xd(),tf=Zd(),mC=[uC.map,fC.seq,hC.string,dC.nullTag,pC.boolTag,tf.intOct,tf.int,tf.intHex,ef.floatNaN,ef.floatExp,ef.float];sg.schema=mC});var dg=C(ug=>{"use strict";var vC=ke(),gC=Mn(),wC=Fn();function lg(e){return typeof e=="bigint"||Number.isInteger(e)}var Tc=({value:e})=>JSON.stringify(e),yC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Tc},{identify:e=>e==null,createNode:()=>new vC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Tc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Tc},{identify:lg,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})=>lg(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:Tc}],NC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},bC=[gC.map,wC.seq].concat(yC,NC);ug.schema=bC});var nf=C(fg=>{"use strict";var ho=Zs("buffer"),rf=ke(),kC=so(),SC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ho.Buffer=="function")return ho.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 ho.Buffer=="function")s=o instanceof ho.Buffer?o.toString("base64"):ho.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=rf.Scalar.BLOCK_LITERAL),t!==rf.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===rf.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return kC.stringifyString({comment:e,type:t,value:s},r,n,a)}};fg.binary=SC});var Oc=C($c=>{"use strict";var jc=G(),af=ir(),EC=ke(),PC=ar();function hg(e,t){if(jc.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!jc.isPair(r)){if(jc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new af.Pair(new EC.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]=Rc.isPair(r)?r:new Gd.Pair(r)}}else t("Expected a sequence for this tag");return e}function og(e,t,i){let{replacer:r}=i,n=new fC.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(Gd.createPair(s,c,i))}return n}var hC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ag,createNode:og};Cc.createPairs=og;Cc.pairs=hC;Cc.resolvePairs=ag});var Yd=C(Kd=>{"use strict";var sg=G(),Ud=Gi(),ao=Zi(),pC=er(),cg=xc(),Ur=class e extends pC.YAMLSeq{constructor(){super(),this.add=ao.YAMLMap.prototype.add.bind(this),this.delete=ao.YAMLMap.prototype.delete.bind(this),this.get=ao.YAMLMap.prototype.get.bind(this),this.has=ao.YAMLMap.prototype.has.bind(this),this.set=ao.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(sg.isPair(n)?(a=Ud.toJS(n.key,"",i),o=Ud.toJS(n.value,a,i)):a=Ud.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=cg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ur.tag="tag:yaml.org,2002:omap";var mC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ur,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=cg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)sg.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ur,i)},createNode:(e,t,i)=>Ur.from(e,t,i)};Kd.YAMLOMap=Ur;Kd.omap=mC});var hg=C(Xd=>{"use strict";var lg=ke();function ug({value:e,source:t},i){return t&&(e?dg:fg).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var dg={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 lg.Scalar(!0),stringify:ug},fg={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 lg.Scalar(!1),stringify:ug};Xd.falseTag=fg;Xd.trueTag=dg});var pg=C(Ac=>{"use strict";var vC=ke(),Qd=jn(),gC={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:Qd.stringifyNumber},wC={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():Qd.stringifyNumber(e)}},yC={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 vC.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:Qd.stringifyNumber};Ac.float=yC;Ac.floatExp=wC;Ac.floatNaN=gC});var vg=C(so=>{"use strict";var mg=jn(),oo=e=>typeof e=="bigint"||Number.isInteger(e);function _c(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 Zd(e,t,i){let{value:r}=e;if(oo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return mg.stringifyNumber(e)}var NC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>_c(e,2,2,i),stringify:e=>Zd(e,2,"0b")},bC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>_c(e,1,8,i),stringify:e=>Zd(e,8,"0")},kC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>_c(e,0,10,i),stringify:mg.stringifyNumber},SC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>_c(e,2,16,i),stringify:e=>Zd(e,16,"0x")};so.int=kC;so.intBin=NC;so.intHex=SC;so.intOct=bC});var tf=C(ef=>{"use strict";var jc=G(),Tc=Xi(),Ic=Zi(),Kr=class e extends Ic.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;jc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Tc.Pair(t.key,null):i=new Tc.Pair(t,null),Ic.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Ic.findPair(this.items,t);return!i&&jc.isPair(r)?jc.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=Ic.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Tc.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(Tc.createPair(o,null,r));return a}};Kr.tag="tag:yaml.org,2002:set";var EC={collection:"map",identify:e=>e instanceof Set,nodeClass:Kr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Kr.from(e,t,i),resolve(e,t){if(jc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Kr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ef.YAMLSet=Kr;ef.set=EC});var nf=C($c=>{"use strict";var PC=jn();function rf(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 gg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return PC.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 RC={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})=>rf(e,i),stringify:gg},CC={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=>rf(e,!1),stringify:gg},wg={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(wg.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=rf(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$/,"")??""};$c.floatTime=CC;$c.intTime=RC;$c.timestamp=wg});var bg=C(Ng=>{"use strict";var xC=Tn(),AC=bc(),_C=In(),TC=ro(),IC=Jd(),yg=hg(),af=pg(),Oc=vg(),jC=hc(),$C=Yd(),OC=xc(),HC=tf(),of=nf(),DC=[xC.map,_C.seq,TC.string,AC.nullTag,yg.trueTag,yg.falseTag,Oc.intBin,Oc.intOct,Oc.int,Oc.intHex,af.floatNaN,af.floatExp,af.float,IC.binary,jC.merge,$C.omap,OC.pairs,HC.set,of.intTime,of.floatTime,of.timestamp];Ng.schema=DC});var Tg=C(lf=>{"use strict";var Pg=Tn(),LC=bc(),Rg=In(),MC=ro(),FC=Ld(),sf=Fd(),cf=Vd(),BC=eg(),VC=rg(),Cg=Jd(),co=hc(),xg=Yd(),Ag=xc(),kg=bg(),_g=tf(),Hc=nf(),Sg=new Map([["core",BC.schema],["failsafe",[Pg.map,Rg.seq,MC.string]],["json",VC.schema],["yaml11",kg.schema],["yaml-1.1",kg.schema]]),Eg={binary:Cg.binary,bool:FC.boolTag,float:sf.float,floatExp:sf.floatExp,floatNaN:sf.floatNaN,floatTime:Hc.floatTime,int:cf.int,intHex:cf.intHex,intOct:cf.intOct,intTime:Hc.intTime,map:Pg.map,merge:co.merge,null:LC.nullTag,omap:xg.omap,pairs:Ag.pairs,seq:Rg.seq,set:_g.set,timestamp:Hc.timestamp},qC={"tag:yaml.org,2002:binary":Cg.binary,"tag:yaml.org,2002:merge":co.merge,"tag:yaml.org,2002:omap":xg.omap,"tag:yaml.org,2002:pairs":Ag.pairs,"tag:yaml.org,2002:set":_g.set,"tag:yaml.org,2002:timestamp":Hc.timestamp};function WC(e,t,i){let r=Sg.get(t);if(r&&!e)return i&&!r.includes(co.merge)?r.concat(co.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Sg.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(co.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Eg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Eg).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},[])}lf.coreKnownTags=qC;lf.getTags=WC});var ff=C(Ig=>{"use strict";var uf=G(),zC=Tn(),JC=In(),GC=ro(),Dc=Tg(),UC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,df=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,uf.MAP,{value:zC.map}),Object.defineProperty(this,uf.SCALAR,{value:GC.string}),Object.defineProperty(this,uf.SEQ,{value:JC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?UC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ig.Schema=df});var $g=C(jg=>{"use strict";var KC=G(),hf=eo(),lo=Ya();function YC(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=hf.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(lo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(KC.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(lo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=hf.stringify(e.contents,n,()=>s=null,c);s&&(l+=lo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(hf.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(lo.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(lo.indentComment(a(c),"")))}return i.join(`
57
+ ${a.comment}`:r.comment}r=n}e.items[i]=jc.isPair(r)?r:new af.Pair(r)}}else t("Expected a sequence for this tag");return e}function pg(e,t,i){let{replacer:r}=i,n=new PC.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(af.createPair(s,c,i))}return n}var RC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hg,createNode:pg};$c.createPairs=pg;$c.pairs=RC;$c.resolvePairs=hg});var cf=C(sf=>{"use strict";var mg=G(),of=Qi(),po=nr(),CC=ar(),vg=Oc(),Zr=class e extends CC.YAMLSeq{constructor(){super(),this.add=po.YAMLMap.prototype.add.bind(this),this.delete=po.YAMLMap.prototype.delete.bind(this),this.get=po.YAMLMap.prototype.get.bind(this),this.has=po.YAMLMap.prototype.has.bind(this),this.set=po.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(mg.isPair(n)?(a=of.toJS(n.key,"",i),o=of.toJS(n.value,a,i)):a=of.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=vg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Zr.tag="tag:yaml.org,2002:omap";var xC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Zr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=vg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)mg.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Zr,i)},createNode:(e,t,i)=>Zr.from(e,t,i)};sf.YAMLOMap=Zr;sf.omap=xC});var bg=C(lf=>{"use strict";var gg=ke();function wg({value:e,source:t},i){return t&&(e?yg:Ng).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var yg={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 gg.Scalar(!0),stringify:wg},Ng={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 gg.Scalar(!1),stringify:wg};lf.falseTag=Ng;lf.trueTag=yg});var kg=C(Hc=>{"use strict";var AC=ke(),uf=Bn(),_C={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:uf.stringifyNumber},IC={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():uf.stringifyNumber(e)}},TC={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 AC.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:uf.stringifyNumber};Hc.float=TC;Hc.floatExp=IC;Hc.floatNaN=_C});var Eg=C(vo=>{"use strict";var Sg=Bn(),mo=e=>typeof e=="bigint"||Number.isInteger(e);function Dc(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 df(e,t,i){let{value:r}=e;if(mo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Sg.stringifyNumber(e)}var jC={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Dc(e,2,2,i),stringify:e=>df(e,2,"0b")},$C={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Dc(e,1,8,i),stringify:e=>df(e,8,"0")},OC={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Dc(e,0,10,i),stringify:Sg.stringifyNumber},HC={identify:mo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Dc(e,2,16,i),stringify:e=>df(e,16,"0x")};vo.int=OC;vo.intBin=jC;vo.intHex=HC;vo.intOct=$C});var hf=C(ff=>{"use strict";var Fc=G(),Lc=ir(),Mc=nr(),en=class e extends Mc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Fc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Lc.Pair(t.key,null):i=new Lc.Pair(t,null),Mc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Mc.findPair(this.items,t);return!i&&Fc.isPair(r)?Fc.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=Mc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Lc.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(Lc.createPair(o,null,r));return a}};en.tag="tag:yaml.org,2002:set";var DC={collection:"map",identify:e=>e instanceof Set,nodeClass:en,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>en.from(e,t,i),resolve(e,t){if(Fc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new en,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ff.YAMLSet=en;ff.set=DC});var mf=C(Bc=>{"use strict";var LC=Bn();function pf(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 Pg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return LC.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 MC={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})=>pf(e,i),stringify:Pg},FC={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=>pf(e,!1),stringify:Pg},Rg={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(Rg.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=pf(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$/,"")??""};Bc.floatTime=FC;Bc.intTime=MC;Bc.timestamp=Rg});var Ag=C(xg=>{"use strict";var BC=Mn(),VC=xc(),qC=Fn(),WC=fo(),zC=nf(),Cg=bg(),vf=kg(),Vc=Eg(),JC=Nc(),GC=cf(),UC=Oc(),KC=hf(),gf=mf(),YC=[BC.map,qC.seq,WC.string,VC.nullTag,Cg.trueTag,Cg.falseTag,Vc.intBin,Vc.intOct,Vc.int,Vc.intHex,vf.floatNaN,vf.floatExp,vf.float,zC.binary,JC.merge,GC.omap,UC.pairs,KC.set,gf.intTime,gf.floatTime,gf.timestamp];xg.schema=YC});var Mg=C(Nf=>{"use strict";var jg=Mn(),XC=xc(),$g=Fn(),QC=fo(),ZC=Kd(),wf=Xd(),yf=Zd(),ex=cg(),tx=dg(),Og=nf(),go=Nc(),Hg=cf(),Dg=Oc(),_g=Ag(),Lg=hf(),qc=mf(),Ig=new Map([["core",ex.schema],["failsafe",[jg.map,$g.seq,QC.string]],["json",tx.schema],["yaml11",_g.schema],["yaml-1.1",_g.schema]]),Tg={binary:Og.binary,bool:ZC.boolTag,float:wf.float,floatExp:wf.floatExp,floatNaN:wf.floatNaN,floatTime:qc.floatTime,int:yf.int,intHex:yf.intHex,intOct:yf.intOct,intTime:qc.intTime,map:jg.map,merge:go.merge,null:XC.nullTag,omap:Hg.omap,pairs:Dg.pairs,seq:$g.seq,set:Lg.set,timestamp:qc.timestamp},ix={"tag:yaml.org,2002:binary":Og.binary,"tag:yaml.org,2002:merge":go.merge,"tag:yaml.org,2002:omap":Hg.omap,"tag:yaml.org,2002:pairs":Dg.pairs,"tag:yaml.org,2002:set":Lg.set,"tag:yaml.org,2002:timestamp":qc.timestamp};function rx(e,t,i){let r=Ig.get(t);if(r&&!e)return i&&!r.includes(go.merge)?r.concat(go.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Ig.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(go.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Tg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Tg).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},[])}Nf.coreKnownTags=ix;Nf.getTags=rx});var Sf=C(Fg=>{"use strict";var bf=G(),nx=Mn(),ax=Fn(),ox=fo(),Wc=Mg(),sx=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,kf=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Wc.getTags(t,"compat"):t?Wc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Wc.coreKnownTags:{},this.tags=Wc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,bf.MAP,{value:nx.map}),Object.defineProperty(this,bf.SCALAR,{value:ox.string}),Object.defineProperty(this,bf.SEQ,{value:ax.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?sx:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Fg.Schema=kf});var Vg=C(Bg=>{"use strict";var cx=G(),Ef=co(),wo=no();function lx(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=Ef.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(wo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(cx.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(wo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ef.stringify(e.contents,n,()=>s=null,c);s&&(l+=wo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Ef.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(wo.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(wo.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}jg.stringifyDocument=YC});var uo=C(Og=>{"use strict";var XC=Ua(),$n=rc(),Rt=G(),QC=Xi(),ZC=Gi(),ex=ff(),tx=$g(),pf=Zs(),ix=gd(),rx=Ka(),mf=vd(),vf=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Rt.NODE_TYPE,{value:Rt.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 mf.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,{[Rt.NODE_TYPE]:{value:Rt.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=Rt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){On(this.contents)&&this.contents.add(t)}addIn(t,i){On(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=pf.anchorNames(this);t.anchor=!i||r.has(i)?pf.findNewAnchor(i||"a",r):i}return new XC.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 p=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=i.filter(p).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}=pf.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=rx.createNode(t,u,v);return s&&Rt.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new QC.Pair(n,a)}delete(t){return On(this.contents)?this.contents.delete(t):!1}deleteIn(t){return $n.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):On(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Rt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return $n.isEmptyPath(t)?!i&&Rt.isScalar(this.contents)?this.contents.value:this.contents:Rt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Rt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return $n.isEmptyPath(t)?this.contents!==void 0:Rt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=$n.collectionFromPath(this.schema,[t],i):On(this.contents)&&this.contents.set(t,i)}setIn(t,i){$n.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=$n.collectionFromPath(this.schema,Array.from(t),i):On(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new mf.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 mf.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 ex.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=ZC.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"?ix.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 tx.stringifyDocument(this,t)}};function On(e){if(Rt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Og.Document=vf});var po=C(ho=>{"use strict";var fo=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},gf=class extends fo{constructor(t,i,r){super("YAMLParseError",t,i,r)}},wf=class extends fo{constructor(t,i,r){super("YAMLWarning",t,i,r)}},nx=(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
+ `}Bg.stringifyDocument=lx});var yo=C(qg=>{"use strict";var ux=io(),Vn=uc(),Rt=G(),dx=ir(),fx=Qi(),hx=Sf(),px=Vg(),Pf=oc(),mx=xd(),vx=ro(),Rf=Cd(),Cf=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Rt.NODE_TYPE,{value:Rt.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 Rf.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,{[Rt.NODE_TYPE]:{value:Rt.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=Rt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){qn(this.contents)&&this.contents.add(t)}addIn(t,i){qn(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Pf.anchorNames(this);t.anchor=!i||r.has(i)?Pf.findNewAnchor(i||"a",r):i}return new ux.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 p=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=i.filter(p).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}=Pf.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=vx.createNode(t,u,v);return s&&Rt.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new dx.Pair(n,a)}delete(t){return qn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Vn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):qn(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Rt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Vn.isEmptyPath(t)?!i&&Rt.isScalar(this.contents)?this.contents.value:this.contents:Rt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Rt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Vn.isEmptyPath(t)?this.contents!==void 0:Rt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Vn.collectionFromPath(this.schema,[t],i):qn(this.contents)&&this.contents.set(t,i)}setIn(t,i){Vn.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Vn.collectionFromPath(this.schema,Array.from(t),i):qn(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 Rf.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 Rf.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 hx.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=fx.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"?mx.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 px.stringifyDocument(this,t)}};function qn(e){if(Rt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}qg.Document=Cf});var ko=C(bo=>{"use strict";var No=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},xf=class extends No{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Af=class extends No{constructor(t,i,r){super("YAMLWarning",t,i,r)}},gx=(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
- `}};ho.YAMLError=fo;ho.YAMLParseError=gf;ho.YAMLWarning=wf;ho.prettifyError=nx});var mo=C(Hg=>{"use strict";function ax(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,m=null,p=null,b=null,g=null,y=null,E=null,k=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=N.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=N.source:(!E||i!=="seq-item-ind")&&(c=!0):f+=N.source,l=!0,h=!0,(p||b)&&(g=N),u=!0;break;case"anchor":p&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,k??(k=N.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),b=N,k??(k=N.offset),l=!1,u=!1,v=!0;break}case i:(p||b)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),E&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),E=N,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){y&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let S=e[e.length-1],R=S?S.offset+S.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"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:E,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:b,newlineAfterProp:g,end:R,start:k??R}}Hg.resolveProps=ax});var Lc=C(Dg=>{"use strict";function yf(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(yf(t.key)||yf(t.value))return!0}return!1;default:return!0}}Dg.containsNewline=yf});var Nf=C(Lg=>{"use strict";var ox=Lc();function sx(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&ox.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Lg.flowIndentCheck=sx});var bf=C(Fg=>{"use strict";var Mg=G();function cx(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Mg.isScalar(a)&&Mg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Fg.mapIncludes=cx});var Jg=C(zg=>{"use strict";var Bg=Xi(),lx=Zi(),Vg=mo(),ux=Lc(),qg=Nf(),dx=bf(),Wg="All mapping items must start at the same column";function fx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??lx.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,m=Vg.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!m.found;if(p){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",Wg)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
67
- `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||ux.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&n(c,"BAD_INDENT",Wg);i.atKey=!0;let b=m.end,g=f?e(i,f,m,n):t(i,b,d,null,m,n);i.schema.compat&&qg.flowIndentCheck(r.indent,f,n),i.atKey=!1,dx.mapIncludes(i,s.items,g)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let y=Vg.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=y.end,y.found){p&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&m.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=v?e(i,v,y,n):t(i,c,h,null,y,n);i.schema.compat&&qg.flowIndentCheck(r.indent,v,n),c=E.range[2];let k=new Bg.Pair(g,E);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
68
- `+y.comment:g.comment=y.comment);let E=new Bg.Pair(g);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}zg.resolveBlockMap=fx});var Ug=C(Gg=>{"use strict";var hx=er(),px=mo(),mx=Nf();function vx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??hx.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=px.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&&mx.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Gg.resolveBlockSeq=vx});var Hn=C(Kg=>{"use strict";function gx(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}}Kg.resolveEnd=gx});var Zg=C(Qg=>{"use strict";var wx=G(),yx=Xi(),Yg=Zi(),Nx=er(),bx=Hn(),Xg=mo(),kx=Lc(),Sx=bf(),kf="Block collections are not allowed within flow collections",Sf=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Ex({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:Nx.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 p=0;p<r.items.length;++p){let b=r.items[p],{start:g,key:y,sep:E,value:k}=b,S=Xg.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??E?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!E&&!k){p===0&&S.comma?n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<r.items.length-1&&n(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),S.comment&&(l.comment?l.comment+=`
69
- `+S.comment:l.comment=S.comment),d=S.end;continue}!o&&i.options.strict&&kx.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)S.comma&&n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(S.comma||n(S.start,"MISSING_CHAR",`Missing , between ${s} items`),S.comment){let R="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":R=N.source.substring(1);break e;default:break e}if(R){let N=l.items[l.items.length-1];wx.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
- `+R:N.comment=R,S.comment=S.comment.substring(R.length+1)}}if(!o&&!E&&!S.found){let R=k?e(i,k,S,n):t(i,S.end,E,null,S,n);l.items.push(R),d=R.range[2],Sf(k)&&n(R.range,"BLOCK_IN_FLOW",kf)}else{i.atKey=!0;let R=S.end,N=y?e(i,y,S,n):t(i,R,g,null,S,n);Sf(y)&&n(N.range,"BLOCK_IN_FLOW",kf),i.atKey=!1;let w=Xg.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:k,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!S.found&&i.options.strict){if(E)for(let $ of E){if($===w.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<w.found.offset-1024&&n(w.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(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,w,n):w.found?t(i,w.end,E,null,w,n):null;P?Sf(k)&&n(P.range,"BLOCK_IN_FLOW",kf):w.comment&&(N.comment?N.comment+=`
71
- `+w.comment:N.comment=w.comment);let F=new yx.Pair(N,P);if(i.options.keepSourceTokens&&(F.srcToken=b),o){let $=l;Sx.mapIncludes(i,$.items,N)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(F)}else{let $=new Yg.YAMLMap(i.schema);$.flow=!0,$.items.push(F);let Fe=(P??N).range;$.range=[N.range[0],Fe[1],Fe[2]],l.items.push($)}d=P?P.range[2]:w.end}}let f=o?"}":"]",[h,...v]=r.end,m=d;if(h?.source===f)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),b=u?`${p} must end with a ${f}`:`${p} 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 p=bx.resolveEnd(v,m,i.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
- `+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}Qg.resolveFlowCollection=Ex});var tw=C(ew=>{"use strict";var Px=G(),Rx=ke(),Cx=Zi(),xx=er(),Ax=Jg(),_x=Ug(),Tx=Zg();function Ef(e,t,i,r,n,a){let o=i.type==="block-map"?Ax.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?_x.resolveBlockSeq(e,t,i,r,a):Tx.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 Ix(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===Cx.YAMLMap.tagName&&s==="map"||o===xx.YAMLSeq.tagName&&s==="seq")return Ef(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),Ef(e,t,i,n,o)}let l=Ef(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Px.isNode(u)?u:new Rx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ew.composeCollection=Ix});var Rf=C(iw=>{"use strict";var Pf=ke();function jx(e,t,i){let r=t.offset,n=$x(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Pf.Scalar.BLOCK_FOLDED:Pf.Scalar.BLOCK_LITERAL,o=t.source?Ox(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
65
+ `}};bo.YAMLError=No;bo.YAMLParseError=xf;bo.YAMLWarning=Af;bo.prettifyError=gx});var So=C(Wg=>{"use strict";function wx(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,m=null,p=null,b=null,g=null,S=null,N=null,k=null;for(let y of e)switch(v&&(y.type!=="space"&&y.type!=="newline"&&y.type!=="comma"&&a(y.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&y.type!=="comment"&&y.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),y.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&y.source.includes(" ")&&(m=y),u=!0;break;case"comment":{u||a(y,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=y.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=y.source:(!N||i!=="seq-item-ind")&&(c=!0):f+=y.source,l=!0,h=!0,(p||b)&&(g=y),u=!0;break;case"anchor":p&&a(y,"MULTIPLE_ANCHORS","A node can have at most one anchor"),y.source.endsWith(":")&&a(y.offset+y.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=y,k??(k=y.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(y,"MULTIPLE_TAGS","A node can have at most one tag"),b=y,k??(k=y.offset),l=!1,u=!1,v=!0;break}case i:(p||b)&&a(y,"BAD_PROP_ORDER",`Anchors and tags must be after the ${y.source} indicator`),N&&a(y,"UNEXPECTED_TOKEN",`Unexpected ${y.source} in ${t??"collection"}`),N=y,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){S&&a(y,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),S=y,l=!1,u=!1;break}default:a(y,"UNEXPECTED_TOKEN",`Unexpected ${y.type} token`),l=!1,u=!1}let E=e[e.length-1],R=E?E.offset+E.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"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:N,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:b,newlineAfterProp:g,end:R,start:k??R}}Wg.resolveProps=wx});var zc=C(zg=>{"use strict";function _f(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(_f(t.key)||_f(t.value))return!0}return!1;default:return!0}}zg.containsNewline=_f});var If=C(Jg=>{"use strict";var yx=zc();function Nx(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&yx.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Jg.flowIndentCheck=Nx});var Tf=C(Ug=>{"use strict";var Gg=G();function bx(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Gg.isScalar(a)&&Gg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Ug.mapIncludes=bx});var ew=C(Zg=>{"use strict";var Kg=ir(),kx=nr(),Yg=So(),Sx=zc(),Xg=If(),Ex=Tf(),Qg="All mapping items must start at the same column";function Px({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??kx.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,m=Yg.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!m.found;if(p){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",Qg)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
67
+ `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||Sx.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&n(c,"BAD_INDENT",Qg);i.atKey=!0;let b=m.end,g=f?e(i,f,m,n):t(i,b,d,null,m,n);i.schema.compat&&Xg.flowIndentCheck(r.indent,f,n),i.atKey=!1,Ex.mapIncludes(i,s.items,g)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let S=Yg.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){p&&(v?.type==="block-map"&&!S.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&m.start<S.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let N=v?e(i,v,S,n):t(i,c,h,null,S,n);i.schema.compat&&Xg.flowIndentCheck(r.indent,v,n),c=N.range[2];let k=new Kg.Pair(g,N);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(g.comment?g.comment+=`
68
+ `+S.comment:g.comment=S.comment);let N=new Kg.Pair(g);i.options.keepSourceTokens&&(N.srcToken=u),s.items.push(N)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Zg.resolveBlockMap=Px});var iw=C(tw=>{"use strict";var Rx=ar(),Cx=So(),xx=If();function Ax({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Rx.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=Cx.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&&xx.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}tw.resolveBlockSeq=Ax});var Wn=C(rw=>{"use strict";function _x(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}}rw.resolveEnd=_x});var sw=C(ow=>{"use strict";var Ix=G(),Tx=ir(),nw=nr(),jx=ar(),$x=Wn(),aw=So(),Ox=zc(),Hx=Tf(),jf="Block collections are not allowed within flow collections",$f=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?nw.YAMLMap:jx.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 p=0;p<r.items.length;++p){let b=r.items[p],{start:g,key:S,sep:N,value:k}=b,E=aw.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:S??N?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!N&&!k){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<r.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
+ `+E.comment:l.comment=E.comment),d=E.end;continue}!o&&i.options.strict&&Ox.containsNewline(S)&&n(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let R="";e:for(let y of g)switch(y.type){case"comma":case"space":break;case"comment":R=y.source.substring(1);break e;default:break e}if(R){let y=l.items[l.items.length-1];Ix.isPair(y)&&(y=y.value??y.key),y.comment?y.comment+=`
70
+ `+R:y.comment=R,E.comment=E.comment.substring(R.length+1)}}if(!o&&!N&&!E.found){let R=k?e(i,k,E,n):t(i,E.end,N,null,E,n);l.items.push(R),d=R.range[2],$f(k)&&n(R.range,"BLOCK_IN_FLOW",jf)}else{i.atKey=!0;let R=E.end,y=S?e(i,S,E,n):t(i,R,g,null,E,n);$f(S)&&n(y.range,"BLOCK_IN_FLOW",jf),i.atKey=!1;let w=aw.resolveProps(N??[],{flow:s,indicator:"map-value-ind",next:k,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!E.found&&i.options.strict){if(N)for(let $ of N){if($===w.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<w.found.offset-1024&&n(w.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(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,w,n):w.found?t(i,w.end,N,null,w,n):null;P?$f(k)&&n(P.range,"BLOCK_IN_FLOW",jf):w.comment&&(y.comment?y.comment+=`
71
+ `+w.comment:y.comment=w.comment);let F=new Tx.Pair(y,P);if(i.options.keepSourceTokens&&(F.srcToken=b),o){let $=l;Hx.mapIncludes(i,$.items,y)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(F)}else{let $=new nw.YAMLMap(i.schema);$.flow=!0,$.items.push(F);let Be=(P??y).range;$.range=[y.range[0],Be[1],Be[2]],l.items.push($)}d=P?P.range[2]:w.end}}let f=o?"}":"]",[h,...v]=r.end,m=d;if(h?.source===f)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),b=u?`${p} must end with a ${f}`:`${p} 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 p=$x.resolveEnd(v,m,i.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
+ `+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}ow.resolveFlowCollection=Dx});var lw=C(cw=>{"use strict";var Lx=G(),Mx=ke(),Fx=nr(),Bx=ar(),Vx=ew(),qx=iw(),Wx=sw();function Of(e,t,i,r,n,a){let o=i.type==="block-map"?Vx.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?qx.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 zx(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===Fx.YAMLMap.tagName&&s==="map"||o===Bx.YAMLSeq.tagName&&s==="seq")return Of(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),Of(e,t,i,n,o)}let l=Of(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Lx.isNode(u)?u:new Mx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}cw.composeCollection=zx});var Df=C(uw=>{"use strict";var Hf=ke();function Jx(e,t,i){let r=t.offset,n=Gx(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Hf.Scalar.BLOCK_FOLDED:Hf.Scalar.BLOCK_LITERAL,o=t.source?Ux(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",p=r+n.length;return t.source&&(p+=t.source.length),{value:m,type:a,comment:n.comment,range:[r,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[p,b]=o[m];if(b===""||b==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&i(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),u=m,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+b.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",f="",h=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
74
- `;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(g?2:1),"BAD_INDENT",E),p=""}a===Pf.Scalar.BLOCK_LITERAL?(d+=f+p.slice(c)+b,f=`
74
+ `;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let N=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(g?2:1),"BAD_INDENT",N),p=""}a===Hf.Scalar.BLOCK_LITERAL?(d+=f+p.slice(c)+b,f=`
75
75
  `):p.length>c||b[0]===" "?(f===" "?f=`
76
76
  `:!h&&f===`
77
77
  `&&(f=`
@@ -84,65 +84,65 @@ ${l}
84
84
  `+o[m][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 $x({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 m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Ox(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}iw.resolveBlockScalar=jx});var xf=C(nw=>{"use strict";var Cf=ke(),Hx=Hn();function Dx(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=Cf.Scalar.PLAIN,c=Lx(a,l);break;case"single-quoted-scalar":s=Cf.Scalar.QUOTE_SINGLE,c=Mx(a,l);break;case"double-quoted-scalar":s=Cf.Scalar.QUOTE_DOUBLE,c=Fx(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=Hx.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Lx(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}`),rw(e)}function Mx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),rw(e.slice(1,-1)).replace(/''/g,"'")}function rw(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 Gx({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 m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Ux(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}uw.resolveBlockScalar=Jx});var Mf=C(fw=>{"use strict";var Lf=ke(),Kx=Wn();function Yx(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=Lf.Scalar.PLAIN,c=Xx(a,l);break;case"single-quoted-scalar":s=Lf.Scalar.QUOTE_SINGLE,c=Qx(a,l);break;case"double-quoted-scalar":s=Lf.Scalar.QUOTE_DOUBLE,c=Zx(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=Kx.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Xx(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}`),dw(e)}function Qx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),dw(e.slice(1,-1)).replace(/''/g,"'")}function dw(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 Fx(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 Zx(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}=Bx(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Vx[a];if(o)i+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=eA(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=tA[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+=qx(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+=iA(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 Bx(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 eA(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 Vx={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function qx(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}}nw.resolveFlowScalar=Dx});var sw=C(ow=>{"use strict";var Yr=G(),aw=ke(),Wx=Rf(),zx=xf();function Jx(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Wx.resolveBlockScalar(e,t,r):zx.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[Yr.SCALAR]:c?l=Gx(e.schema,n,c,i,r):t.type==="scalar"?l=Ux(e,n,t,r):l=e.schema[Yr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Yr.isScalar(d)?d:new aw.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new aw.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 Gx(e,t,i,r,n){if(i==="!")return e[Yr.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[Yr.SCALAR])}function Ux({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[Yr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Yr.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}ow.composeScalar=Jx});var lw=C(cw=>{"use strict";function Kx(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}cw.emptyScalarPosition=Kx});var fw=C(_f=>{"use strict";var Yx=Ua(),Xx=G(),Qx=tw(),uw=sw(),Zx=Hn(),eA=lw(),tA={composeNode:dw,composeEmptyNode:Af};function dw(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=iA(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=uw.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Qx.composeCollection(tA,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=Af(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&&(!Xx.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 Af(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:eA.emptyScalarPosition(t,i,r),indent:-1,source:""},d=uw.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 iA({options:e},{offset:t,source:i,end:r},n){let a=new Yx.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=Zx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}_f.composeEmptyNode=Af;_f.composeNode=dw});var mw=C(pw=>{"use strict";var rA=uo(),hw=fw(),nA=Hn(),aA=mo();function oA(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new rA.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=aA.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?hw.composeNode(l,n,u,o):hw.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=nA.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}pw.composeDoc=oA});var If=C(ww=>{"use strict";var sA=Js("process"),cA=vd(),lA=uo(),vo=po(),vw=G(),uA=mw(),dA=Hn();function go(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 gw(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 tA={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function iA(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}}fw.resolveFlowScalar=Yx});var mw=C(pw=>{"use strict";var tn=G(),hw=ke(),rA=Df(),nA=Mf();function aA(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?rA.resolveBlockScalar(e,t,r):nA.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[tn.SCALAR]:c?l=oA(e.schema,n,c,i,r):t.type==="scalar"?l=sA(e,n,t,r):l=e.schema[tn.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=tn.isScalar(d)?d:new hw.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new hw.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 oA(e,t,i,r,n){if(i==="!")return e[tn.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[tn.SCALAR])}function sA({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[tn.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[tn.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}pw.composeScalar=aA});var gw=C(vw=>{"use strict";function cA(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}vw.emptyScalarPosition=cA});var Nw=C(Bf=>{"use strict";var lA=io(),uA=G(),dA=lw(),ww=mw(),fA=Wn(),hA=gw(),pA={composeNode:yw,composeEmptyNode:Ff};function yw(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=mA(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=ww.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=dA.composeCollection(pA,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=Ff(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&&(!uA.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 Ff(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:hA.emptyScalarPosition(t,i,r),indent:-1,source:""},d=ww.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 mA({options:e},{offset:t,source:i,end:r},n){let a=new lA.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=fA.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Bf.composeEmptyNode=Ff;Bf.composeNode=yw});var Sw=C(kw=>{"use strict";var vA=yo(),bw=Nw(),gA=Wn(),wA=So();function yA(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new vA.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=wA.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?bw.composeNode(l,n,u,o):bw.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=gA.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}kw.composeDoc=yA});var qf=C(Rw=>{"use strict";var NA=Zs("process"),bA=Cd(),kA=yo(),Eo=ko(),Ew=G(),SA=Sw(),EA=Wn();function Po(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 Pw(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 Tf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=go(i);a?this.warnings.push(new vo.YAMLWarning(o,r,n)):this.errors.push(new vo.YAMLParseError(o,r,n))},this.directives=new cA.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=gw(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(vw.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];vw.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 Vf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=Po(i);a?this.warnings.push(new Eo.YAMLWarning(o,r,n)):this.errors.push(new Eo.YAMLParseError(o,r,n))},this.directives=new bA.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=Pw(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(Ew.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Ew.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:gw(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(sA.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=go(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=uA.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 vo.YAMLParseError(go(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 vo.YAMLParseError(go(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=dA.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 vo.YAMLParseError(go(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 lA.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}}};ww.Composer=Tf});var bw=C(Mc=>{"use strict";var fA=Rf(),hA=xf(),pA=po(),yw=Za();function mA(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 pA.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return hA.resolveFlowScalar(e,t,r);case"block-scalar":return fA.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function vA(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=yw.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:Pw(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(NA.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=Po(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=SA.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 Eo.YAMLParseError(Po(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 Eo.YAMLParseError(Po(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=EA.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 Eo.YAMLParseError(Po(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 kA.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}}};Rw.Composer=Vf});var Aw=C(Jc=>{"use strict";var PA=Df(),RA=Mf(),CA=ko(),Cw=so();function xA(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 CA.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return RA.resolveFlowScalar(e,t,r);case"block-scalar":return PA.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function AA(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Cw.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 Nw(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 gA(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=yw.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">":wA(e,c);break;case'"':jf(e,c,"double-quoted-scalar");break;case"'":jf(e,c,"single-quoted-scalar");break;default:jf(e,c,"scalar")}}function wA(e,t){let i=t.indexOf(`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return xw(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 _A(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=Cw.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">":IA(e,c);break;case'"':Wf(e,c,"double-quoted-scalar");break;case"'":Wf(e,c,"single-quoted-scalar");break;default:Wf(e,c,"scalar")}}function IA(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}];Nw(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 Nw(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 jf(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})}}}Mc.createScalarToken=vA;Mc.resolveAsScalar=mA;Mc.setScalarValue=gA});var Sw=C(kw=>{"use strict";var yA=e=>"type"in e?Bc(e):Fc(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+=Fc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Fc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Fc(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 Fc({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}kw.stringify=yA});var Cw=C(Rw=>{"use strict";var $f=Symbol("break visit"),NA=Symbol("skip children"),Ew=Symbol("remove item");function Xr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Pw(Object.freeze([]),e,t)}Xr.BREAK=$f;Xr.SKIP=NA;Xr.REMOVE=Ew;Xr.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};Xr.parentCollection=(e,t)=>{let i=Xr.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 Pw(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=Pw(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===$f)return $f;s===Ew&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Rw.visit=Xr});var Vc=C(st=>{"use strict";var Of=bw(),bA=Sw(),kA=Cw(),Hf="\uFEFF",Df="",Lf="",Mf="",SA=e=>!!e&&"items"in e,EA=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function PA(e){switch(e){case Hf:return"<BOM>";case Df:return"<DOC>";case Lf:return"<FLOW_END>";case Mf:return"<SCALAR>";default:return JSON.stringify(e)}}function RA(e){switch(e){case Hf:return"byte-order-mark";case Df:return"doc-mode";case Lf:return"flow-error-end";case Mf: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}];xw(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 xw(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 Wf(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})}}}Jc.createScalarToken=AA;Jc.resolveAsScalar=xA;Jc.setScalarValue=_A});var Iw=C(_w=>{"use strict";var TA=e=>"type"in e?Uc(e):Gc(e);function Uc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Uc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Gc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Gc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Gc(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Gc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Uc(t)),i)for(let a of i)n+=a.source;return r&&(n+=Uc(r)),n}_w.stringify=TA});var Ow=C($w=>{"use strict";var zf=Symbol("break visit"),jA=Symbol("skip children"),Tw=Symbol("remove item");function rn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),jw(Object.freeze([]),e,t)}rn.BREAK=zf;rn.SKIP=jA;rn.REMOVE=Tw;rn.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};rn.parentCollection=(e,t)=>{let i=rn.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 jw(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=jw(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===zf)return zf;s===Tw&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}$w.visit=rn});var Kc=C(st=>{"use strict";var Jf=Aw(),$A=Iw(),OA=Ow(),Gf="\uFEFF",Uf="",Kf="",Yf="",HA=e=>!!e&&"items"in e,DA=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function LA(e){switch(e){case Gf:return"<BOM>";case Uf:return"<DOC>";case Kf:return"<FLOW_END>";case Yf:return"<SCALAR>";default:return JSON.stringify(e)}}function MA(e){switch(e){case Gf:return"byte-order-mark";case Uf:return"doc-mode";case Kf:return"flow-error-end";case Yf: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}st.createScalarToken=Of.createScalarToken;st.resolveAsScalar=Of.resolveAsScalar;st.setScalarValue=Of.setScalarValue;st.stringify=bA.stringify;st.visit=kA.visit;st.BOM=Hf;st.DOCUMENT=Df;st.FLOW_END=Lf;st.SCALAR=Mf;st.isCollection=SA;st.isScalar=EA;st.prettyToken=PA;st.tokenType=RA});var Vf=C(Aw=>{"use strict";var wo=Vc();function zt(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var xw=new Set("0123456789ABCDEFabcdef"),CA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qc=new Set(",[]{}"),xA=new Set(` ,[]{}
121
- \r `),Ff=e=>!e||xA.has(e),Bf=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}st.createScalarToken=Jf.createScalarToken;st.resolveAsScalar=Jf.resolveAsScalar;st.setScalarValue=Jf.setScalarValue;st.stringify=$A.stringify;st.visit=OA.visit;st.BOM=Gf;st.DOCUMENT=Uf;st.FLOW_END=Kf;st.SCALAR=Yf;st.isCollection=HA;st.isScalar=DA;st.prettyToken=LA;st.tokenType=MA});var Zf=C(Dw=>{"use strict";var Ro=Kc();function Jt(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Hw=new Set("0123456789ABCDEFabcdef"),FA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Yc=new Set(",[]{}"),BA=new Set(` ,[]{}
121
+ \r `),Xf=e=>!e||BA.has(e),Qf=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==="...")&&zt(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]===wo.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 wo.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==="...")&&zt(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&&!zt(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===":")&&zt(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ff),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&zt(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield wo.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Ff),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||zt(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==="...")&&Jt(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]===Ro.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 Ro.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==="...")&&Jt(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&&!Jt(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===":")&&Jt(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(Xf),"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("..."))&&Jt(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Ro.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(Xf),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Jt(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=>zt(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=>Jt(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 wo.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(zt(a)||t&&qc.has(a))break;i=r}else if(zt(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 Ro.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(Jt(a)||t&&Yc.has(a))break;i=r}else if(Jt(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&&qc.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&&qc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield wo.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Ff),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(zt(r)||i&&qc.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(;!zt(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(CA.has(i))i=this.buffer[++t];else if(i==="%"&&xw.has(this.buffer[t+1])&&xw.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&&Yc.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&&Yc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Ro.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(Xf),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Jt(r)||i&&Yc.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(;!Jt(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(FA.has(i))i=this.buffer[++t];else if(i==="%"&&Hw.has(this.buffer[t+1])&&Hw.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)}};Aw.Lexer=Bf});var Wf=C(_w=>{"use strict";var qf=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}}}};_w.LineCounter=qf});var Jf=C(Ow=>{"use strict";var AA=Js("process"),Tw=Vc(),_A=Vf();function tr(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Iw(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 $w(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 Dn(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 zc(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 jw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!tr(t.start,"explicit-key-ind")&&!tr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,$w(t.value)?t.value.end?zc(t.value.end,t.sep):t.value.end=t.sep:zc(t.start,t.sep),delete t.sep)}var zf=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 _A.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,AA.env.LOG_TOKENS&&console.log("|",Tw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Tw.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"&&jw(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&&Iw(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":{Iw(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=Dn(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)}};Dw.Lexer=Qf});var th=C(Lw=>{"use strict";var eh=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}}}};Lw.LineCounter=eh});var rh=C(qw=>{"use strict";var VA=Zs("process"),Mw=Kc(),qA=Zf();function or(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Fw(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 Vw(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 Xc(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 zn(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 Qc(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 Bw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!or(t.start,"explicit-key-ind")&&!or(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Vw(t.value)?t.value.end?Qc(t.value.end,t.sep):t.value.end=t.sep:Qc(t.start,t.sep),delete t.sep)}var ih=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 qA.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,VA.env.LOG_TOKENS&&console.log("|",Mw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Mw.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"&&Bw(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&&Fw(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":{Fw(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=Xc(this.peek(2)),r=zn(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)){zc(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(tr(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($w(i.key)&&!tr(i.sep,"newline")){let o=Dn(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(tr(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Dn(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]}):tr(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&&!tr(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)){zc(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||tr(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=Dn(n);jw(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)){Qc(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(or(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(Vw(i.key)&&!or(i.sep,"newline")){let o=zn(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(or(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=zn(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]}):or(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&&!or(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)){Qc(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||or(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=Xc(r),a=zn(n);Bw(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=Dn(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=Dn(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())}}};Ow.Parser=zf});var Fw=C(No=>{"use strict";var Hw=If(),TA=uo(),yo=po(),IA=Ad(),jA=G(),$A=Wf(),Dw=Jf();function Lw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new $A.LineCounter||null,prettyErrors:t}}function OA(e,t={}){let{lineCounter:i,prettyErrors:r}=Lw(t),n=new Dw.Parser(i?.addNewLine),a=new Hw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(yo.prettifyError(e,i)),s.warnings.forEach(yo.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Mw(e,t={}){let{lineCounter:i,prettyErrors:r}=Lw(t),n=new Dw.Parser(i?.addNewLine),a=new Hw.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 yo.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(yo.prettifyError(e,i)),o.warnings.forEach(yo.prettifyError(e,i))),o}function HA(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Mw(e,i);if(!n)return null;if(n.warnings.forEach(a=>IA.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 DA(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 jA.isDocument(e)&&!r?e.toString(i):new TA.Document(e,r,i).toString(i)}No.parse=HA;No.parseAllDocuments=OA;No.parseDocument=Mw;No.stringify=DA});var Qr=C(X=>{"use strict";var LA=If(),MA=uo(),FA=ff(),Gf=po(),BA=Ua(),ir=G(),VA=Xi(),qA=ke(),WA=Zi(),zA=er(),JA=Vc(),GA=Vf(),UA=Wf(),KA=Jf(),Jc=Fw(),Bw=Wa();X.Composer=LA.Composer;X.Document=MA.Document;X.Schema=FA.Schema;X.YAMLError=Gf.YAMLError;X.YAMLParseError=Gf.YAMLParseError;X.YAMLWarning=Gf.YAMLWarning;X.Alias=BA.Alias;X.isAlias=ir.isAlias;X.isCollection=ir.isCollection;X.isDocument=ir.isDocument;X.isMap=ir.isMap;X.isNode=ir.isNode;X.isPair=ir.isPair;X.isScalar=ir.isScalar;X.isSeq=ir.isSeq;X.Pair=VA.Pair;X.Scalar=qA.Scalar;X.YAMLMap=WA.YAMLMap;X.YAMLSeq=zA.YAMLSeq;X.CST=JA;X.Lexer=GA.Lexer;X.LineCounter=UA.LineCounter;X.Parser=KA.Parser;X.parse=Jc.parse;X.parseAllDocuments=Jc.parseAllDocuments;X.parseDocument=Jc.parseDocument;X.stringify=Jc.stringify;X.visit=Bw.visit;X.visitAsync=Bw.visitAsync});import{promises as uP}from"node:fs";import od from"node:path";import{promises as Qu}from"fs";import Ie from"path";import{promises as JS}from"fs";import Oa from"path";import{isDeepStrictEqual as ZD}from"util";import{createHash as yP}from"crypto";function zm(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 Jm(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Jm(e[t]);return Object.freeze(e)}function Ji(e){return Jm(structuredClone(e))}function cd(e,t,i,r){return e.resolveStep({pkg:Ji(t),state:Ji(i),context:Ji(r)})}function Gm(e,t,i,r,n,a){return e.resolveNext({pkg:Ji(t),state:Ji(i),step:Ji(r),outcome:Ji(n),context:Ji(a)})}function NP(e,t,i){return yP("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function ld(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Um(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=cd(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=ld(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:NP(s.runId,s.iteration,o.id),stepId:o.id};return bP(e,s,c,i)}function bP(e,t,i,r){let n=zm(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"?cd(r,e,t,n):void 0,o=a?ld(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"?Gm(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!ld(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 ep}from"fs";import fb from"path";var ud={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},Ym={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},Xm={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},Qm=new Map,dd=new Map;for(let e of Object.keys(ud)){for(let[t,i]of Object.entries(ud[e]))Qm.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Ym[e]))dd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Xm[e]))dd.set(i.toLocaleLowerCase("en-US"),t)}function kP(e,t){return ud[e][t]}function fd(e,t){return Ym[e][t]??Xm[e][t]}function Gs(e){return Qm.get(e.trim().toLocaleLowerCase("en-US"))??null}function Zm(e){return dd.get(e.trim().toLocaleLowerCase("en-US"))??null}function Us(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${kP(e,i)}
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=Xc(t),r=zn(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=Xc(t),r=zn(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())}}};qw.Parser=ih});var Uw=C(xo=>{"use strict";var Ww=qf(),WA=yo(),Co=ko(),zA=Fd(),JA=G(),GA=th(),zw=rh();function Jw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new GA.LineCounter||null,prettyErrors:t}}function UA(e,t={}){let{lineCounter:i,prettyErrors:r}=Jw(t),n=new zw.Parser(i?.addNewLine),a=new Ww.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(Co.prettifyError(e,i)),s.warnings.forEach(Co.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Gw(e,t={}){let{lineCounter:i,prettyErrors:r}=Jw(t),n=new zw.Parser(i?.addNewLine),a=new Ww.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 Co.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(Co.prettifyError(e,i)),o.warnings.forEach(Co.prettifyError(e,i))),o}function KA(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Gw(e,i);if(!n)return null;if(n.warnings.forEach(a=>zA.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 YA(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 JA.isDocument(e)&&!r?e.toString(i):new WA.Document(e,r,i).toString(i)}xo.parse=KA;xo.parseAllDocuments=UA;xo.parseDocument=Gw;xo.stringify=YA});var nn=C(X=>{"use strict";var XA=qf(),QA=yo(),ZA=Sf(),nh=ko(),e_=io(),sr=G(),t_=ir(),i_=ke(),r_=nr(),n_=ar(),a_=Kc(),o_=Zf(),s_=th(),c_=rh(),Zc=Uw(),Kw=Qa();X.Composer=XA.Composer;X.Document=QA.Document;X.Schema=ZA.Schema;X.YAMLError=nh.YAMLError;X.YAMLParseError=nh.YAMLParseError;X.YAMLWarning=nh.YAMLWarning;X.Alias=e_.Alias;X.isAlias=sr.isAlias;X.isCollection=sr.isCollection;X.isDocument=sr.isDocument;X.isMap=sr.isMap;X.isNode=sr.isNode;X.isPair=sr.isPair;X.isScalar=sr.isScalar;X.isSeq=sr.isSeq;X.Pair=t_.Pair;X.Scalar=i_.Scalar;X.YAMLMap=r_.YAMLMap;X.YAMLSeq=n_.YAMLSeq;X.CST=a_;X.Lexer=o_.Lexer;X.LineCounter=s_.LineCounter;X.Parser=c_.Parser;X.parse=Zc.parse;X.parseAllDocuments=Zc.parseAllDocuments;X.parseDocument=Zc.parseDocument;X.stringify=Zc.stringify;X.visit=Kw.visit;X.visitAsync=Kw.visitAsync});import{promises as SP}from"node:fs";import gd from"node:path";import{promises as ld}from"fs";import je from"path";import{promises as rE}from"fs";import qa from"path";import{isDeepStrictEqual as hL}from"util";import{createHash as TP}from"crypto";function Zm(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 ev(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))ev(e[t]);return Object.freeze(e)}function Xi(e){return ev(structuredClone(e))}function yd(e,t,i,r){return e.resolveStep({pkg:Xi(t),state:Xi(i),context:Xi(r)})}function tv(e,t,i,r,n,a){return e.resolveNext({pkg:Xi(t),state:Xi(i),step:Xi(r),outcome:Xi(n),context:Xi(a)})}function jP(e,t,i){return TP("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Nd(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function iv(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=yd(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=Nd(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:jP(s.runId,s.iteration,o.id),stepId:o.id};return $P(e,s,c,i)}function $P(e,t,i,r){let n=Zm(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 rv(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"?yd(r,e,t,n):void 0,o=a?Nd(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"?tv(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Nd(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 cp}from"fs";import bb from"path";var bd={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},nv={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},av={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},ov=new Map,kd=new Map;for(let e of Object.keys(bd)){for(let[t,i]of Object.entries(bd[e]))ov.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(nv[e]))kd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(av[e]))kd.set(i.toLocaleLowerCase("en-US"),t)}function OP(e,t){return bd[e][t]}function Sd(e,t){return nv[e][t]??av[e][t]}function ec(e){return ov.get(e.trim().toLocaleLowerCase("en-US"))??null}function sv(e){return kd.get(e.trim().toLocaleLowerCase("en-US"))??null}function tc(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${OP(e,i)}
143
143
  `).join(`
144
- `)}function qt(e,t,i){return e==="zh-CN"?i:t}var Gl=Rn(Qr(),1);import{promises as ib}from"fs";import mi from"path";import{execFileSync as YA}from"child_process";import bo from"path";function rr(e,t){return YA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function XA(e,t){let i=bo.normalize(e),r=bo.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function fe(e){try{let t=bo.resolve(rr(e,["rev-parse","--show-toplevel"])),r=rr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?bo.resolve(r.slice(9)):t,a=null;try{a=rr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!XA(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Vw(e){try{rr(e,["rev-parse","--is-inside-work-tree"]);let t=rr(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:bo.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 Jt(e){return Vw(e).map(t=>t.root)}function ko(e,t){try{return rr(e,["check-ref-format","--branch",t]),rr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function xi(e,t){try{let i=rr(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 t_}from"node:crypto";import{promises as Gt}from"node:fs";import Ct from"node:path";import{TextDecoder as i_}from"node:util";import Uf from"path";var QA=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ZA=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function e_(e){return e.toLowerCase().startsWith(".env")}function ci(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>e_(r))?"environment-file":i.some(r=>ZA.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>QA.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Kf(e,t){let i=ci(t);if(i)return i;let r=Uf.resolve(e.projectRoot,...t.split("/")),n=Uf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Uf.resolve(e.configFile)?"native-runtime":null}function nr(e){return e!==0&&e!==0n&&e!=="0"}function vt(e,t){return nr(e.dev)&&nr(t.dev)&&nr(e.ino)&&nr(t.ino)}function z(e,t){let i=nr(e.dev)&&nr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=nr(e.ino)&&nr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var So=1024*1024;function Yf(e,t){let i=Ct.relative(e,t);return i===""||!Ct.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ct.sep}`)}function r_(e){let t=Ct.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})||Ct.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=ci(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 n_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function a_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function qw(e){let t=await Gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Gt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function o_(e,t){let i=Ct.resolve(e),r=Ct.resolve(t);if(!Yf(i,r))throw new Error("Native artifact path is outside its root");let n=[await qw(i)],a=i;for(let o of Ct.relative(i,r).split(Ct.sep).filter(Boolean)){a=Ct.join(a,o);let s=await qw(a);if(!Yf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Ww(e){for(let t of e){let i=await Gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!a_(t,i)||await Gt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=r_(e.ref),i=e.maxBytes===null?null:n_(e.maxBytes??So),r=Ct.resolve(e.root,...t.split("/")),n=await o_(e.root,Ct.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Gt.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 Gt.realpath(r);if(!Yf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Gt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await Ww(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Gc(a,c)||!Gc(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 y=i===null?h.length:i+1-f,E=await s.read(h,0,Math.min(h.length,y),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await Ww(n),!m.isFile()||m.isSymbolicLink()||p!==o||!Gc(c,v)||!Gc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),g;try{g=new i_("utf-8",{fatal:!0}).decode(b)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:f,hash:e.includeHash===!1?null:t_("sha256").update(b).digest("hex"),text:g}}finally{await s.close()}}import{randomUUID as s_}from"crypto";import{promises as Ve}from"fs";import Ut from"path";function Xf(e,t){let i=Ut.relative(e,t);return i===""||!Ut.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ut.sep}`)}function c_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Qf(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function l_(e,t){return Qf(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function zw(e){let t=await Ve.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 Ve.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Eo(e){for(let t of e){let i=await Ve.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!c_(t,i)||await Ve.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function u_(e,t){let i=Ut.resolve(e),r=Ut.resolve(t);if(!Xf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await zw(i)],a=Ut.relative(i,r).split(Ut.sep).filter(Boolean),o=i;for(let s of a){await Eo(n),o=Ut.join(o,s);try{await Ve.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await zw(o);if(!Xf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Eo(n),n}async function d_(e){let t;try{t=await Ve.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 Jw(e,t,i={}){let r=Ut.dirname(e),n=i.containedRoot?await u_(i.containedRoot,r):null;n||await Ve.mkdir(r,{recursive:!0});let a=Ut.join(r,`.${Ut.basename(e)}.${s_()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await Ve.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ve.lstat(a),Ve.realpath(a)]);if(await Eo(n),!l.isFile()||l.isSymbolicLink()||!Qf(s,l)||!Xf(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(),!Qf(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 Eo(n);let l=await Ve.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!l_(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Ve.link(a,e),await Ve.unlink(a)):await Ve.rename(a,e),await d_(r)}catch(l){if(await o?.close(),!n)await Ve.rm(a,{force:!0});else try{await Eo(n),await Ve.rm(a,{force:!0})}catch{}throw l}}async function he(e,t,i={}){await Jw(e,t,i)}async function Gw(e,t,i={}){await Jw(e,t,i)}async function ee(e,t,i={}){await he(e,JSON.stringify(t,null,2)+`
145
- `,i)}import V_ from"path";var Po=Rn(Qr(),1);import ar from"path";var Ro=64*1024,Kc=1024,Yc=64,Uw=1024,Kw=64,Qw=5,Uc={learning:!0,retrieval:!0},Zw={provider:"local"},f_=12e4,Yw=6e5,h_=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".dsh/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/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],p_=["**/.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"],m_=[...h_,...p_].sort((e,t)=>e.localeCompare(t,"en"));var Kt={include:["**/*"],exclude:[...m_],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ln={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
+ `)}function Wt(e,t,i){return e==="zh-CN"?i:t}var iu=$n(nn(),1);import{promises as db}from"fs";import vi from"path";import{execFileSync as l_}from"child_process";import Ao from"path";function cr(e,t){return l_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function u_(e,t){let i=Ao.normalize(e),r=Ao.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function fe(e){try{let t=Ao.resolve(cr(e,["rev-parse","--show-toplevel"])),r=cr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?Ao.resolve(r.slice(9)):t,a=null;try{a=cr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!u_(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Yw(e){try{cr(e,["rev-parse","--is-inside-work-tree"]);let t=cr(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:Ao.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 Gt(e){return Yw(e).map(t=>t.root)}function _o(e,t){try{return cr(e,["check-ref-format","--branch",t]),cr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Ai(e,t){try{let i=cr(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 p_}from"node:crypto";import{promises as Ut}from"node:fs";import Ct from"node:path";import{TextDecoder as m_}from"node:util";import ah from"path";var d_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),f_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function h_(e){return e.toLowerCase().startsWith(".env")}function ui(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>h_(r))?"environment-file":i.some(r=>f_.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>d_.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function oh(e,t){let i=ui(t);if(i)return i;let r=ah.resolve(e.projectRoot,...t.split("/")),n=ah.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===ah.resolve(e.configFile)?"native-runtime":null}function lr(e){return e!==0&&e!==0n&&e!=="0"}function vt(e,t){return lr(e.dev)&&lr(t.dev)&&lr(e.ino)&&lr(t.ino)}function z(e,t){let i=lr(e.dev)&&lr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=lr(e.ino)&&lr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var Io=1024*1024;function sh(e,t){let i=Ct.relative(e,t);return i===""||!Ct.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ct.sep}`)}function v_(e){let t=Ct.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})||Ct.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=ui(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 g_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function w_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function el(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Xw(e){let t=await Ut.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ut.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function y_(e,t){let i=Ct.resolve(e),r=Ct.resolve(t);if(!sh(i,r))throw new Error("Native artifact path is outside its root");let n=[await Xw(i)],a=i;for(let o of Ct.relative(i,r).split(Ct.sep).filter(Boolean)){a=Ct.join(a,o);let s=await Xw(a);if(!sh(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Qw(e){for(let t of e){let i=await Ut.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!w_(t,i)||await Ut.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=v_(e.ref),i=e.maxBytes===null?null:g_(e.maxBytes??Io),r=Ct.resolve(e.root,...t.split("/")),n=await y_(e.root,Ct.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ut.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 Ut.realpath(r);if(!sh(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ut.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ut.lstat(r),Ut.realpath(r)]);if(await Qw(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!el(a,c)||!el(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 S=i===null?h.length:i+1-f,N=await s.read(h,0,Math.min(h.length,S),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Ut.lstat(r),Ut.realpath(r)]);if(await Qw(n),!m.isFile()||m.isSymbolicLink()||p!==o||!el(c,v)||!el(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),g;try{g=new m_("utf-8",{fatal:!0}).decode(b)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:p_("sha256").update(b).digest("hex"),text:g}}finally{await s.close()}}import{randomUUID as N_}from"crypto";import{promises as _e}from"fs";import Kt from"path";function tl(e,t){let i=Kt.relative(e,t);return i===""||!Kt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Kt.sep}`)}function b_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function il(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function k_(e,t){return il(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Zw(e){let t=await _e.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 _e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Jn(e){for(let t of e){let i=await _e.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!b_(t,i)||await _e.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function S_(e,t,i){let[r,n]=await Promise.all([_e.lstat(e),_e.realpath(e),i?Jn(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!il(r,t)||i&&!tl(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function E_(e,t){let i=Kt.resolve(e),r=Kt.resolve(t);if(!tl(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Zw(i)],a=Kt.relative(i,r).split(Kt.sep).filter(Boolean),o=i;for(let s of a){await Jn(n),o=Kt.join(o,s);try{await _e.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zw(o);if(!tl(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Jn(n),n}async function P_(e){let t;try{t=await _e.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 ey(e,t,i={}){let r=Kt.dirname(e),n=i.containedRoot?await E_(i.containedRoot,r):null;n||await _e.mkdir(r,{recursive:!0});let a=Kt.join(r,`.${Kt.basename(e)}.${N_()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await _e.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([_e.lstat(a),_e.realpath(a)]);if(await Jn(n),!l.isFile()||l.isSymbolicLink()||!il(s,l)||!tl(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(),!il(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await S_(a,c,n),await i.beforeCommit?.(),n){await Jn(n);let l=await _e.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!k_(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await _e.link(a,e),await _e.unlink(a)):await _e.rename(a,e),await P_(r)}catch(l){if(await o?.close(),!n)await _e.rm(a,{force:!0});else try{await Jn(n),await _e.rm(a,{force:!0})}catch{}throw l}}async function he(e,t,i={}){await ey(e,t,i)}async function ty(e,t,i={}){await ey(e,t,i)}async function ee(e,t,i={}){await he(e,JSON.stringify(t,null,2)+`
145
+ `,i)}import iI from"path";var To=$n(nn(),1);import ur from"path";var jo=64*1024,nl=1024,al=64,iy=1024,ry=64,oy=5,rl={learning:!0,retrieval:!0},sy={provider:"local"},R_=12e4,ny=6e5,C_=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/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/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],x_=["**/.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"],A_=[...C_,...x_].sort((e,t)=>e.localeCompare(t,"en"));var Yt={include:["**/*"],exclude:[...A_],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Gn={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.
146
146
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
147
147
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
148
148
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -166,48 +166,48 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
166
166
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
167
167
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
168
168
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
169
- # 可选值:true | false`}};function ey(e,t){return Ln[t][e]}function v_(e,t,i,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Ln.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Ln.en)return s}if(a===4&&t==="knowledge"&&r==="remote"){let s=`knowledge.remote.${o}`;if(s in Ln.en)return s}if(a===4&&t==="knowledge"&&r==="local"){let s=`knowledge.local.${o}`;if(s in Ln.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&i==="snapshot"){let s=`native.snapshot.${o}`;if(s in Ln.en)return s}return null}function Co(e,t){let i=[],r=null,n=null,a=null;for(let o of(0,Po.stringify)(e).trimEnd().split(`
170
- `)){let s=v_(o,r,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of ey(s,t).split(`
169
+ # 可选值:true | false`}};function cy(e,t){return Gn[t][e]}function __(e,t,i,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Gn.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Gn.en)return s}if(a===4&&t==="knowledge"&&r==="remote"){let s=`knowledge.remote.${o}`;if(s in Gn.en)return s}if(a===4&&t==="knowledge"&&r==="local"){let s=`knowledge.local.${o}`;if(s in Gn.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&i==="snapshot"){let s=`native.snapshot.${o}`;if(s in Gn.en)return s}return null}function $o(e,t){let i=[],r=null,n=null,a=null;for(let o of(0,To.stringify)(e).trimEnd().split(`
170
+ `)){let s=__(o,r,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of cy(s,t).split(`
171
171
  `))i.push(`${c}${l}`)}i.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?r="native":o.startsWith("classic:")?r="classic":o.startsWith("hook:")?r="hook":o.startsWith("memory:")?r="memory":o.startsWith("knowledge:")?r="knowledge":r=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(r==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),r==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return i.push(""),i.join(`
172
- `)}function g_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||ar.posix.isAbsolute(i)||ar.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 Mn(e){let t=g_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ty(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 Xc(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||ar.posix.isAbsolute(r)||ar.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 Ai(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function iy(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 Qc(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>Kc)throw new Error(`${t} exceeds ${Kc} 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>Yc)throw new Error(`${t} contains more than ${Yc} wildcard tokens`);return e}function Xw(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=>Qc(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Zf(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 w_(e){if(e===void 0)return{...Kt,include:[...Kt.include],exclude:[...Kt.exclude]};let t=Ai(e,"native.snapshot");return{include:Xw(t.include,"native.snapshot.include",Kt.include),exclude:Xw(t.exclude,"native.snapshot.exclude",Kt.exclude),max_files:Zf(t.max_files,Kt.max_files,"native.snapshot.max_files"),max_total_bytes:Zf(t.max_total_bytes,Kt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Zf(t.max_duration_ms,Kt.max_duration_ms,"native.snapshot.max_duration_ms")}}function y_(e){if(e===void 0)return;let t=Ai(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=Ai(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:Mn(r),toArtifactRoot:Mn(n),stage:a,...o?{cleanup:o}:{}}}function N_(e){if(e===void 0)return;let t=Ai(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ai(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(ar.posix.isAbsolute(r[0])||ar.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??f_;if(!Number.isSafeInteger(n)||n<1||n>Yw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Yw}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function b_(e,t={}){let i=Ai(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??Qw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=y_(i.pending_root_move),c=N_(i.finish);return{artifact_root:Mn(r),language:iy(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:w_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function k_(e){let t=Ai(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:ty(t.artifact_layout),language:iy(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function S_(e){let i=Ai(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)=>Xc(r,`hook.allow_paths[${n}]`)))]}}function E_(e){if(e===void 0)return{...Uc};let t=Ai(e,"memory"),i=t.learning??Uc.learning,r=t.retrieval??Uc.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function eh(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function P_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||ar.posix.isAbsolute(i)||ar.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>Uw)throw new Error(`${t} exceeds ${Uw} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Kw)throw new Error(`${t} contains more than ${Kw} wildcard tokens`);return i}function R_(e){let i=eh(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>P_(r,`knowledge.local.include[${n}]`)))]}}function C_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function x_(e){let t=eh(e,"knowledge.remote"),i=C_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function A_(e){if(e===void 0)return{...Zw};let t=eh(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:R_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:x_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function __(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function T_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)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 u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Fn(e,t={}){let i=(0,Po.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=__(n.ambient_resume),o=n.hook===void 0?void 0:S_(n.hook),s=E_(n.memory),c=A_(n.knowledge),l=n.native===void 0?void 0:b_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:k_(n.classic),d=T_(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function ry(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 ny(e){let t=e.knowledge??{...Zw};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Uc},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...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:ry(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 gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function xo(e,t){let i=ny(t),r=Fn((0,Po.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={...gt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=gt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=gt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...gt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...gt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=gt(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=gt(a.finish);o.finish={...s,pull_request:{...gt(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={...gt(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=gt(a.pending_root_move),c=ry(r.native.pending_root_move),l=gt(s.cleanup),u=gt(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={...gt(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 j_}from"crypto";import{promises as tl}from"fs";import or from"path";import{constants as Zc,promises as Zr}from"fs";var Yt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function th(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ay(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ao(e){return{dev:e.dev,ino:e.ino,birthtime:th(e)}}function el(e,t){let i=Ao(e),r=Ao(t);return vt(i,r)?z(i,r):z(i,r)&&th(e)===th(t)&&ay(e)===ay(t)&&e.size===t.size}async function en(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 Zr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Yt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Yt("too-large",`${r} exceeds ${t} bytes`);let o=await Zr.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Ao(a)});let s=process.platform==="win32"?Zc.O_RDONLY:Zc.O_RDONLY|Zc.O_NOFOLLOW|Zc.O_NONBLOCK,c;try{c=await Zr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Yt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Zr.lstat(e,{bigint:n}),Zr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!el(a,l)||!el(a,u))throw new Yt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Ao(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(h+=y,h>t)throw new Yt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),Zr.lstat(e,{bigint:n}),Zr.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!el(a,m)||!el(a,p))throw new Yt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Ao(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function I_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ih(e,t){let i=or.relative(e,t);return i===""||!or.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${or.sep}`)}async function oy(e,t){let i=or.resolve(e),r=await tl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return tl.realpath(i)}async function sy(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=or.join(n,i[a]);let o;try{o=await tl.lstat(n)}catch(u){if(I_(u))return{exists:!1,kind:"missing"};throw u}let s=or.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 tl.realpath(n);if(!ih(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 Bn(e,t,i){let r=Xc(t,i.label),n=or.resolve(e),a=await oy(n,i.label),o=r.split("/"),s=or.resolve(n,...o);if(!ih(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await sy(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function sr(e,t,i,r){let n=await Bn(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 oy(n.projectRoot,r.label);return en(n.target,i,{...r,verify:async(o,s)=>{if(!ih(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await sy(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var _o=".comet/config.yaml";function rh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function $_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function il(e,t={}){return(await To(e,t)).document}async function cy(e){try{return(await sr(e,_o,Ro,{label:_o})).bytes}catch(t){if($_(t))return null;throw t}}function ly(e){return e?{exists:!0,sha256:j_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function rl(e){return ly(await cy(e))}async function To(e,t={}){let i=await cy(e);return{document:i?Fn(i.toString("utf8"),t):null,identity:ly(i)}}async function nh(e){return(await il(e))?.config??null}var qV=16*1024;async function ah(e,t){if(!t)return;let i=await rl(e);if(!rh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as uy,promises as cr}from"fs";import K from"path";import L_ from"os";var nl=".comet/config.yaml",M_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function oh(e){try{return await cr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function F_(e){try{let t=await cr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function qn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Vn(e){let t=[],i=e;for(;!await oh(i);){let n=K.dirname(i);if(n===i)break;t.push(K.basename(i)),i=n}let r=await cr.realpath(i);return K.resolve(r,...t.reverse())}async function sh(e){try{return(await cr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ch(e){let t=K.resolve(e);try{(await cr.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=K.resolve(L_.homedir());for(;;){if(!(t===r&&i!==r)){let o=K.join(t,...nl.split("/")),s=t===i||await F_(o);if(await oh(o)&&s)return t}if(await oh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function al(e){return Mn(e)}async function B_(e,t){let i=al(t),r=K.resolve(e,...i.split("/")),n=await cr.realpath(e),a=await Vn(r);if(!qn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function qe(e,t){let i=al(t),r=await B_(e,i),n=K.join(r,"comet");if(await sh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Vn(r),Vn(n)]);if(!qn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await sh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([cr.realpath(s),Vn(c)]);if(!qn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...nl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function fy(e){if(!M_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){fy(t);let i=K.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function tn(e,t){fy(t);let i=K.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=We(e,t);if(uy(i))return i;let r=tn(e,t);return uy(r)?r:i}async function dy(e){try{let t=await cr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function jo(e,t){let i=We(e,t),r=tn(e,t),[n,a]=await Promise.all([dy(i),dy(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 lr(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=K.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=K.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return qn(K.resolve(e),K.resolve(t))}async function T(e,t){let i=K.resolve(e),r=K.resolve(t);if(!qn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await sh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Vn(i),Vn(r)]);if(!qn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var lh=Kt;var ol=Qc;async function ye(e){let t=(await il(e))?.config??null;return t?.native?t:null}async function Wn(e){let t=await ye(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 ur(e,t,i={}){let r=await To(e,{allowPartialProject:!0}),n=xo(r.document?.value??{},t),a=V_.join(e,...nl.split("/"));await he(a,Co(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ah(e,r.identity)}})}import{promises as MI}from"fs";import FI from"path";import{AsyncLocalStorage as q_}from"async_hooks";import{randomUUID as vy}from"crypto";import{promises as xt}from"fs";import gy from"os";import pe from"path";var py=16*1024,uh=".coordinator",W_=5e3,my=new q_,sl=new Map;function z_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function J_(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 wy(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 dh(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return vt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function cl(e,t){return dh(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function G_(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&&cl(e.identity,t.identity)}async function li(e){let t,i;try{let r=await en(e,py,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Yt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${py} 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:J_(JSON.parse(t.toString("utf8")),e),identity:wy(i)}}async function U_(e){return(await li(e))?.owner??null}function fh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==gy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=eT(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function K_(e,t){try{await xt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ll(e,t){let i=await li(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xt.mkdir(t,{recursive:!0});let r=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${vy()}.removed`);try{await xt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await li(r);if(!n||n.owner.id!==e.owner.id||!dh(n.identity,e.identity))throw await K_(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xt.rm(r,{force:!0}),"removed"}function yy(e){return{id:vy(),pid:process.pid,hostname:gy.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Ny(e,t){let i;try{i=await xt.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await U_(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)+`
173
- `,"utf8"),await i.sync(),wy(await i.stat({bigint:!0}))}finally{await i.close()}}async function Y_(e,t){let i=await T(e.runtimeDir,e.locksDir);await xt.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,pe.join(i,uh));await xt.mkdir(r,{recursive:!0});let n=yy(t),a=pe.join(r,`.${n.id}.tmp`),o=pe.join(r,`${n.id}.claim`);try{let s=await Ny(a,n);await xt.rename(a,o);let c=await li(o);if(!c||!dh(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 xt.rm(a,{force:!0})}}async function X_(e){let t=pe.dirname(e.file),i=!1,r=pe.basename(e.file);for(let n of await xt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=pe.join(t,n.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await li(a),s=fh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ll(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function by(e){let t=await li(e.file);if(t){if(t.owner.id!==e.owner.id||!cl(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ll(t,pe.dirname(e.file))}}async function Q_(e,t){let i=Date.now()+W_;for(;;){let r=await Y_(e,t);if(!await X_(r))return r;if(await by(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 Z_(e){let t=sl.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return sl.set(e,n),await t,()=>{i(),sl.get(e)===n&&sl.delete(e)}}async function ul(e,t,i){let r=pe.resolve(e.locksDir),n=my.getStore();if(n?.has(r))return i();let a=await Z_(r);try{let o=await Q_(e,t),s=new Map(n??[]);return s.set(r,o),await my.run(s,async()=>{try{return await i()}finally{await by(o)}})}finally{a()}}async function zn(e,t,i){let r=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?ul(o,t,()=>n(a+1)):i()};return n(0)}async function dr(e,t,i){return ul(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await xt.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,pe.join(r,z_(t))),a=yy(i),o=await Ny(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function fr(e){await li(e.file)&&await ul({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${pe.basename(e.file)}`,async()=>{let t=await li(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cl(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,uh);await ll(t,i)})}function eT(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function $o(e){return fh(await li(e))}async function hh(e,t,i){return ul(e,`take over ${pe.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(pe.resolve(pe.dirname(n))!==pe.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await li(n),o=fh(a);if(o.status==="missing")return{status:"missing"};if(i&&!G_(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(r,uh);return await ll(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as oI}from"node:fs";import Eh from"node:path";import zT from"node:path";import Iy from"node:path";import ky from"node:path";import{createHash as tT}from"crypto";function Xt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function iT(e,t){t.has(e)&&Xt("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)||Xt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Xt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Xt("symbol properties are not supported"),`[${e.map(r=>ph(r,t)).join(",")}]`}finally{t.delete(e)}}function rT(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Xt("only plain objects are supported"),t.has(e)&&Xt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Xt("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))&&Xt("accessor properties are not supported"),`${JSON.stringify(o)}:${ph(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ph(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)||Xt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?iT(e,t):rT(e,t);case"bigint":case"function":case"symbol":case"undefined":return Xt(`${typeof e} values are not supported`)}return Xt("unsupported value type")}function Oo(e){return ph(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return tT("sha256").update(`${e}
174
- ${Oo(t)}`).digest("hex")}var nT="comet.native.acceptance.v1",aT=/^acceptance-[a-f0-9]{64}$/u,oT=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),sT=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,cT=/^[a-f0-9]{64}$/u,lT=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function uT(e,t){return e<t?-1:e>t?1:0}var _i=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Do=Object.freeze({maxCriteria:1024}),Sy="<!-- comet-native:acceptance-evidence:start -->",Ey="<!-- comet-native:acceptance-evidence:end -->";function Py(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 Ry(e,t){let i=t.toString(36),r=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function dT(e){if(!cT.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=lT.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function fT(e,t){let i=Py(e.text,_i.maxTextBytes),r=e.context.slice(0,_i.maxContextItems).map(n=>Py(n,_i.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 xy(e){let t=dT({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(uT),n=r.slice(0,_i.maxFailedCheckIds),a=e.criteria.slice(t,t+_i.maxItems);for(let c of a){let l=[...i,fT(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?Ry(e.acceptanceHash,u):null,limits:{..._i}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>_i.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?Ry(e.acceptanceHash,o):null,limits:{..._i}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>_i.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function vh(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 mh(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 Cy(e){return e.includes("-->")||e.includes("--!>")}function*Jn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
172
+ `)}function I_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||ur.posix.isAbsolute(i)||ur.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 Un(e){let t=I_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ly(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 ol(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||ur.posix.isAbsolute(r)||ur.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 _i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function uy(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 sl(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>nl)throw new Error(`${t} exceeds ${nl} 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>al)throw new Error(`${t} contains more than ${al} wildcard tokens`);return e}function ay(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=>sl(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function ch(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 T_(e){if(e===void 0)return{...Yt,include:[...Yt.include],exclude:[...Yt.exclude]};let t=_i(e,"native.snapshot");return{include:ay(t.include,"native.snapshot.include",Yt.include),exclude:ay(t.exclude,"native.snapshot.exclude",Yt.exclude),max_files:ch(t.max_files,Yt.max_files,"native.snapshot.max_files"),max_total_bytes:ch(t.max_total_bytes,Yt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ch(t.max_duration_ms,Yt.max_duration_ms,"native.snapshot.max_duration_ms")}}function j_(e){if(e===void 0)return;let t=_i(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=_i(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:Un(r),toArtifactRoot:Un(n),stage:a,...o?{cleanup:o}:{}}}function $_(e){if(e===void 0)return;let t=_i(e,"native.finish");if(t.pull_request===void 0)return{};let i=_i(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(ur.posix.isAbsolute(r[0])||ur.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??R_;if(!Number.isSafeInteger(n)||n<1||n>ny)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${ny}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function O_(e,t={}){let i=_i(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??oy;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=j_(i.pending_root_move),c=$_(i.finish);return{artifact_root:Un(r),language:uy(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:T_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function H_(e){let t=_i(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:ly(t.artifact_layout),language:uy(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function D_(e){let i=_i(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)=>ol(r,`hook.allow_paths[${n}]`)))]}}function L_(e){if(e===void 0)return{...rl};let t=_i(e,"memory"),i=t.learning??rl.learning,r=t.retrieval??rl.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function lh(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function M_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||ur.posix.isAbsolute(i)||ur.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>iy)throw new Error(`${t} exceeds ${iy} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>ry)throw new Error(`${t} contains more than ${ry} wildcard tokens`);return i}function F_(e){let i=lh(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>M_(r,`knowledge.local.include[${n}]`)))]}}function B_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function V_(e){let t=lh(e,"knowledge.remote"),i=B_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function q_(e){if(e===void 0)return{...sy};let t=lh(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:F_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:V_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function W_(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function z_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)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 u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Kn(e,t={}){let i=(0,To.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=W_(n.ambient_resume),o=n.hook===void 0?void 0:D_(n.hook),s=L_(n.memory),c=q_(n.knowledge),l=n.native===void 0?void 0:O_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:H_(n.classic),d=z_(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function dy(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 fy(e){let t=e.knowledge??{...sy};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...rl},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...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:dy(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 gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Oo(e,t){let i=fy(t),r=Kn((0,To.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={...gt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=gt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=gt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...gt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...gt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=gt(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=gt(a.finish);o.finish={...s,pull_request:{...gt(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={...gt(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=gt(a.pending_root_move),c=dy(r.native.pending_root_move),l=gt(s.cleanup),u=gt(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={...gt(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 G_}from"crypto";import{promises as ul}from"fs";import dr from"path";import{constants as cl,promises as an}from"fs";var Xt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function uh(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function hy(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ho(e){return{dev:e.dev,ino:e.ino,birthtime:uh(e)}}function ll(e,t){let i=Ho(e),r=Ho(t);return vt(i,r)?z(i,r):z(i,r)&&uh(e)===uh(t)&&hy(e)===hy(t)&&e.size===t.size}async function on(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 an.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Xt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Xt("too-large",`${r} exceeds ${t} bytes`);let o=await an.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Ho(a)});let s=process.platform==="win32"?cl.O_RDONLY:cl.O_RDONLY|cl.O_NOFOLLOW|cl.O_NONBLOCK,c;try{c=await an.open(e,s)}catch(l){throw l.code==="ELOOP"?new Xt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),an.lstat(e,{bigint:n}),an.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ll(a,l)||!ll(a,u))throw new Xt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Ho(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:S}=await c.read(v,0,Math.min(v.length,g),null);if(S===0)break;if(h+=S,h>t)throw new Xt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),an.lstat(e,{bigint:n}),an.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!ll(a,m)||!ll(a,p))throw new Xt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Ho(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function J_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function dh(e,t){let i=dr.relative(e,t);return i===""||!dr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${dr.sep}`)}async function py(e,t){let i=dr.resolve(e),r=await ul.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ul.realpath(i)}async function my(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=dr.join(n,i[a]);let o;try{o=await ul.lstat(n)}catch(u){if(J_(u))return{exists:!1,kind:"missing"};throw u}let s=dr.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 ul.realpath(n);if(!dh(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 Yn(e,t,i){let r=ol(t,i.label),n=dr.resolve(e),a=await py(n,i.label),o=r.split("/"),s=dr.resolve(n,...o);if(!dh(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await my(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function fr(e,t,i,r){let n=await Yn(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 py(n.projectRoot,r.label);return on(n.target,i,{...r,verify:async(o,s)=>{if(!dh(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await my(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var Do=".comet/config.yaml";function fh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function U_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function dl(e,t={}){return(await Lo(e,t)).document}async function vy(e){try{return(await fr(e,Do,jo,{label:Do})).bytes}catch(t){if(U_(t))return null;throw t}}function gy(e){return e?{exists:!0,sha256:G_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fl(e){return gy(await vy(e))}async function Lo(e,t={}){let i=await vy(e);return{document:i?Kn(i.toString("utf8"),t):null,identity:gy(i)}}async function hh(e){return(await dl(e))?.config??null}var pq=16*1024;async function ph(e,t){if(!t)return;let i=await fl(e);if(!fh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as wy,promises as hr}from"fs";import K from"path";import Q_ from"os";var hl=".comet/config.yaml",Z_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function mh(e){try{return await hr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function eI(e){try{let t=await hr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Qn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Xn(e){let t=[],i=e;for(;!await mh(i);){let n=K.dirname(i);if(n===i)break;t.push(K.basename(i)),i=n}let r=await hr.realpath(i);return K.resolve(r,...t.reverse())}async function vh(e){try{return(await hr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gh(e){let t=K.resolve(e);try{(await hr.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=K.resolve(Q_.homedir());for(;;){if(!(t===r&&i!==r)){let o=K.join(t,...hl.split("/")),s=t===i||await eI(o);if(await mh(o)&&s)return t}if(await mh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function pl(e){return Un(e)}async function tI(e,t){let i=pl(t),r=K.resolve(e,...i.split("/")),n=await hr.realpath(e),a=await Xn(r);if(!Qn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function qe(e,t){let i=pl(t),r=await tI(e,i),n=K.join(r,"comet");if(await vh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Xn(r),Xn(n)]);if(!Qn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await vh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([hr.realpath(s),Xn(c)]);if(!Qn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...hl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function Ny(e){if(!Z_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){Ny(t);let i=K.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function sn(e,t){Ny(t);let i=K.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function D(e,t){let i=We(e,t);if(wy(i))return i;let r=sn(e,t);return wy(r)?r:i}async function yy(e){try{let t=await hr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Fo(e,t){let i=We(e,t),r=sn(e,t),[n,a]=await Promise.all([yy(i),yy(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 pr(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=K.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=K.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return Qn(K.resolve(e),K.resolve(t))}async function I(e,t){let i=K.resolve(e),r=K.resolve(t);if(!Qn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await vh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Xn(i),Xn(r)]);if(!Qn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var wh=Yt;var ml=sl;async function ye(e){let t=(await dl(e))?.config??null;return t?.native?t:null}async function Zn(e){let t=await ye(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 mr(e,t,i={}){let r=await Lo(e,{allowPartialProject:!0}),n=Oo(r.document?.value??{},t),a=iI.join(e,...hl.split("/"));await he(a,$o(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ph(e,r.identity)}})}import{promises as QT}from"fs";import ZT from"path";import{AsyncLocalStorage as rI}from"async_hooks";import{randomUUID as Ey}from"crypto";import{promises as xt}from"fs";import Py from"os";import pe from"path";var ky=16*1024,yh=".coordinator",nI=5e3,Sy=new rI,vl=new Map;function aI(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function oI(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 Ry(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 gl(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return vt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function wl(e,t){return gl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function sI(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&&wl(e.identity,t.identity)}async function Qt(e){let t,i;try{let r=await on(e,ky,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Xt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${ky} 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:oI(JSON.parse(t.toString("utf8")),e),identity:Ry(i)}}async function cI(e){return(await Qt(e))?.owner??null}function Nh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Py.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=pI(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function lI(e,t){try{await xt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function yl(e,t){let i=await Qt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!wl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xt.mkdir(t,{recursive:!0});let r=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${Ey()}.removed`);try{await xt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Qt(r);if(!n||n.owner.id!==e.owner.id||!gl(n.identity,e.identity))throw await lI(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xt.rm(r,{force:!0}),"removed"}function Cy(e){return{id:Ey(),pid:process.pid,hostname:Py.hostname(),createdAt:new Date().toISOString(),operation:e}}async function xy(e,t){let i;try{i=await xt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await cI(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let r;try{await i.writeFile(JSON.stringify(t,null,2)+`
173
+ `,"utf8"),await i.sync(),r=Ry(await i.stat({bigint:!0}))}finally{await i.close()}let n=await Qt(e);if(!r||!n||n.owner.id!==t.id||!gl(n.identity,r))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function uI(e,t){let i=await I(e.runtimeDir,e.locksDir);await xt.mkdir(i,{recursive:!0});let r=await I(e.runtimeDir,pe.join(i,yh));await xt.mkdir(r,{recursive:!0});let n=Cy(t),a=pe.join(r,`.${n.id}.tmp`),o=pe.join(r,`${n.id}.claim`);try{let s=await xy(a,n);await xt.rename(a,o);let c=await Qt(o);if(!c||!gl(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 xt.rm(a,{force:!0})}}async function dI(e){let t=pe.dirname(e.file),i=!1,r=pe.basename(e.file);for(let n of await xt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=pe.join(t,n.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await Qt(a),s=Nh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await yl(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function Ay(e){let t=await Qt(e.file);if(t){if(t.owner.id!==e.owner.id||!wl(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await yl(t,pe.dirname(e.file))}}async function fI(e,t){let i=Date.now()+nI;for(;;){let r=await uI(e,t);if(!await dI(r))return r;if(await Ay(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 hI(e){let t=vl.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return vl.set(e,n),await t,()=>{i(),vl.get(e)===n&&vl.delete(e)}}async function Nl(e,t,i){let r=pe.resolve(e.locksDir),n=Sy.getStore();if(n?.has(r))return i();let a=await hI(r);try{let o=await fI(e,t),s=new Map(n??[]);return s.set(r,o),await Sy.run(s,async()=>{try{return await i()}finally{await Ay(o)}})}finally{a()}}async function ea(e,t,i){let r=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?Nl(o,t,()=>n(a+1)):i()};return n(0)}async function vr(e,t,i){return Nl(e,`acquire ${t}`,async()=>{let r=await I(e.runtimeDir,e.locksDir);await xt.mkdir(r,{recursive:!0});let n=await I(e.runtimeDir,pe.join(r,aI(t))),a=Cy(i),o=await xy(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function gr(e){await Qt(e.file)&&await Nl({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${pe.basename(e.file)}`,async()=>{let t=await Qt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!wl(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,yh);await yl(t,i)})}function pI(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function Bo(e){return Nh(await Qt(e))}async function bh(e,t,i){return Nl(e,`take over ${pe.basename(t)}`,async()=>{let r=await I(e.runtimeDir,e.locksDir),n=await I(e.runtimeDir,t);if(pe.resolve(pe.dirname(n))!==pe.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await Qt(n),o=Nh(a);if(o.status==="missing")return{status:"missing"};if(i&&!sI(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(r,yh);return await yl(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as yT}from"node:fs";import Th from"node:path";import nT from"node:path";import Fy from"node:path";import _y from"node:path";import{createHash as mI}from"crypto";function Zt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function vI(e,t){t.has(e)&&Zt("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)||Zt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Zt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Zt("symbol properties are not supported"),`[${e.map(r=>kh(r,t)).join(",")}]`}finally{t.delete(e)}}function gI(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Zt("only plain objects are supported"),t.has(e)&&Zt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Zt("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))&&Zt("accessor properties are not supported"),`${JSON.stringify(o)}:${kh(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function kh(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)||Zt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?vI(e,t):gI(e,t);case"bigint":case"function":case"symbol":case"undefined":return Zt(`${typeof e} values are not supported`)}return Zt("unsupported value type")}function Vo(e){return kh(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return mI("sha256").update(`${e}
174
+ ${Vo(t)}`).digest("hex")}var wI="comet.native.acceptance.v1",yI=/^acceptance-[a-f0-9]{64}$/u,NI=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),bI=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,kI=/^[a-f0-9]{64}$/u,SI=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function EI(e,t){return e<t?-1:e>t?1:0}var Ii=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Wo=Object.freeze({maxCriteria:1024}),Iy="<!-- comet-native:acceptance-evidence:start -->",Ty="<!-- comet-native:acceptance-evidence:end -->";function jy(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 $y(e,t){let i=t.toString(36),r=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function PI(e){if(!kI.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=SI.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function RI(e,t){let i=jy(e.text,Ii.maxTextBytes),r=e.context.slice(0,Ii.maxContextItems).map(n=>jy(n,Ii.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 Hy(e){let t=PI({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(EI),n=r.slice(0,Ii.maxFailedCheckIds),a=e.criteria.slice(t,t+Ii.maxItems);for(let c of a){let l=[...i,RI(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?$y(e.acceptanceHash,u):null,limits:{...Ii}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Ii.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?$y(e.acceptanceHash,o):null,limits:{...Ii}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Ii.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Eh(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 Sh(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 Oy(e){return e.includes("-->")||e.includes("--!>")}function*ta(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
175
175
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
176
- `,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=mh(l,t);else if(i)Cy(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=mh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Cy(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 hT(e){return[...Jn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Ho(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function pT(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function gh(e,t,i,r=[],n="content-hash"){let a=Ho(i),o=t.replaceAll("\\","/").trim(),s=r.map(Ho);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-${D(nT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function wh(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 mT(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Jn(e)){n=s+1;let c=o?vh(a):null;c?.level===1&&(Gs(c.text)==="acceptanceExamples"?(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 dl(e,t="brief.md",i=Do.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=mT(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Jn(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 Jn(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(),wh(o.map(l=>gh("brief-example",t,l.join(`
177
- `),[],r)),"Brief",r)}function fl(e,t="spec.md",i=Do.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(gh("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,r)),o=null}};for(let{line:c,body:l}of Jn(e)){let u=l?vh(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=Ho(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(),wh(n,"Specification",r)}function Ay(e,t="spec.md",i=Do.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(gh("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 Jn(e)){let f=d?vh(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||mh(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(m=>m.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(m=>m.text)},c();continue}s===null?s={parts:[h],context:a.map(m=>m.text)}:s.parts.push(h)}return c(),wh(n,"Specification mandatory requirements",r)}function vT(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||pT(i)||ky.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=ky.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(!sT.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function gT(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=>!oT.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function _y(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=gT(i,r),a=n.acceptance_id;if(typeof a!="string"||!aT.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 vT(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 Ty(e){let t=hT(e);if(t.some(({line:l,body:u})=>!u&&(l===Sy||l===Ey)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Sy?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Ey?[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(`
179
- `).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=_y(o),c=wT(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function wT(e){let t=_y([...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 yT=/^A[1-9]\d*$/u;function jy(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Iy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Iy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function NT(e,t){return e.localeCompare(t,"en")}function hl(e){let t=jy(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>NT(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=dl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=jy(a.source,`Native spec source for ${a.capability}`);r.push(...fl(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=Ho(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 $y(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(!yT.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Oy(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var vl=Rn(Qr(),1);import{promises as bT}from"node:fs";var Gn="comet.native.v4",Lo="comet.native.local-execution.v4";var Hy=["multi-session","single-session"];function yh(){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 kT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ST=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ET=/^A[1-9][0-9]*$/u,PT=/^[a-f0-9]{64}$/u,RT=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ml=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 Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qe(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 _e(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 bh(e,t){return e===null?null:_e(e,t)}function CT(e,t){let i=_e(e,t);if(!PT.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Un(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function me(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 xT(e,t){return e===null?null:me(e,t,Number.MIN_SAFE_INTEGER)}function Se(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ui(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function gl(e,t){return ui(e,t,(i,r)=>_e(i,`${t}[${r}]`))}function rn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Kn(e,t){let i=_e(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function kh(e,t,i=!1){let r=_e(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 At(e,t){let i=Xe(e,t);return Qe(i,new Set(["text","truncated"]),t),{text:_e(i.text,`${t}.text`,{empty:!0}),truncated:Un(i.truncated,`${t}.truncated`)}}function AT(e,t){let i=`Native spec_changes[${t}]`,r=Xe(e,i);Qe(r,new Set(["capability","operation","source"]),i);let n=_e(r.capability,`${i}.capability`);if(!ST.test(n))throw new Error(`${i}.capability is invalid`);let a=Se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:kh(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 _T(e){let t="Native workspace",i=Xe(e,t);Qe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=bh(i.change_branch,`${t}.change_branch`),a=bh(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Se(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 TT(e){let t="Native loop",i=Xe(e,t);Qe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=gl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);rn(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:Se(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:me(i.goal_cycle,`${t}.goal_cycle`,1),iteration:me(i.iteration,`${t}.iteration`),attempt:me(i.attempt,`${t}.attempt`),retry_epoch:me(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:me(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:me(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:me(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:bh(i.next_action,`${t}.next_action`)}}function IT(e,t){let i=`Native acceptance[${t}]`,r=Xe(e,i);Qe(r,new Set(["id","source","text","result","reason"]),i);let n=_e(r.id,`${i}.id`);if(!ET.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:kh(r.source,`${i}.source`),text:_e(r.text,`${i}.text`),result:Se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:At(r.reason,`${i}.reason`)}}function jT(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["name","result","note"]),i),{name:At(r.name,`${i}.name`),result:Se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:At(r.note,`${i}.note`)}}function $T(e){let t="Native builder_handoff",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=gl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);rn(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Xe(i.review,`${t}.review`);return n&&Qe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:_e(i.candidate_id,`${t}.candidate_id`),identity_provider:_e(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:_e(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),summary:At(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ui(i.checks,`${t}.checks`,jT),checks_truncated:Un(i.checks_truncated,`${t}.checks_truncated`),known_limits:ui(i.known_limits,`${t}.known_limits`,(a,o)=>At(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Un(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Se(n.status,["passed"],`${t}.review.status`),summary:At(n.summary,`${t}.review.summary`),reviewer_execution_ref:_e(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Kn(i.submitted_at,`${t}.submitted_at`)}}function OT(e,t){let i=`Native blockers[${t}]`,r=Xe(e,i);Qe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=gl(r.acceptance_ids,`${i}.acceptance_ids`);return rn(n,`${i}.acceptance_ids`),{owner:Se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:At(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Se(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function HT(e,t){let i=`Native verification.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:_e(r.id,`${i}.id`),name:At(r.name,`${i}.name`),argv_display:ui(r.argv_display,`${i}.argv_display`,(n,a)=>At(n,`${i}.argv_display[${a}]`)),argv_truncated:Un(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:kh(r.cwd_ref,`${i}.cwd_ref`,!0),status:Se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:xT(r.exit_code,`${i}.exit_code`),duration_ms:me(r.duration_ms,`${i}.duration_ms`)}}function DT(e){let t="Native verification",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ui(i.checks,`${t}.checks`,HT);rn(r.map(a=>a.id),`${t}.checks IDs`);let n=_e(i.identity_provider,`${t}.identity_provider`);return{candidate_id:_e(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:_e(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),attempt:me(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Se(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Se(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:At(i.summary,`${t}.summary`),risks:ui(i.risks,`${t}.risks`,(a,o)=>At(a,`${t}.risks[${o}]`)),risks_truncated:Un(i.risks_truncated,`${t}.risks_truncated`),completed_at:Kn(i.completed_at,`${t}.completed_at`)}}function Dy(e,t){let i=`Native history[${t}]`,r=Xe(e,i);Qe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=gl(r.unresolved_ids,`${i}.unresolved_ids`);return rn(n,`${i}.unresolved_ids`),{goal_cycle:me(r.goal_cycle,`${i}.goal_cycle`,1),iteration:me(r.iteration,`${i}.iteration`),attempt:me(r.attempt,`${i}.attempt`),outcome:Se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:At(r.summary,`${i}.summary`),completed_at:Kn(r.completed_at,`${i}.completed_at`)}}function LT(e){let t="Native history_overflow.outcome_counts",i=Xe(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Qe(i,new Set(r),t),{pass:me(i.pass,`${t}.pass`),fail:me(i.fail,`${t}.fail`),blocked:me(i.blocked,`${t}.blocked`),"execution-error":me(i["execution-error"],`${t}.execution-error`),recovery:me(i.recovery,`${t}.recovery`)}}function MT(e){let t="Native history_overflow",i=Xe(e,t);Qe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=me(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Kn(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Kn(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=LT(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 FT(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){if(!(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.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}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 BT(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 ct(e){let t=Xe(e,"Native portable state");if(Qe(t,RT,"Native portable state"),t.schema!==Gn)throw new Error(`Native portable state schema must be ${Gn}`);let i=_e(t.name,"Native state name");if(!kT.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=ui(t.spec_changes,"Native spec_changes",AT);rn(r.map(s=>s.capability),"Native spec change capabilities");let n=ui(t.acceptance,"Native acceptance",IT);rn(n.map(s=>s.id),"Native acceptance IDs");let a=ui(t.history,"Native history",Dy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Gn,name:i,language:Se(t.language,["en","zh-CN"],"Native state language"),phase:Se(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Se(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:me(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:CT(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Se(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:_T(t.workspace),loop:TT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:$T(t.builder_handoff),blockers:ui(t.blockers,"Native blockers",OT),verification:t.verification===null?null:DT(t.verification),history:a,history_overflow:MT(t.history_overflow),verification_result:Se(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Se(t.verification_report,["verification.md"],"Native verification_report"),archived:Un(t.archived,"Native archived"),created_at:Kn(t.created_at,"Native created_at")};return FT(o),BT(o),o}function Yn(e,t){let i=ct(e),r=Dy(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 ct({...i,history:n,history_overflow:a})}function VT(e,t){let i=(0,vl.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 Ze(e){let t=await bT.readFile(e,"utf8");return ct(VT(t,"Native portable state"))}async function wl(e,t,i={}){let r=ct(t);await he(e,(0,vl.stringify)(r),i)}var pl=new Map;async function qT(e,t){let i=pl.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);pl.set(e,a),await i;try{return await t()}finally{r(),pl.get(e)===a&&pl.delete(e)}}async function nn(e){return qT(e.file,async()=>{let t=me(e.expectedStateVersion,"Native expected state version",1),i=ct(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ze(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new ml(t,r.state_version);return await wl(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ze(e.file);if(n.state_version!==t)throw new ml(t,n.state_version)}}),i})}function WT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function hr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(WT(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 Ne="comet.native.v3",be="comet.native.v2",et="comet.native.v1",pr="comet.native.transition.v3",Ti="comet.native.transition.v2",an="comet.native.transition.v1";var yl="comet.native.portable-migration.v1",JT=new Set(["schema","id","change","fromSchema","status","createdAt"]),GT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,UT=/^[a-z0-9][a-z0-9-]{7,127}$/u,KT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),YT=new Set([et,be,Ne]);function XT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function QT(e,t){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 ZT(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 eI(e){return e.schema===et?on(e):e.schema===be?di(e):lt(e)}function tI(e){return zT.posix.normalize(e.replaceAll("\\","/"))}function iI(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:tI(t.source)})}function rI(e){return e==="shape"?"shape":"build"}function nI(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function aI(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 Ly(e){let t=eI(e.state);$y(e.acceptance);let i=rI(t.phase),r=i==="shape"?0:1,n=QT(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 ct({schema:Gn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:iI(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:nI(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:hr(aI(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:yh(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Sh(e){let t=XT(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!JT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==yl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!UT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!GT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!YT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!KT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:ZT(t.createdAt,"Native portable migration transaction createdAt")}}function My(e){switch(Sh(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 Nl="comet.native.archive-transaction.v4",Fy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",sI=new RegExp(`^portable-archive-(${Fy})\\.json$`,"u"),cI=new RegExp(`^portable-migration-(${Fy})\\.json$`,"u"),lI=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uI=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dI=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),fI=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),hI=new Set(["capability","operation","source","content"]),By=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Vy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qy(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 pI(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Vy(e,i);if(qy(r,hI,i),typeof r.capability!="string"||!By.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 mI(e){let t=Vy(e,"Native portable Archive transaction");if(qy(t,fI,"Native portable Archive transaction"),t.schema!==Nl)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!lI.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!By.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"||!uI.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"||!dI.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(pI);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:Nl,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 sn(e){let t=sI.exec(e);if(t)return{kind:"archive",change:t[1]};let i=cI.exec(e);return i?{kind:"migration",change:i[1]}:null}function mr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=sn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Eh.join(e.transactionsDir,i)}async function Mo(e,t){let i=sn(t);if(!i)return null;let r=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Eh.join(e.transactionsDir,t);if(i.kind==="archive"){let s=mI(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=Sh(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 bl(e,t){let i=mr(e,t);try{return await Mo(e,Eh.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Wy(e){let t;try{t=await oI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>sn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function zy(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Fo}from"fs";import _t from"path";import{TextDecoder as NI}from"util";import{createHash as vI}from"node:crypto";import{constants as kl,promises as W}from"node:fs";import Y from"node:path";import{TextDecoder as gI}from"node:util";function ze(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function Jy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Qn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Xn(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 vr(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 gr(e,t,i){let r=Y.resolve(e),n=Y.resolve(t);if(!ze(r,n))throw new Error(`${i} is outside its managed root`);let a=[await vr(r,i)],o=r;for(let s of Y.relative(r,n).split(Y.sep).filter(Boolean)){await we(a,i),o=Y.join(o,s);let c=await vr(o,i);if(!ze(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Qn(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function wI(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 re(e){let t=Jy(e.maxBytes),i=Y.resolve(e.file),r=await gr(e.root,Y.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>vr(Y.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(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=Gy(a),s=await W.realpath(i);if(!ze(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ze(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?kl.O_RDONLY:kl.O_RDONLY|kl.O_NOFOLLOW|kl.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 we(r,e.label),await we(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Xn(o,u)||!Xn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await wI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!Xn(o,v)||!Xn(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:vI("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Sl(e){let t=await re(e),i;try{i=new gI("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 wt(e){let t=await gr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=Jy(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 we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function Qt(e){let t=await gr(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function yI(e){let t=Y.resolve(e.directory),i=Y.resolve(e.quarantine);if(Y.dirname(i)!==Y.dirname(t)||!ze(Y.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await gr(e.root,Y.dirname(t),e.label),n=await vr(t,e.label);if(!ze(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Qn(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 we(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Qn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await 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 Uy(e){await yI(e)}async function El(e){let t=Y.resolve(e.file),i=await gr(e.root,Y.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=Gy(r),a=await W.realpath(t);if(!ze(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({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()||!Xn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Xn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function Ph(e){let t=Y.resolve(e.directory),i=await gr(e.root,Y.dirname(t),e.label),r=await vr(t,e.label);if(!ze(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Qn(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function fi(e){let t=Y.resolve(e.root),i=Y.resolve(e.directory);if(!ze(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await vr(t,e.label)],n=t;for(let a of Y.relative(t,i).split(Y.sep).filter(Boolean)){await we(r,e.label),n=Y.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await vr(n,e.label);if(!ze(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await we(r,e.label)}async function Rh(e){let t=Y.resolve(e.root),i=Y.resolve(e.source),r=Y.resolve(e.target);if(i===r||!ze(t,i)||!ze(t,r)||ze(i,r)||ze(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await fi({root:t,directory:Y.dirname(r),label:`${e.label} target parent`});let n=await gr(t,Y.dirname(i),e.label),a=await gr(t,Y.dirname(r),e.label),o=await vr(i,e.label);if(!ze(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([we(n,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Qn(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([we(n,e.label),we(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Qn(o,c)||!ze(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 wr(e){let t=await re({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 Gw(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 re({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 re({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 bI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),kI=new Set(["id","type","source","target","staged","backup"]),SI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),EI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),PI=new Set(["sequence","timestamp","type","operationId"]),Qy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Zy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),RI=256*1024,CI=1024*1024,eN=16*1024,Rl=1024,Ah=64*1024*1024,xI=2e4,tN=new NI("utf-8",{fatal:!0});function Bo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vo(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 ea(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ch(e,t){if(typeof e!="string"||e.length===0||_t.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Pl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Ky(e,t){if(Ch(e,t),e.includes("\\")||e!==_t.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 AI(e,t){let i=Bo(e,`transaction operations[${t}]`);if(Vo(i,kI,`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`);Ch(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ch(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 xl(e){let t=Bo(e,"Native Archive transaction journal");if(Vo(t,SI,"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"||!Qy.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(!ea(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Pl(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=Bo(s,`Archive transaction operations[${c}]`);if(Vo(l,EI,`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`);Ky(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Ky(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Pl(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(Pl(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`);Pl(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 _h(e){let t=Bo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return xl(t);if(Vo(t,bI,"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"||!Qy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!_t.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!_t.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(!ea(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(AI),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 iN(e,t){let i=Bo(e,`Native transaction event at line ${t}`);if(Vo(i,PI,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!ea(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Zy.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 _I(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&&!ea(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||ea(e)}function Zn(e,t){return e.length<t.length&&t.startsWith(e)}function TI(e){let t='","operationId":"';if(Zn(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)?Zn(i.slice(r),'"}'):!1}function II(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>eN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Zn(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(!_I(n))return!1;if(r.length<24)return!0;if(!ea(n))return!1;let a='","type":"',o=r.slice(24);if(Zn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Zy){if(Zn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(TI(l))return!0}else if(Zn(l,'"}'))return!0}return!1}function jI(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>eN)throw new Error(`Native transaction event at line ${t} is too large`);return iN(JSON.parse(e),t)}function $I(e){let t=e.split(`
180
- `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Rl)throw new Error(`Native transaction event log exceeds ${Rl} 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(jI(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&II(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function rN(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
176
+ `,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=Sh(l,t);else if(i)Oy(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Sh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Oy(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 CI(e){return[...ta(e)].map(({line:t,body:i})=>({line:t,body:i}))}function qo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function xI(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Ph(e,t,i,r=[],n="content-hash"){let a=qo(i),o=t.replaceAll("\\","/").trim(),s=r.map(qo);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-${H(wI,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Rh(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 AI(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of ta(e)){n=s+1;let c=o?Eh(a):null;c?.level===1&&(ec(c.text)==="acceptanceExamples"?(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 bl(e,t="brief.md",i=Wo.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=AI(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ta(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 ta(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(),Rh(o.map(l=>Ph("brief-example",t,l.join(`
177
+ `),[],r)),"Brief",r)}function kl(e,t="spec.md",i=Wo.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(Ph("spec-scenario",t,[o.title,...o.body].join(`
178
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of ta(e)){let u=l?Eh(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=qo(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(),Rh(n,"Specification",r)}function Dy(e,t="spec.md",i=Wo.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(Ph("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 ta(e)){let f=d?Eh(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||Sh(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(m=>m.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(m=>m.text)},c();continue}s===null?s={parts:[h],context:a.map(m=>m.text)}:s.parts.push(h)}return c(),Rh(n,"Specification mandatory requirements",r)}function _I(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||xI(i)||_y.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=_y.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(!bI.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function II(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=>!NI.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function Ly(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=II(i,r),a=n.acceptance_id;if(typeof a!="string"||!yI.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 _I(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 My(e){let t=CI(e);if(t.some(({line:l,body:u})=>!u&&(l===Iy||l===Ty)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Iy?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Ty?[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(`
179
+ `).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=Ly(o),c=TI(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function TI(e){let t=Ly([...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 jI=/^A[1-9]\d*$/u;function By(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Fy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Fy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function $I(e,t){return e.localeCompare(t,"en")}function Sl(e){let t=By(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>$I(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=bl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=By(a.source,`Native spec source for ${a.capability}`);r.push(...kl(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=qo(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 Vy(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(!jI.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function qy(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var Rl=$n(nn(),1);import{promises as OI}from"node:fs";var ia="comet.native.v4",zo="comet.native.local-execution.v4";var Wy=["multi-session","single-session"];function Ch(){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 HI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LI=/^A[1-9][0-9]*$/u,MI=/^[a-f0-9]{64}$/u,FI=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Pl=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 Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qe(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 Ie(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 Ah(e,t){return e===null?null:Ie(e,t)}function zy(e,t){let i=Ie(e,t);if(!MI.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function ra(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function me(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 BI(e,t){return e===null?null:me(e,t,Number.MIN_SAFE_INTEGER)}function Se(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function di(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Cl(e,t){return di(e,t,(i,r)=>Ie(i,`${t}[${r}]`))}function cn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function na(e,t){let i=Ie(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function _h(e,t,i=!1){let r=Ie(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 At(e,t){let i=Xe(e,t);return Qe(i,new Set(["text","truncated"]),t),{text:Ie(i.text,`${t}.text`,{empty:!0}),truncated:ra(i.truncated,`${t}.truncated`)}}function VI(e,t){let i=`Native spec_changes[${t}]`,r=Xe(e,i);Qe(r,new Set(["capability","operation","source"]),i);let n=Ie(r.capability,`${i}.capability`);if(!DI.test(n))throw new Error(`${i}.capability is invalid`);let a=Se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:_h(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 qI(e){let t="Native workspace",i=Xe(e,t);Qe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Ah(i.change_branch,`${t}.change_branch`),a=Ah(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Se(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 WI(e){let t="Native loop",i=Xe(e,t);Qe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Cl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);cn(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:Se(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:me(i.goal_cycle,`${t}.goal_cycle`,1),iteration:me(i.iteration,`${t}.iteration`),attempt:me(i.attempt,`${t}.attempt`),retry_epoch:me(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:me(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:me(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:me(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Ah(i.next_action,`${t}.next_action`)}}function zI(e,t){let i=`Native acceptance[${t}]`,r=Xe(e,i);Qe(r,new Set(["id","source","text","result","reason"]),i);let n=Ie(r.id,`${i}.id`);if(!LI.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:_h(r.source,`${i}.source`),text:Ie(r.text,`${i}.text`),result:Se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:At(r.reason,`${i}.reason`)}}function JI(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["name","result","note"]),i),{name:At(r.name,`${i}.name`),result:Se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:At(r.note,`${i}.note`)}}function GI(e){let t="Native builder_handoff",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=Cl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);cn(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Xe(i.review,`${t}.review`);return n&&Qe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Ie(i.candidate_id,`${t}.candidate_id`),identity_provider:Ie(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Ie(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),summary:At(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:di(i.checks,`${t}.checks`,JI),checks_truncated:ra(i.checks_truncated,`${t}.checks_truncated`),known_limits:di(i.known_limits,`${t}.known_limits`,(a,o)=>At(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ra(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Se(n.status,["passed"],`${t}.review.status`),summary:At(n.summary,`${t}.review.summary`),reviewer_execution_ref:Ie(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:na(i.submitted_at,`${t}.submitted_at`)}}function UI(e,t){let i=`Native blockers[${t}]`,r=Xe(e,i);Qe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Cl(r.acceptance_ids,`${i}.acceptance_ids`);return cn(n,`${i}.acceptance_ids`),{owner:Se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:At(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Se(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function KI(e,t){let i=`Native verification.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Ie(r.id,`${i}.id`),name:At(r.name,`${i}.name`),argv_display:di(r.argv_display,`${i}.argv_display`,(n,a)=>At(n,`${i}.argv_display[${a}]`)),argv_truncated:ra(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:_h(r.cwd_ref,`${i}.cwd_ref`,!0),status:Se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:BI(r.exit_code,`${i}.exit_code`),duration_ms:me(r.duration_ms,`${i}.duration_ms`)}}function YI(e){let t="Native verification",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=di(i.checks,`${t}.checks`,KI);cn(r.map(a=>a.id),`${t}.checks IDs`);let n=Ie(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Ie(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Ie(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),attempt:me(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Se(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Se(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:At(i.summary,`${t}.summary`),risks:di(i.risks,`${t}.risks`,(a,o)=>At(a,`${t}.risks[${o}]`)),risks_truncated:ra(i.risks_truncated,`${t}.risks_truncated`),completed_at:na(i.completed_at,`${t}.completed_at`)}}function Jy(e,t){let i=`Native history[${t}]`,r=Xe(e,i);Qe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Cl(r.unresolved_ids,`${i}.unresolved_ids`);return cn(n,`${i}.unresolved_ids`),{goal_cycle:me(r.goal_cycle,`${i}.goal_cycle`,1),iteration:me(r.iteration,`${i}.iteration`),attempt:me(r.attempt,`${i}.attempt`),outcome:Se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:At(r.summary,`${i}.summary`),completed_at:na(r.completed_at,`${i}.completed_at`)}}function XI(e){let t="Native history_overflow.outcome_counts",i=Xe(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Qe(i,new Set(r),t),{pass:me(i.pass,`${t}.pass`),fail:me(i.fail,`${t}.fail`),blocked:me(i.blocked,`${t}.blocked`),"execution-error":me(i["execution-error"],`${t}.execution-error`),recovery:me(i.recovery,`${t}.recovery`)}}function QI(e){let t="Native history_overflow",i=Xe(e,t);Qe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=me(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:na(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:na(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=XI(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 ZI(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){if(!(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.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}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 eT(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 ct(e){let t=Xe(e,"Native portable state");if(Qe(t,FI,"Native portable state"),t.schema!==ia)throw new Error(`Native portable state schema must be ${ia}`);let i=Ie(t.name,"Native state name");if(!HI.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=di(t.spec_changes,"Native spec_changes",VI);cn(r.map(s=>s.capability),"Native spec change capabilities");let n=di(t.acceptance,"Native acceptance",zI);cn(n.map(s=>s.id),"Native acceptance IDs");let a=di(t.history,"Native history",Jy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ia,name:i,language:Se(t.language,["en","zh-CN"],"Native state language"),phase:Se(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Se(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:me(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:zy(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:zy(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Se(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:qI(t.workspace),loop:WI(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:GI(t.builder_handoff),blockers:di(t.blockers,"Native blockers",UI),verification:t.verification===null?null:YI(t.verification),history:a,history_overflow:QI(t.history_overflow),verification_result:Se(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Se(t.verification_report,["verification.md"],"Native verification_report"),archived:ra(t.archived,"Native archived"),created_at:na(t.created_at,"Native created_at")};return ZI(o),eT(o),o}function ln(e,t){let i=ct(e),r=Jy(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 ct({...i,history:n,history_overflow:a})}function tT(e,t){let i=(0,Rl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ze(e){let t=await OI.readFile(e,"utf8");return ct(tT(t,"Native portable state"))}async function xl(e,t,i={}){let r=ct(t);await he(e,(0,Rl.stringify)(r),i)}var El=new Map;async function iT(e,t){let i=El.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);El.set(e,a),await i;try{return await t()}finally{r(),El.get(e)===a&&El.delete(e)}}async function un(e){return iT(e.file,async()=>{let t=me(e.expectedStateVersion,"Native expected state version",1),i=ct(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ze(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new Pl(t,r.state_version);return await xl(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ze(e.file);if(n.state_version!==t)throw new Pl(t,n.state_version)}}),i})}function rT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Ti(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(rT(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 Ne="comet.native.v3",be="comet.native.v2",et="comet.native.v1",wr="comet.native.transition.v3",ji="comet.native.transition.v2",dn="comet.native.transition.v1";var Al="comet.native.portable-migration.v1",aT=new Set(["schema","id","change","fromSchema","status","createdAt"]),oT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sT=/^[a-z0-9][a-z0-9-]{7,127}$/u,cT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),lT=new Set([et,be,Ne]);function uT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function dT(e,t){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 fT(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 hT(e){return e.schema===et?fn(e):e.schema===be?fi(e):lt(e)}function pT(e){return nT.posix.normalize(e.replaceAll("\\","/"))}function mT(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:pT(t.source)})}function vT(e){return e==="shape"?"shape":"build"}function gT(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function wT(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 Gy(e){let t=hT(e.state);Vy(e.acceptance);let i=vT(t.phase),r=i==="shape"?0:1,n=dT(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 ct({schema:ia,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:mT(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:gT(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:Ti(wT(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Ch(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ih(e){let t=uT(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!aT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Al)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!sT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!oT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!lT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!cT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Al,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:fT(t.createdAt,"Native portable migration transaction createdAt")}}function Uy(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 _l="comet.native.archive-transaction.v4",Ky="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",NT=new RegExp(`^portable-archive-(${Ky})\\.json$`,"u"),bT=new RegExp(`^portable-migration-(${Ky})\\.json$`,"u"),kT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ST=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ET=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),PT=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),RT=new Set(["capability","operation","source","content"]),Yy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Xy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qy(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 CT(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Xy(e,i);if(Qy(r,RT,i),typeof r.capability!="string"||!Yy.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 xT(e){let t=Xy(e,"Native portable Archive transaction");if(Qy(t,PT,"Native portable Archive transaction"),t.schema!==_l)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!kT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Yy.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"||!ST.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"||!ET.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(CT);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:_l,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 hn(e){let t=NT.exec(e);if(t)return{kind:"archive",change:t[1]};let i=bT.exec(e);return i?{kind:"migration",change:i[1]}:null}function yr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=hn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Th.join(e.transactionsDir,i)}async function Jo(e,t){let i=hn(t);if(!i)return null;let r=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Th.join(e.transactionsDir,t);if(i.kind==="archive"){let s=xT(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 aa(e,t){let i=yr(e,t);try{return await Jo(e,Th.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Zy(e){let t;try{t=await yT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>hn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function eN(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Go}from"fs";import _t from"path";import{TextDecoder as jT}from"util";import{createHash as AT}from"node:crypto";import{constants as Il,promises as W}from"node:fs";import Y from"node:path";import{TextDecoder as _T}from"node:util";function ze(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function tN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function sa(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function iN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function oa(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 Nr(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 br(e,t,i){let r=Y.resolve(e),n=Y.resolve(t);if(!ze(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Nr(r,i)],o=r;for(let s of Y.relative(r,n).split(Y.sep).filter(Boolean)){await we(a,i),o=Y.join(o,s);let c=await Nr(o,i);if(!ze(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!sa(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function IT(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 re(e){let t=tN(e.maxBytes),i=Y.resolve(e.file),r=await br(e.root,Y.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Nr(Y.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(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=iN(a),s=await W.realpath(i);if(!ze(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ze(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Il.O_RDONLY:Il.O_RDONLY|Il.O_NOFOLLOW|Il.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 we(r,e.label),await we(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!oa(o,u)||!oa(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await IT(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!oa(o,v)||!oa(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:AT("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Tl(e){let t=await re(e),i;try{i=new _T("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 wt(e){let t=await br(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=tN(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 we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function ei(e){let t=await br(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function TT(e){let t=Y.resolve(e.directory),i=Y.resolve(e.quarantine);if(Y.dirname(i)!==Y.dirname(t)||!ze(Y.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await br(e.root,Y.dirname(t),e.label),n=await Nr(t,e.label);if(!ze(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!sa(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 we(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!sa(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 rN(e){await TT(e)}async function jl(e){let t=Y.resolve(e.file),i=await br(e.root,Y.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=iN(r),a=await W.realpath(t);if(!ze(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({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()||!oa(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!oa(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function jh(e){let t=Y.resolve(e.directory),i=await br(e.root,Y.dirname(t),e.label),r=await Nr(t,e.label);if(!ze(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!sa(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function hi(e){let t=Y.resolve(e.root),i=Y.resolve(e.directory);if(!ze(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 Y.relative(t,i).split(Y.sep).filter(Boolean)){await we(r,e.label),n=Y.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Nr(n,e.label);if(!ze(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await we(r,e.label)}async function $h(e){let t=Y.resolve(e.root),i=Y.resolve(e.source),r=Y.resolve(e.target);if(i===r||!ze(t,i)||!ze(t,r)||ze(i,r)||ze(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await hi({root:t,directory:Y.dirname(r),label:`${e.label} target parent`});let n=await br(t,Y.dirname(i),e.label),a=await br(t,Y.dirname(r),e.label),o=await Nr(i,e.label);if(!ze(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([we(n,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!sa(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([we(n,e.label),we(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!sa(o,c)||!ze(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 kr(e){let t=await re({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 ty(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 re({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 re({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 $T=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),OT=new Set(["id","type","source","target","staged","backup"]),HT=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),DT=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),LT=new Set(["sequence","timestamp","type","operationId"]),sN=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),cN=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),MT=256*1024,FT=1024*1024,lN=16*1024,Ol=1024,Dh=64*1024*1024,BT=2e4,uN=new jT("utf-8",{fatal:!0});function Uo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ko(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function la(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||_t.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function $l(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function nN(e,t){if(Oh(e,t),e.includes("\\")||e!==_t.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 VT(e,t){let i=Uo(e,`transaction operations[${t}]`);if(Ko(i,OT,`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 Dl(e){let t=Uo(e,"Native Archive transaction journal");if(Ko(t,HT,"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"||!sN.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(!la(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if($l(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=Uo(s,`Archive transaction operations[${c}]`);if(Ko(l,DT,`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`);nN(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&nN(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&$l(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($l(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`);$l(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=Uo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Dl(t);if(Ko(t,$T,"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"||!sN.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!_t.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!_t.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(!la(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(VT),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 dN(e,t){let i=Uo(e,`Native transaction event at line ${t}`);if(Ko(i,LT,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!la(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!cN.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 qT(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&&!la(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||la(e)}function ca(e,t){return e.length<t.length&&t.startsWith(e)}function WT(e){let t='","operationId":"';if(ca(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)?ca(i.slice(r),'"}'):!1}function zT(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>lN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(ca(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(!qT(n))return!1;if(r.length<24)return!0;if(!la(n))return!1;let a='","type":"',o=r.slice(24);if(ca(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of cN){if(ca(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(WT(l))return!0}else if(ca(l,'"}'))return!0}return!1}function JT(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>lN)throw new Error(`Native transaction event at line ${t} is too large`);return dN(JSON.parse(e),t)}function GT(e){let t=e.split(`
180
+ `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Ol)throw new Error(`Native transaction event log exceeds ${Ol} 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(JT(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&zT(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function fN(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
181
181
  `)}
182
- `}function OI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return _t.join(e.transactionsDir,t)}function Al(e,t){let i=OI(e,t);return{directory:i,journal:_t.join(i,"transaction.json"),events:_t.join(i,"events.jsonl"),staged:_t.join(i,"staged"),backups:_t.join(i,"backups")}}async function hi(e,t){let i=Al(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function HI(e,t){if(t.length===0||_t.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=_t.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function yr(e,t){let i=HI(e,t);return T(j(e,i),i)}async function cn(e){try{return await Fo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Th(e,t,i={}){let r=await hi(e,t);try{await Fo.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 re({root:e.runtimeDir,file:r.events,maxBytes:CI,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=tN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=$I(a),s=rN(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 Yy(e,t,i){let r=await Th(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 Tt(e,t,i,r){let n=await hi(e,t),a=await Th(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await he(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>Yy(e,t,a)}),o;if(a.events.length>=Rl)throw new Error(`Native transaction event log ${t} exceeds ${Rl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return iN(s,s.sequence),await Fo.mkdir(n.directory,{recursive:!0}),await he(n.events,rN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>Yy(e,t,a)}),s}async function nN(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=_h(t);let i=await hi(e,t.id);await Fo.mkdir(i.staged,{recursive:!0}),await Fo.mkdir(i.backups,{recursive:!0}),await ee(i.journal,t,{containedRoot:e.runtimeDir}),await Tt(e,t.id,"prepared")}async function yt(e,t,i={}){let r=await hi(e,t),n=await re({root:e.runtimeDir,file:r.journal,maxBytes:RI,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(tN.decode(n.bytes)),o=_h(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Nr(e,t,i={}){return(await Th(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=_h({...t,status:i});return await ee((await hi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function xh(e,t,i){try{return await re({root:j(e,t),file:t,maxBytes:Ah,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ih(e,t,i,r){let n=await xh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await xh(e,i,`${r} target`);await fi({root:j(e,i),directory:_t.dirname(i),label:`${r} target parent`}),await wr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Ah,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function aN(e,t,i){let r=await xh(e,t,i);r&&await El({root:j(e,t),file:t,maxBytes:Ah,expectedHash:r.hash,expectedSize:r.size,label:i})}async function Xy(e,t){if(!t.backup)return;let i=await yr(e,t.target),r=await yr(e,t.backup);!await cn(i)||await cn(r)||await Ih(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function DI(e,t){let i=await yr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Xy(e,t),await Ih(e,await yr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Xy(e,t),await aN(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 yr(e,t.source),[n,a]=await Promise.all([cn(r),cn(i)]);if(!n&&a){await(await wt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:xI})).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 Rh({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function oN(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 Nr(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 Tt(e,r.id,"operation-started",s.id),await DI(e,s),await Tt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await yt(e,r.id),r}async function LI(e,t){let i=await yr(e,t.target),r=t.backup?await yr(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 yr(e,t.source);if(await cn(i)){if(await cn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Rh({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await cn(r)?await Ih(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await aN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function _l(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 Nr(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 Tt(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 LI(e,a);return await Tt(e,r.id,"rollback-completed"),r=await Cl(e,r,"rolled-back"),r}async function ta(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 Tt(e,t.id,i),i==="commit"?Cl(e,t,"committed"):t}async function BI(e,t,i){let r;try{r=await MI.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 yt(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(sn(n.name))try{let a=await Mo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(zy(a))return!0}catch{return!0}return!1}async function VI(e,t){let i=Date.now()+5e3,r=FI.join(e.locksDir,"root-move.lock");for(;;)try{return await dr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await $o(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 se(e,t,i,r){let n=await VI(e,t);try{if(await Wn(e.projectRoot),await BI(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fr(n)}}function sN(e){return Number.isSafeInteger(e)&&e>=1}async function cN(e){if(!sN(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(!sN(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 Ol}from"crypto";import{spawn as wN}from"node:child_process";import{promises as ce}from"fs";import V from"path";import{createHash as lN}from"crypto";import{createReadStream as qI}from"fs";async function Zt(e){let t=lN("sha256");for await(let i of qI(e))t.update(i);return t.digest("hex")}function L(e){return lN("sha256").update(e).digest("hex")}var Tl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Lh=1e3,WI=8*1024*1024,zI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),GI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),UI=new Set(["schema","include","exclude","hash"]),KI=new Set(["provider","gitSelection","physicalSelection","projection"]),YI=new Set(["provider","selection"]),XI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),QI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),ZI=new Set(["schema","status","before","after"]),ej=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),tj=new Set(["path","hash","size","type","gitObjectId"]),ij=new Set(["path","size","type","reason"]),rj=new Set(["ref","hash","count"]),nj=new Set(["change-created","legacy-migration","explicit"]),aj=new Set(["file","directory","other"]),oj=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"]),Hl=/^[a-f0-9]{64}$/u,yN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sj=new Set(["EACCES","EPERM"]),oa=64*1024,Hh=64*1024,cj=6e4,lj=1e3,uj=2,Mh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},dj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function NN(e){let t=e.deadlineMs??cj;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 ei(e){return Math.max(0,e.deadlineAt-Date.now())}function M(e){return ei(e)>=1}function jh(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 na(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function fj(e){let t={...dj,...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 hj(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&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=wN(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),lj),u.unref()}catch{d(!1)}});for(let s=0;s<uj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Fh(e,t,i,r){let n=ei(e);if(n<1)throw jh();let a=e.gitProcess,o=wN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,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=hj(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?jh(v.error):jh()}return{code:h,spawnError:s}});return{child:o,completion:f}}function bN(e){let t={...Mh,...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 Il(e,t,i,r=Hh){let{child:n,completion:a}=Fh(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>=oa)return;let v=oa-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.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 $h(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Wo(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Fh(e,t,i,r.stdin!==void 0),c=[],l=Ol("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,y=E=>{let k=0;for(;k<E.byteLength;){let S=E.indexOf(0,k),R=S<0?E.byteLength:S,N=E.subarray(k,R);if(!p&&N.byteLength>0&&(m.byteLength+N.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,N])),S<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=S+1}};o.stdout.on("data",E=>{l.update(E),f+=E.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){y(E);return}for(let S=0;S<E.byteLength;S+=k)y(E.subarray(S,Math.min(E.byteLength,S+k)))}),o.stderr.on("data",E=>{if(d>=oa)return;let k=oa-d,S=Buffer.from(E).subarray(0,k);u.push(S),d+=S.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:E,spawnError:k})=>{let S=r.acceptedExitCodes??[0];if(E!==null&&S.includes(E)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function jl(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 pj(e,t,i){if(i.length===0)return new Set;let r=await Wo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Mh,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=jl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function mj(e,t,i){let{child:r,completion:n}=Fh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=oa)return;let d=oa-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 aa(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function vj(e,t){return e.map(i=>{let r=aa(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function gj(e){let t=V.resolve(e);for(;;){try{return await ce.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function kN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=aa(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 Wo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Wo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Wo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function SN(e){return{stageBefore:$h(e.stagedBefore),combined:$h(e.combined),stageAfter:$h(e.stagedAfter)}}async function EN(e,t,i=Mh,r={}){let n=V.resolve(t.projectRoot);if(!await gj(n))return null;let a;try{a=await Il(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw na(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}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 kN(e,t,i,r)}catch(g){throw na(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let y of g){let E=jl(y),k=E.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(E.slice(0,k))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=aa(E.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),S.stage==="0"&&d.set(R,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(jl),m=vj(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,y)=>!u.has(g)&&v[y].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:SN(o)}}function kr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function uN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function wj(e,t){return!kr(e.stageBefore,e.stageAfter)||!kr(e.stageAfter,t.stageBefore)||!kr(e.combined,t.combined)||!kr(t.stageBefore,t.stageAfter)}async function PN(e,t,i,r,n){let a;try{a=await kN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw na(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=SN(a),c=uN(o)||uN(s),l=wj(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:L(`comet.native.git-selection-overflow.v2
183
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var yj=(1n<<256n)-1n;function Nj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function dN(e){let t=V.resolve(e.paths.projectRoot),i=V.resolve(e.paths.nativeRoot),r=V.resolve(e.paths.runtimeDir),n=V.resolve(e.paths.configFile),a=V.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,m=!1,p=()=>ei(e.execution)>=1?!0:(h=!0,m=!0,!1),b=E=>{let k=Buffer.from(`${E.type}\0${E.path}`,"utf8"),S=Ol("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=S[R];if(l=l+BigInt(`0x${S.toString("hex")}`)&yj,d+=1,f+=k.byteLength,Buffer.byteLength(E.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,m=!0;return}o.push(E)},g=async E=>{if(m||!p())return;let k;try{k=await ce.opendir(E)}catch(P){if(!p())return;if(!Pe(P)&&!Ee(P)||E===t&&Pe(P))throw P;v||=Ee(P),h||=Pe(P),m=!0;return}if(!p()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let S=!1,R;try{for(;!m&&p();){let P;try{P=await k.read()}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te)||E===t&&Pe(te))throw te;v||=Ee(te),h||=Pe(te),m=!0;break}if(!p()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,m=!0;break}let F=V.join(E,P.name),$=kj(t,F);if(F===n||F===a||ti(i,F)||ti(r,F)||e.denylist.some(te=>ti(te,F))||ci($)!==null)continue;if(!p())break;let Fe;try{Fe=await ce.lstat(F)}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te))throw te;if(v=!0,b({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:Pe(te)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;let ue=Nj(Fe);if(ue==="directory"){if(Rj(e.policy,$))continue;if(!p())break;let te;try{te=await ce.realpath(F)}catch(ai){if(!p())break;if(!Pe(ai)&&!Ee(ai))throw ai;if(v=!0,b({path:$,type:ue}),s.push({path:$,size:null,type:"directory",reason:Pe(ai)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;if(!O(e.physicalProjectRoot,te)||ti(e.physicalNativeRoot,te))continue;if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||(await g(F),m))break;continue}if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||m)break}}catch(P){S=!0,R=P}let N;try{await k.close()}catch(P){N=P}let w=p();if(S)throw R;if(w&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await g(t),p(),h?(o.length=0,d=0,f=0):(o.sort((E,k)=>E.path.localeCompare(k.path,"en")),s.sort((E,k)=>E.path.localeCompare(k.path,"en")));let y=h?L(`comet.native.physical-selection-incomplete.v1
182
+ `}function UT(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return _t.join(e.transactionsDir,t)}function Ll(e,t){let i=UT(e,t);return{directory:i,journal:_t.join(i,"transaction.json"),events:_t.join(i,"events.jsonl"),staged:_t.join(i,"staged"),backups:_t.join(i,"backups")}}async function pi(e,t){let i=Ll(e,t);return await Promise.all(Object.values(i).map(r=>I(e.runtimeDir,r))),i}function KT(e,t){if(t.length===0||_t.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=_t.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Sr(e,t){let i=KT(e,t);return I(j(e,i),i)}async function pn(e){try{return await Go.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mh(e,t,i={}){let r=await pi(e,t);try{await Go.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 re({root:e.runtimeDir,file:r.events,maxBytes:FT,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=uN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=GT(a),s=fN(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 aN(e,t,i){let r=await Mh(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 It(e,t,i,r){let n=await pi(e,t),a=await Mh(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await he(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>aN(e,t,a)}),o;if(a.events.length>=Ol)throw new Error(`Native transaction event log ${t} exceeds ${Ol} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return dN(s,s.sequence),await Go.mkdir(n.directory,{recursive:!0}),await he(n.events,fN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>aN(e,t,a)}),s}async function hN(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 pi(e,t.id);await Go.mkdir(i.staged,{recursive:!0}),await Go.mkdir(i.backups,{recursive:!0}),await ee(i.journal,t,{containedRoot:e.runtimeDir}),await It(e,t.id,"prepared")}async function yt(e,t,i={}){let r=await pi(e,t),n=await re({root:e.runtimeDir,file:r.journal,maxBytes:MT,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(uN.decode(n.bytes)),o=Lh(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Er(e,t,i={}){return(await Mh(e,t,i)).events}async function Hl(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 ee((await pi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function Hh(e,t,i){try{return await re({root:j(e,t),file:t,maxBytes:Dh,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Fh(e,t,i,r){let n=await Hh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await Hh(e,i,`${r} target`);await hi({root:j(e,i),directory:_t.dirname(i),label:`${r} target parent`}),await kr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Dh,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function pN(e,t,i){let r=await Hh(e,t,i);r&&await jl({root:j(e,t),file:t,maxBytes:Dh,expectedHash:r.hash,expectedSize:r.size,label:i})}async function oN(e,t){if(!t.backup)return;let i=await Sr(e,t.target),r=await Sr(e,t.backup);!await pn(i)||await pn(r)||await Fh(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function YT(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 oN(e,t),await Fh(e,await Sr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await oN(e,t),await pN(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([pn(r),pn(i)]);if(!n&&a){await(await wt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:BT})).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 $h({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function mN(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 Hl(e,t,"applying"):t,n=await Er(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 It(e,r.id,"operation-started",s.id),await YT(e,s),await It(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await yt(e,r.id),r}async function XT(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 pn(i)){if(await pn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await $h({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await pn(r)?await Fh(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await pN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Ml(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 Er(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 Hl(e,t,"rolling-back");await It(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 XT(e,a);return await It(e,r.id,"rollback-completed"),r=await Hl(e,r,"rolled-back"),r}async function ua(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 It(e,t.id,i),i==="commit"?Hl(e,t,"committed"):t}async function ej(e,t,i){let r;try{r=await QT.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 yt(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(hn(n.name))try{let a=await Jo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(eN(a))return!0}catch{return!0}return!1}async function tj(e,t){let i=Date.now()+5e3,r=ZT.join(e.locksDir,"root-move.lock");for(;;)try{return await vr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Bo(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function se(e,t,i,r){let n=await tj(e,t);try{if(await Zn(e.projectRoot),await ej(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await gr(n)}}function vN(e){return Number.isSafeInteger(e)&&e>=1}async function gN(e){if(!vN(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(!vN(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 Wl}from"crypto";import{spawn as CN}from"node:child_process";import{promises as ce}from"fs";import V from"path";import{createHash as wN}from"crypto";import{createReadStream as ij}from"fs";async function ti(e){let t=wN("sha256");for await(let i of ij(e))t.update(i);return t.digest("hex")}function L(e){return wN("sha256").update(e).digest("hex")}var Fl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Jh=1e3,rj=8*1024*1024,nj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aj=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),oj=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),sj=new Set(["schema","include","exclude","hash"]),cj=new Set(["provider","gitSelection","physicalSelection","projection"]),lj=new Set(["provider","selection"]),uj=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),dj=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),fj=new Set(["schema","status","before","after"]),hj=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),pj=new Set(["path","hash","size","type","gitObjectId"]),mj=new Set(["path","size","type","reason"]),vj=new Set(["ref","hash","count"]),gj=new Set(["change-created","legacy-migration","explicit"]),wj=new Set(["file","directory","other"]),yj=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"]),zl=/^[a-f0-9]{64}$/u,xN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Nj=new Set(["EACCES","EPERM"]),ma=64*1024,Wh=64*1024,bj=6e4,kj=1e3,Sj=2,Gh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Ej={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function AN(e){let t=e.deadlineMs??bj;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 ii(e){return Math.max(0,e.deadlineAt-Date.now())}function M(e){return ii(e)>=1}function Bh(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 ha(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function Pj(e){let t={...Ej,...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 Rj(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&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=CN(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),kj),u.unref()}catch{d(!1)}});for(let s=0;s<Sj;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 Uh(e,t,i,r){let n=ii(e);if(n<1)throw Bh();let a=e.gitProcess,o=CN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,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=Rj(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?Bh(v.error):Bh()}return{code:h,spawnError:s}});return{child:o,completion:f}}function _N(e){let t={...Gh,...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 Bl(e,t,i,r=Wh){let{child:n,completion:a}=Uh(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>=ma)return;let v=ma-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.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 Vh(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Xo(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}=Uh(e,t,i,r.stdin!==void 0),c=[],l=Wl("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,S=N=>{let k=0;for(;k<N.byteLength;){let E=N.indexOf(0,k),R=E<0?N.byteLength:E,y=N.subarray(k,R);if(!p&&y.byteLength>0&&(m.byteLength+y.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,y])),E<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=E+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){S(N);return}for(let E=0;E<N.byteLength;E+=k)S(N.subarray(E,Math.min(N.byteLength,E+k)))}),o.stderr.on("data",N=>{if(d>=ma)return;let k=ma-d,E=Buffer.from(N).subarray(0,k);u.push(E),d+=E.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:k})=>{let E=r.acceptedExitCodes??[0];if(N!==null&&E.includes(N)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Vl(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 Cj(e,t,i){if(i.length===0)return new Set;let r=await Xo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Gh,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=Vl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function xj(e,t,i){let{child:r,completion:n}=Uh(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>=ma)return;let d=ma-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 pa(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function Aj(e,t){return e.map(i=>{let r=pa(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function _j(e){let t=V.resolve(e);for(;;){try{return await ce.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function IN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=pa(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 Xo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Xo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Xo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function TN(e){return{stageBefore:Vh(e.stagedBefore),combined:Vh(e.combined),stageAfter:Vh(e.stagedAfter)}}async function jN(e,t,i=Gh,r={}){let n=V.resolve(t.projectRoot);if(!await _j(n))return null;let a;try{a=await Bl(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw ha(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}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 IN(e,t,i,r)}catch(g){throw ha(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let S of g){let N=Vl(S),k=N.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let E=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,k))?.groups;if(!E)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=pa(N.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),E.stage==="0"&&d.set(R,E.objectId),E.mode==="160000"&&E.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(Vl),m=Aj(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,S)=>!u.has(g)&&v[S].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:TN(o)}}function Rr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function yN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function Ij(e,t){return!Rr(e.stageBefore,e.stageAfter)||!Rr(e.stageAfter,t.stageBefore)||!Rr(e.combined,t.combined)||!Rr(t.stageBefore,t.stageAfter)}async function $N(e,t,i,r,n){let a;try{a=await IN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw ha(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=TN(a),c=yN(o)||yN(s),l=Ij(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:L(`comet.native.git-selection-overflow.v2
183
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var Tj=(1n<<256n)-1n;function jj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function NN(e){let t=V.resolve(e.paths.projectRoot),i=V.resolve(e.paths.nativeRoot),r=V.resolve(e.paths.runtimeDir),n=V.resolve(e.paths.configFile),a=V.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,m=!1,p=()=>ii(e.execution)>=1?!0:(h=!0,m=!0,!1),b=N=>{let k=Buffer.from(`${N.type}\0${N.path}`,"utf8"),E=Wl("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=E[R];if(l=l+BigInt(`0x${E.toString("hex")}`)&Tj,d+=1,f+=k.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,m=!0;return}o.push(N)},g=async N=>{if(m||!p())return;let k;try{k=await ce.opendir(N)}catch(P){if(!p())return;if(!Pe(P)&&!Ee(P)||N===t&&Pe(P))throw P;v||=Ee(P),h||=Pe(P),m=!0;return}if(!p()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let E=!1,R;try{for(;!m&&p();){let P;try{P=await k.read()}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te)||N===t&&Pe(te))throw te;v||=Ee(te),h||=Pe(te),m=!0;break}if(!p()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,m=!0;break}let F=V.join(N,P.name),$=Oj(t,F);if(F===n||F===a||ri(i,F)||ri(r,F)||e.denylist.some(te=>ri(te,F))||ui($)!==null)continue;if(!p())break;let Be;try{Be=await ce.lstat(F)}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te))throw te;if(v=!0,b({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:Pe(te)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;let ue=jj(Be);if(ue==="directory"){if(Mj(e.policy,$))continue;if(!p())break;let te;try{te=await ce.realpath(F)}catch(si){if(!p())break;if(!Pe(si)&&!Ee(si))throw si;if(v=!0,b({path:$,type:ue}),s.push({path:$,size:null,type:"directory",reason:Pe(si)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;if(!O(e.physicalProjectRoot,te)||ri(e.physicalNativeRoot,te))continue;if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||(await g(F),m))break;continue}if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||m)break}}catch(P){E=!0,R=P}let y;try{await k.close()}catch(P){y=P}let w=p();if(E)throw R;if(w&&y!==void 0&&y.code!=="ERR_DIR_CLOSED")throw y};await g(t),p(),h?(o.length=0,d=0,f=0):(o.sort((N,k)=>N.path.localeCompare(k.path,"en")),s.sort((N,k)=>N.path.localeCompare(k.path,"en")));let S=h?L(`comet.native.physical-selection-incomplete.v1
184
184
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):L(`comet.native.physical-selection.v1
185
- ${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:y,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function RN(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 bj(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!RN(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 CN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function fN(e,t){let r=(await Il(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!yN.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return L(`gitlink:${r}`)}async function hN(e,t){let i=await fN(e,t),r=await mj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await fN(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function qo(e,t){if(ci(t)!==null)return!1;let i=V.resolve(e.projectRoot,...t.split("/"));return!ti(V.resolve(e.nativeRoot),i)&&!ti(V.resolve(e.runtimeDir),i)}function Bh(e,t={}){let i=Ii(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 kj(e,t){return V.relative(e,t).split(V.sep).join("/")}function Sj(e,t){return t.map(i=>V.resolve(e,...i.split(/[\\/]/u)))}function ti(e,t){let i=V.resolve(e),r=V.resolve(t);return r===i||O(i,r)}function Pe(e){return sj.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Vh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
186
- `)}function Ej(e,t){return L(`comet.native.snapshot-policy.v1
187
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Oh(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 Pj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function pN(e){let t=ol(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?Pj(n):void 0;if(a&&!a())return!1;let o=Oh(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=Oh(i,c,a),o===null||o.size===0)return!1}return Oh(i,o,a)?.has(i.length)??!1}}function xN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ol(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>ol(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=Ej(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(pN),excludeMatchers:i.map(pN),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 Rj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function mN(e,t,i){if(!e)return!0;let r=()=>M(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 zo(e,t,i){let r=JSON.stringify(i);return L(`${e}
185
+ ${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:S,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function ON(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 $j(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!ON(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 HN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function bN(e,t){let r=(await Bl(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!xN.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return L(`gitlink:${r}`)}async function kN(e,t){let i=await bN(e,t),r=await xj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await bN(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function Yo(e,t){if(ui(t)!==null)return!1;let i=V.resolve(e.projectRoot,...t.split("/"));return!ri(V.resolve(e.nativeRoot),i)&&!ri(V.resolve(e.runtimeDir),i)}function Kh(e,t={}){let i=$i(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 Oj(e,t){return V.relative(e,t).split(V.sep).join("/")}function Hj(e,t){return t.map(i=>V.resolve(e,...i.split(/[\\/]/u)))}function ri(e,t){let i=V.resolve(e),r=V.resolve(t);return r===i||O(i,r)}function Pe(e){return Nj.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Yh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
186
+ `)}function Dj(e,t){return L(`comet.native.snapshot-policy.v1
187
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function qh(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 Lj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function SN(e){let t=ml(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?Lj(n):void 0;if(a&&!a())return!1;let o=qh(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=qh(i,c,a),o===null||o.size===0)return!1}return qh(i,o,a)?.has(i.length)??!1}}function DN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ml(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>ml(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=Dj(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(SN),excludeMatchers:i.map(SN),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 Mj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function EN(e,t,i){if(!e)return!0;let r=()=>M(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 Qo(e,t,i){let r=JSON.stringify(i);return L(`${e}
188
188
  ${Buffer.byteLength(t)}:${t}
189
- ${Buffer.byteLength(r)}:${r}`)}function Dh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function $l(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Dh(i))return e.splice(t,1),i}return null}function br(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Cj(e,t,i,r){if(!M(r))return{status:"budget-exhausted"};let n;try{n=await ce.open(e,"r")}catch(c){if(!M(r))return{status:"budget-exhausted"};throw c}if(!M(r))return await n.close(),{status:"budget-exhausted"};let a=Ol("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!M(r))return{status:"budget-exhausted"};let c=await n.stat();if(!M(r))return{status:"budget-exhausted"};if(!c.isFile()||!br(i,c))return{status:"changed"};for(;;){if(!M(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(!M(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!M(r))return{status:"budget-exhausted"};let d=await n.stat();return M(r)?!d.isFile()||!br(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 It(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jt(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function ra(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function xj(e,t){let i=It(e,`Native snapshot entry ${t}`);jt(i,tj,`Native snapshot entry ${t}`);let r=AN(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Hl.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:pi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!yN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Aj(e,t){let i=It(e,`Native snapshot omission ${t}`);if(jt(i,ij,`Native snapshot omission ${t}`),!aj.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!oj.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:AN(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:pi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function _j(e){let t=It(e,"Native snapshot omission overflow");if(jt(t,rj,"Native snapshot omission overflow"),typeof t.hash!="string"||!Hl.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:ra(t.count,"Native snapshot omission overflow count")}}function ia(e,t){let i=It(e,t);if(jt(i,QI,t),typeof i.hash!="string"||!Hl.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=pi(i.recordCount,`${t} recordCount`),n=pi(i.storedRecordCount,`${t} storedRecordCount`),a=pi(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 vN(e){let t=It(e,"Native Git selection evidence");if(jt(t,XI,"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=ia(t.stageBefore,"Native Git selection stageBefore"),r=ia(t.combined,"Native Git selection combined"),n=ia(t.stageAfter,"Native Git selection stageAfter"),a=ia(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ia(t.finalCombined,"Native Git selection finalCombined"),s=ia(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!kr(i,n)||!kr(n,a)||!kr(r,o)||!kr(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 gN(e,t){let i=It(e,t);if(jt(i,ej,t),typeof i.hash!="string"||!Hl.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=pi(i.visitedNodeCount,`${t} visitedNodeCount`),n=pi(i.recordCount,`${t} recordCount`),a=pi(i.storedRecordCount,`${t} storedRecordCount`),o=pi(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 Tj(e){let t=It(e,"Native physical selection evidence");if(jt(t,ZI,"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=gN(t.before,"Native physical selection before"),r=gN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!RN(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 Ii(e){let t=It(e,"Native content snapshot manifest");if(jt(t,JI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!nj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let S=It(t.capture,"Native content snapshot capture");if(jt(S,KI,"Native content snapshot capture"),S.provider!=="git"&&S.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=S.gitSelection===void 0?void 0:vN(S.gitSelection),N=S.physicalSelection===void 0?void 0:Tj(S.physicalSelection),w=null;if(S.projection!==void 0){let P=It(S.projection,"Native content snapshot projection");if(jt(P,YI,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:vN(P.selection)}}}if(S.provider==="git"){if(N||w)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(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}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=It(t.limits,"Native content snapshot limits");jt(r,GI,"Native content snapshot limits");let n={maxFiles:ra(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ra(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ra(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ra(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:ra(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let S=It(t.policy,"Native snapshot policy");if(jt(S,UI,"Native snapshot policy"),S.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(S.include)||!Array.isArray(S.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=xN({include:S.include,exclude:S.exclude,hash:S.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(xj),s=t.omitted.map(Aj),c=pi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:_j(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(S=>S.size>n.maxFileBytes)||o.reduce((S,R)=>S+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(S=>S.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Lh||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(S=>S.reason==="git-enumeration-limit"),f=s.filter(S=>S.reason==="git-selection-changed");for(let S of[...d,...f])if(S.path!=="."||S.size!==null||S.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",m=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(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(S=>S.reason==="physical-enumeration-limit"),b=s.filter(S=>S.reason==="physical-selection-changed");for(let S of[...p,...b])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,y=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(y!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(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(Vh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Dl(e,t,i={}){let r=Ii(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=NN(i),o=bN(i.gitSelectionLimits),s=await EN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(CN(s).filter(N=>qo(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>qo(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),v=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),m=await pj(a,n,v),p=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&qo(e,N.path)&&(c.has(N.path)||!m.has(N.path)));await PN(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let N of l)b.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((N,w)=>N.path.localeCompare(w.path,"en"));let g=r.omitted.filter(N=>f(N.path)||h(N.path)||!qo(e,N.path)?!1:m.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of b)g.some(w=>w.path===N.path&&w.reason===N.reason)||g.push(N);g.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omissionOverflow?.count??0,E=r.omissionOverflow?.hash??L("comet.native.snapshot-omission-overflow.v1");s.overflow&&(y+=s.overflow.count,E=zo(E,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{y+=1,E=zo(E,"omission",N)};for(;g.length>Lh;){let N=$l(g);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let S=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+y===0,entries:p,omitted:g,omittedCount:g.length+y,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:y}}:{}}),R=S();for(;Vh(R)>r.limits.maxManifestBytes;){let N=$l(g);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=S()}return Ii(R)}function _N(e,t){if(!zI.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(H(e,t),"baseline-manifest.json")}async function Ll(e,t={}){let i={maxFiles:t.limits?.maxFiles??Tl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Tl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Tl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Tl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=xN(t.policy),n=NN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=bN(t.gitSelectionLimits),o=fj(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await ce.realpath(s),l=V.resolve(e.nativeRoot),u=await ce.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=Sj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,y=0,E=0,k=L("comet.native.snapshot-omission-overflow.v1"),S=0,R=!1,N=null,w=_=>{E+=1,k=zo(k,"omission",_)},P=_=>{if(y+=1,p.length<Lh){p.push(_);return}if(Dh(_)){let A=$l(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{y+=_.count,E+=_.count,k=zo(k,"git-selection",{source:"git-selection",..._})},$=_=>{E+=1,k=zo(k,"manifest-entry",{reason:"manifest-size",entry:_})},Fe=async(_,A)=>{m.push(_),S+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ue=(_,A)=>{let I=m.findIndex(oe=>oe.path===_);if(I<0)return;let[q]=m.splice(I,1);S-=q.size,b.delete(_),P(A)},te=async(_,A,I,q)=>{if(!I.isFile()||I.isSymbolicLink()||!M(n))return;let oe;try{oe=await ce.realpath(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n)||!O(c,oe)||ti(u,oe))return;if(m.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(S+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let U,B,ve;try{if(U=await Cj(oe,I.size,I,n),U.status==="budget-exhausted"||!M(n))return;if(U.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!M(n)||(ve=await ce.realpath(_),!M(n)))return;B=await ce.lstat(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(M(n)){if(U.bytes!==I.size||ve!==oe||!br(I,U.finalStat)||!br(U.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}M(n)&&await Fe({path:A,hash:U.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:oe,stat:B})}},ai=async(_,A,I)=>{if(!M(n))return;let q,oe,U;try{if(q=await ce.readlink(_,{encoding:"buffer"}),!M(n)||(U=await ce.lstat(_),!M(n)))return;oe=await ce.readlink(_,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:null,type:"other",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n))return;if(!U.isSymbolicLink()||!br(I,U)||U.mtimeMs!==I.mtimeMs||U.ctimeMs!==I.ctimeMs||!q.equals(oe)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.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(S+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let ve=Ol("sha256").update("symlink\0").update(q).digest("hex");M(n)&&await Fe({path:A,hash:ve,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:U})},Vt=async()=>{for(let[_,A]of[...b]){if(!M(n))return;if(A.kind==="file"){let B,ve;try{if(B=await ce.realpath(A.target),!M(n))return;ve=await ce.lstat(A.target)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"file",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(B!==A.realTarget||!ve.isFile()||ve.isSymbolicLink()||!br(A.stat,ve)||ve.size!==A.stat.size||ve.mtimeMs!==A.stat.mtimeMs||ve.ctimeMs!==A.stat.ctimeMs)&&ue(_,{path:_,size:ve.isFile()?ve.size:null,type:ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,ve;try{if(B=await ce.lstat(A.target),!M(n))return;ve=await ce.readlink(A.target,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"other",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(!B.isSymbolicLink()||!br(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ve))&&ue(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,q;try{if(I=await ce.realpath(A.target),!M(n))return;q=await ce.lstat(A.target)}catch{if(!M(n))return;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;if(!(I===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&br(A.stat,q)&&O(c,I)&&!ti(u,I))){ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let U;try{if(!M(n))return;U=await hN(n,I)}catch(B){if(na(B))throw B;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;U.dirty?ue(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):U.hash!==A.hash&&ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!M(n))return;try{let I=await ce.lstat(A);if(!M(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(!M(n))return;if(Ee(I))continue;if(!Pe(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},pt=await EN(n,e,a,t.gitSelectionHooks);if(pt===null){let _=await dN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(ei(n)<1)break;if(!mN(r,q.path,n))continue;if(ei(n)<1)break;let oe=V.resolve(s,...q.path.split("/")),U;try{U=await ce.lstat(oe)}catch(B){if(!M(n))break;if(!Pe(B)&&!Ee(B))throw B;P({path:q.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(ei(n)<1)break;if(q.type==="symlink"&&U.isSymbolicLink()){if(await ai(oe,q.path,U),ei(n)<1)break;continue}if(q.type!=="file"||!U.isFile()||U.isSymbolicLink()){P({path:q.path,size:U.isFile()?U.size:null,type:U.isDirectory()?"directory":U.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(oe,q.path,U),ei(n)<1)break}ei(n)>=1&&await Vt();let A=await dN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=bj(_.evidence,A.evidence);N=I.evidence;for(let q of[..._.omissions,...A.omissions,...I.omissions])p.some(oe=>oe.path===q.path&&oe.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=Ii(_);for(let de of x.entries)de.gitObjectId!==void 0&&A.set(de.path,de);I=A.size>0}let q=new Set,oe=!0;try{let x=await Wo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,oe=!1,A.clear();else for(let de of x.records){let ge=jl(de),Ye=ge.indexOf(" "),Be=Ye<0?null:aa(ge.slice(Ye+1));if(Ye!==1||Be===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&q.add(Be)}}catch(x){if(na(x))throw x;I=!1,oe=!1,A.clear()}let U=new Set;try{let x=await Il(n,s,["ls-files","--modified","-z"],Hh);for(let de of x.toString("utf8").split("\0")){let ge=aa(de);ge!==null&&U.add(ge)}}catch{I=!1,oe=!1,A.clear()}let B=new Set,ve=new Set;for(let x of CN(pt)){if(b.has(x)||!qo(e,x))continue;if(ei(n)<1)break;if(!mN(r,x,n))continue;if(ei(n)<1)break;let de=V.resolve(s,...x.split("/"));if(de===f||de===h||ti(d,de)||v.some(mt=>ti(mt,de)))continue;if(pt.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let mt,zs;try{[mt,zs]=await Promise.all([ce.realpath(de),ce.lstat(de)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(zs.isSymbolicLink()||!zs.isDirectory()||!O(c,mt)||ti(u,mt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Pn=await hN(n,mt);if(Pn.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Fe({path:x,hash:Pn.hash,size:0,type:"file"},{kind:"gitlink",target:de,realTarget:mt,stat:zs,hash:Pn.hash})}catch(Pn){if(na(Pn))throw Pn;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await ce.lstat(de)}catch(mt){if(Ee(mt)&&pt.tracked.has(x)){g.set(x,de);continue}if(!Pe(mt)&&!Ee(mt))throw mt;P({path:x,size:null,type:"file",reason:Ee(mt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await ai(de,x,ge);continue}if(!ge.isFile()){pt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ye=pt.trackedObjectIds.get(x),Be=Ye?A.get(x):void 0;if(I&&Be?.gitObjectId!==void 0&&Be.gitObjectId===Ye&&!q.has(x)&&!U.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Be.size,type:"file",reason:"file-count"});continue}if(Be.size>i.maxFileBytes){P({path:x,size:Be.size,type:"file",reason:"file-size"});continue}if(S+Be.size>i.maxTotalBytes){P({path:x,size:Be.size,type:"file",reason:"total-size"});continue}m.push({...Be}),S+=Be.size,B.add(x);continue}let qm=oe&&!q.has(x)&&!U.has(x)?Ye:void 0;await te(de,x,ge,qm),qm!==void 0&&ve.add(x)}if(await Vt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await PN(n,e,a,pt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&ve.size>0){let x=await Il(n,s,["ls-files","--modified","-z"],Hh),de=new Set;for(let ge of x.toString("utf8").split("\0")){let Ye=aa(ge);Ye!==null&&de.add(Ye)}for(let ge of B){if(!de.has(ge))continue;let Ye=m.find(Be=>Be.path===ge);ue(ge,{path:ge,size:Ye?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of ve){if(!de.has(ge))continue;let Ye=m.find(Be=>Be.path===ge);Ye&&delete Ye.gitObjectId}}for(let x of pt.omissions)P(x);pt.overflow&&F(pt.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let fP=pt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...pt.evidence?{gitSelection:pt.evidence}:{}},Vm=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:fP,createdAt:(t.now??new Date).toISOString(),complete:y===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:y,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:E}}:{}}),sd=Vm();for(;Vh(sd)>i.maxManifestBytes;){if(p.filter(A=>!Dh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I=0;I<A;I+=1){let q=$l(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I of m.splice(-A))y+=1,$(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");sd=Vm()}return sd}async function qh(e,t,i={}){let n=(await ye(e.projectRoot))?.native.snapshot??lh;return Ll(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 Wh(e,t,i){let r=_N(e,t);await T(j(e,r),r),await ee(r,Ii(i))}async function sa(e,t){let i=_N(e,t),r=j(e,i);await T(r,i);try{let n=await Sl({root:r,file:i,maxBytes:WI,label:"Native baseline snapshot manifest"});return Ii(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Xj}from"crypto";import Qj from"path";var Nt=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 zj}from"node:crypto";import{constants as Fl,promises as tt}from"node:fs";import bt from"node:path";import{TextDecoder as Jj}from"node:util";import Bj from"path";var Dj=Rn(Qr(),1);var J1=4*1024*1024;var Lj=null;function Mj(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function TN(e,t){return(...i)=>{let r=Lj;if(r===null)return t(...i);let n=Mj(`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 X1=TN("hookWritePolicy",async e=>(await nh(e))?.hook??{allow_paths:[]});var IN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Go(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Jo(e,t){let i=Go(e,t);if(Bj.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 Vj(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 jN(e){if(!e.run_id)return null;let t=Go(e,"run_id"),i=Go(e,"skill"),r=Go(e,"skill_version"),n=Go(e,"skill_hash"),a=Jo(e,"pending_ref"),o=Jo(e,"trajectory_ref"),s=Jo(e,"context_ref"),c=Jo(e,"artifacts_ref"),l=Jo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:IN(e,"current_step"),iteration:u,pending:IN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Vj(e)}}var zW=256*1024;var qj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Wj(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=jN(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ml(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=>!qj.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 Wj(t)}var Je={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 Ko(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function ON(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Uo(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 Gj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sr(e,t,i){let r=Nt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=bt.resolve(e),a=bt.resolve(n,...r.slice(8).split("/"));if(!Ko(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function $N(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zh(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Ko(i,r))throw new Error("Native Run path is outside its change");let n=[await $N(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await $N(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ko(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Bl(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Gj(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Uj(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 ln(e,t,i,r,n){let a=await zh(e,bt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.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=ON(o),c=await tt.realpath(t);if(!Ko(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Fl.O_RDONLY:Fl.O_RDONLY|Fl.O_NOFOLLOW|Fl.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Bl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Uo(s,d)||!Uo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await Uj(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Bl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!Uo(s,m)||!Uo(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new Jj("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`${r} is not valid UTF-8`,{cause:y})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function Kj(e,t,i){let r=await zh(e,bt.dirname(t));if(!r)return{exists:!1};let n;try{n=await tt.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 tt.realpath(t);if(!Ko(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Bl(r),{exists:!0,identity:ON(n),realPath:a}}async function Yj(e,t,i,r){let n=await zh(e,bt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await tt.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()||!Uo(i.identity,a)||await tt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Bl(n)}async function Vl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await Kj(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await he(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await Yj(e.changeDir,e.file,i,e.label)}});let r=await ln(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 HN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function DN(e){return`${JSON.stringify(e,null,2)}
190
- `}function Er(e){return Ml(e)}async function $e(e,t){let i=Sr(e,"stateRef"),r=await ln(e,i,Je.runStateBytes,"Native Run state",t);return r?Ml(HN(r.text,"Native Run state")):null}async function un(e,t,i){let r=Ml(t);await Vl({changeDir:e,file:Sr(e,"stateRef"),content:DN(r),maxBytes:Je.runStateBytes,label:"Native Run state",hooks:i})}async function it(e,t,i){let r=Sr(e,"trajectoryRef",t),n=await ln(e,r,Je.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>Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.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 LN(e,t,i){return(await ln(e,Sr(e,"trajectoryRef",t),Je.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function MN(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=Sr(e,"trajectoryRef",t),o=await ln(e,a,Je.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(zj("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await Vl({changeDir:e,file:a,content:i,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function FN(e,t,i,r){let n=Sr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
191
- `;if(Buffer.byteLength(a,"utf8")>Je.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Je.trajectoryEventBytes} bytes`);let o=await ln(e,n,Je.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);await Vl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function ca(e,t,i){let r=await ln(e,Sr(e,"checkpointRef",t),Je.checkpointBytes,"Native Run checkpoint",i);return r?HN(r.text,"Native Run checkpoint"):null}async function BN(e,t,i,r){await Vl({changeDir:e,file:Sr(e,"checkpointRef",t),content:DN(i),maxBytes:Je.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var Zj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ql=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 Jh(e){return Xj("sha256").update(e).digest("hex")}function e$(e,t){if(!Zj.test(t))throw new Error(`Invalid Native change name: ${t}`);return Qj.join(H(e,t),"trajectory.jsonl")}function t$(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 i$(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 r$(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=t$(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(`
192
- `)])}catch(d){if(!i$(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:Jh(t),targetHash:Jh(l),tailHash:Jh(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function VN(e,t){let i=e$(e,t);await T(j(e,i),i);let r=H(e,t),n=await LN(r,Nt.trajectoryRef);return n===null?{status:"clean",file:i}:r$(i,Buffer.from(n))}async function la(e,t){let i=await VN(e,t);return"inspection"in i?i.inspection:i}async function Wl(e,t){let i=await la(e,t);if(i.status!=="clean")throw new ql(i)}async function qN(e,t,i){return se(e,`repair trajectory tail for ${t}`,async()=>{let r=await VN(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new ql(r)}try{await MN(H(e,t),Nt.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 la(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 n$}from"node:crypto";import{promises as zl}from"node:fs";import ji from"node:path";var Yo=/^[a-f0-9]{64}$/u,WN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,a$=16*1024,Uh=process.platform,o$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ua(e){return o$.has(e)}function GN(e,t){let i=ji.relative(e,t);return ji.isAbsolute(i)||i===".."||i.startsWith(`..${ji.sep}`)?null:i.replaceAll("\\","/")||"."}function UN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function KN(e,t){if(e.length===0||UN(e)||e.includes("\\")||ji.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=ji.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Kh(e,t){return n$("sha256").update(`${e}
193
- ${t}`).digest("hex")}async function zN(e,t){let i=await zl.realpath(t),r=await zl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Uh==="win32"?ji.normalize(i).toLowerCase():i;return Kh(e,`${n}
189
+ ${Buffer.byteLength(r)}:${r}`)}function zh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ql(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!zh(i))return e.splice(t,1),i}return null}function Pr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Fj(e,t,i,r){if(!M(r))return{status:"budget-exhausted"};let n;try{n=await ce.open(e,"r")}catch(c){if(!M(r))return{status:"budget-exhausted"};throw c}if(!M(r))return await n.close(),{status:"budget-exhausted"};let a=Wl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!M(r))return{status:"budget-exhausted"};let c=await n.stat();if(!M(r))return{status:"budget-exhausted"};if(!c.isFile()||!Pr(i,c))return{status:"changed"};for(;;){if(!M(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(!M(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!M(r))return{status:"budget-exhausted"};let d=await n.stat();return M(r)?!d.isFile()||!Pr(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 Tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jt(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function fa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function LN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Bj(e,t){let i=Tt(e,`Native snapshot entry ${t}`);jt(i,pj,`Native snapshot entry ${t}`);let r=LN(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!zl.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:mi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!xN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Vj(e,t){let i=Tt(e,`Native snapshot omission ${t}`);if(jt(i,mj,`Native snapshot omission ${t}`),!wj.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!yj.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:LN(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:mi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function qj(e){let t=Tt(e,"Native snapshot omission overflow");if(jt(t,vj,"Native snapshot omission overflow"),typeof t.hash!="string"||!zl.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:fa(t.count,"Native snapshot omission overflow count")}}function da(e,t){let i=Tt(e,t);if(jt(i,dj,t),typeof i.hash!="string"||!zl.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=mi(i.recordCount,`${t} recordCount`),n=mi(i.storedRecordCount,`${t} storedRecordCount`),a=mi(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 PN(e){let t=Tt(e,"Native Git selection evidence");if(jt(t,uj,"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=da(t.stageBefore,"Native Git selection stageBefore"),r=da(t.combined,"Native Git selection combined"),n=da(t.stageAfter,"Native Git selection stageAfter"),a=da(t.finalStageBefore,"Native Git selection finalStageBefore"),o=da(t.finalCombined,"Native Git selection finalCombined"),s=da(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Rr(i,n)||!Rr(n,a)||!Rr(r,o)||!Rr(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 RN(e,t){let i=Tt(e,t);if(jt(i,hj,t),typeof i.hash!="string"||!zl.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=mi(i.visitedNodeCount,`${t} visitedNodeCount`),n=mi(i.recordCount,`${t} recordCount`),a=mi(i.storedRecordCount,`${t} storedRecordCount`),o=mi(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 Wj(e){let t=Tt(e,"Native physical selection evidence");if(jt(t,fj,"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=RN(t.before,"Native physical selection before"),r=RN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!ON(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 $i(e){let t=Tt(e,"Native content snapshot manifest");if(jt(t,aj,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!gj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let E=Tt(t.capture,"Native content snapshot capture");if(jt(E,cj,"Native content snapshot capture"),E.provider!=="git"&&E.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=E.gitSelection===void 0?void 0:PN(E.gitSelection),y=E.physicalSelection===void 0?void 0:Wj(E.physicalSelection),w=null;if(E.projection!==void 0){let P=Tt(E.projection,"Native content snapshot projection");if(jt(P,lj,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:PN(P.selection)}}}if(E.provider==="git"){if(y||w)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(y&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...y?{physicalSelection:y}:{}}}}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=Tt(t.limits,"Native content snapshot limits");jt(r,oj,"Native content snapshot limits");let n={maxFiles:fa(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:fa(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:fa(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:fa(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:fa(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let E=Tt(t.policy,"Native snapshot policy");if(jt(E,sj,"Native snapshot policy"),E.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(E.include)||!Array.isArray(E.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=DN({include:E.include,exclude:E.exclude,hash:E.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(Bj),s=t.omitted.map(Vj),c=mi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:qj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(E=>E.size>n.maxFileBytes)||o.reduce((E,R)=>E+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(E=>E.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Jh||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(E=>E.reason==="git-enumeration-limit"),f=s.filter(E=>E.reason==="git-selection-changed");for(let E of[...d,...f])if(E.path!=="."||E.size!==null||E.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",m=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(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(E=>E.reason==="physical-enumeration-limit"),b=s.filter(E=>E.reason==="physical-selection-changed");for(let E of[...p,...b])if(E.path!=="."||E.size!==null||E.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,S=g?.status==="overflow"||g?.status==="overflow-and-changed",N=g?.status==="changed"||g?.status==="overflow-and-changed";if(S!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(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(Yh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Jl(e,t,i={}){let r=$i(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=AN(i),o=_N(i.gitSelectionLimits),s=await jN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(HN(s).filter(y=>Yo(e,y))),l=[...s.gitlinks].filter(y=>c.has(y)),u=[...s.nestedRepositories].filter(y=>Yo(e,y)),d=(y,w)=>w.some(P=>y===P||y.startsWith(`${P}/`)),f=y=>d(y,l),h=y=>d(y,u),v=[...r.entries.map(y=>y.path),...r.omitted.flatMap(y=>y.type==="directory"?[y.path,`${y.path}/`]:[y.path])].filter(y=>!c.has(y)&&!f(y)&&!h(y)),m=await Cj(a,n,v),p=r.entries.filter(y=>!f(y.path)&&!h(y.path)&&Yo(e,y.path)&&(c.has(y.path)||!m.has(y.path)));await $N(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let y of l)b.push({path:y,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((y,w)=>y.path.localeCompare(w.path,"en"));let g=r.omitted.filter(y=>f(y.path)||h(y.path)||!Yo(e,y.path)?!1:m.has(y.path)?c.has(y.path)||[...c].some(w=>w.startsWith(`${y.path}/`)):!0);for(let y of b)g.some(w=>w.path===y.path&&w.reason===y.reason)||g.push(y);g.sort((y,w)=>y.path.localeCompare(w.path,"en"));let S=r.omissionOverflow?.count??0,N=r.omissionOverflow?.hash??L("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,N=Qo(N,"git-selection",{source:"git-selection",...s.overflow}));let k=y=>{S+=1,N=Qo(N,"omission",y)};for(;g.length>Jh;){let y=ql(g);if(y===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(y)}let E=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+S===0,entries:p,omitted:g,omittedCount:g.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:S}}:{}}),R=E();for(;Yh(R)>r.limits.maxManifestBytes;){let y=ql(g);if(y===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(y),R=E()}return $i(R)}function MN(e,t){if(!nj.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(D(e,t),"baseline-manifest.json")}async function Gl(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=DN(t.policy),n=AN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=_N(t.gitSelectionLimits),o=Pj(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await ce.realpath(s),l=V.resolve(e.nativeRoot),u=await ce.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=Hj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,S=0,N=0,k=L("comet.native.snapshot-omission-overflow.v1"),E=0,R=!1,y=null,w=_=>{N+=1,k=Qo(k,"omission",_)},P=_=>{if(S+=1,p.length<Jh){p.push(_);return}if(zh(_)){let A=ql(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{S+=_.count,N+=_.count,k=Qo(k,"git-selection",{source:"git-selection",..._})},$=_=>{N+=1,k=Qo(k,"manifest-entry",{reason:"manifest-size",entry:_})},Be=async(_,A)=>{m.push(_),E+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ue=(_,A)=>{let T=m.findIndex(oe=>oe.path===_);if(T<0)return;let[q]=m.splice(T,1);E-=q.size,b.delete(_),P(A)},te=async(_,A,T,q)=>{if(!T.isFile()||T.isSymbolicLink()||!M(n))return;let oe;try{oe=await ce.realpath(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:T.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n)||!O(c,oe)||ri(u,oe))return;if(m.length>=i.maxFiles){P({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){P({path:A,size:T.size,type:"file",reason:"file-size"});return}if(E+T.size>i.maxTotalBytes){P({path:A,size:T.size,type:"file",reason:"total-size"});return}let U,B,ve;try{if(U=await Fj(oe,T.size,T,n),U.status==="budget-exhausted"||!M(n))return;if(U.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!M(n)||(ve=await ce.realpath(_),!M(n)))return;B=await ce.lstat(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:T.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(M(n)){if(U.bytes!==T.size||ve!==oe||!Pr(T,U.finalStat)||!Pr(U.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==T.size||B.mtimeMs!==T.mtimeMs||B.ctimeMs!==T.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}M(n)&&await Be({path:A,hash:U.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:oe,stat:B})}},si=async(_,A,T)=>{if(!M(n))return;let q,oe,U;try{if(q=await ce.readlink(_,{encoding:"buffer"}),!M(n)||(U=await ce.lstat(_),!M(n)))return;oe=await ce.readlink(_,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:null,type:"other",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n))return;if(!U.isSymbolicLink()||!Pr(T,U)||U.mtimeMs!==T.mtimeMs||U.ctimeMs!==T.ctimeMs||!q.equals(oe)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.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(E+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let ve=Wl("sha256").update("symlink\0").update(q).digest("hex");M(n)&&await Be({path:A,hash:ve,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:U})},qt=async()=>{for(let[_,A]of[...b]){if(!M(n))return;if(A.kind==="file"){let B,ve;try{if(B=await ce.realpath(A.target),!M(n))return;ve=await ce.lstat(A.target)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"file",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(B!==A.realTarget||!ve.isFile()||ve.isSymbolicLink()||!Pr(A.stat,ve)||ve.size!==A.stat.size||ve.mtimeMs!==A.stat.mtimeMs||ve.ctimeMs!==A.stat.ctimeMs)&&ue(_,{path:_,size:ve.isFile()?ve.size:null,type:ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,ve;try{if(B=await ce.lstat(A.target),!M(n))return;ve=await ce.readlink(A.target,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"other",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(!B.isSymbolicLink()||!Pr(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ve))&&ue(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let T,q;try{if(T=await ce.realpath(A.target),!M(n))return;q=await ce.lstat(A.target)}catch{if(!M(n))return;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;if(!(T===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&Pr(A.stat,q)&&O(c,T)&&!ri(u,T))){ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let U;try{if(!M(n))return;U=await kN(n,T)}catch(B){if(ha(B))throw B;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;U.dirty?ue(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):U.hash!==A.hash&&ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!M(n))return;try{let T=await ce.lstat(A);if(!M(n))return;P({path:_,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!M(n))return;if(Ee(T))continue;if(!Pe(T))throw T;P({path:_,size:null,type:"file",reason:"unreadable"})}}},pt=await jN(n,e,a,t.gitSelectionHooks);if(pt===null){let _=await NN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(ii(n)<1)break;if(!EN(r,q.path,n))continue;if(ii(n)<1)break;let oe=V.resolve(s,...q.path.split("/")),U;try{U=await ce.lstat(oe)}catch(B){if(!M(n))break;if(!Pe(B)&&!Ee(B))throw B;P({path:q.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(ii(n)<1)break;if(q.type==="symlink"&&U.isSymbolicLink()){if(await si(oe,q.path,U),ii(n)<1)break;continue}if(q.type!=="file"||!U.isFile()||U.isSymbolicLink()){P({path:q.path,size:U.isFile()?U.size:null,type:U.isDirectory()?"directory":U.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(oe,q.path,U),ii(n)<1)break}ii(n)>=1&&await qt();let A=await NN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),T=$j(_.evidence,A.evidence);y=T.evidence;for(let q of[..._.omissions,...A.omissions,...T.omissions])p.some(oe=>oe.path===q.path&&oe.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,T=!1;if(_){let x=$i(_);for(let de of x.entries)de.gitObjectId!==void 0&&A.set(de.path,de);T=A.size>0}let q=new Set,oe=!0;try{let x=await Xo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)T=!1,oe=!1,A.clear();else for(let de of x.records){let ge=Vl(de),Ye=ge.indexOf(" "),Ve=Ye<0?null:pa(ge.slice(Ye+1));if(Ye!==1||Ve===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&q.add(Ve)}}catch(x){if(ha(x))throw x;T=!1,oe=!1,A.clear()}let U=new Set;try{let x=await Bl(n,s,["ls-files","--modified","-z"],Wh);for(let de of x.toString("utf8").split("\0")){let ge=pa(de);ge!==null&&U.add(ge)}}catch{T=!1,oe=!1,A.clear()}let B=new Set,ve=new Set;for(let x of HN(pt)){if(b.has(x)||!Yo(e,x))continue;if(ii(n)<1)break;if(!EN(r,x,n))continue;if(ii(n)<1)break;let de=V.resolve(s,...x.split("/"));if(de===f||de===h||ri(d,de)||v.some(mt=>ri(mt,de)))continue;if(pt.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let mt,Qs;try{[mt,Qs]=await Promise.all([ce.realpath(de),ce.lstat(de)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Qs.isSymbolicLink()||!Qs.isDirectory()||!O(c,mt)||ri(u,mt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let jn=await kN(n,mt);if(jn.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Be({path:x,hash:jn.hash,size:0,type:"file"},{kind:"gitlink",target:de,realTarget:mt,stat:Qs,hash:jn.hash})}catch(jn){if(ha(jn))throw jn;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await ce.lstat(de)}catch(mt){if(Ee(mt)&&pt.tracked.has(x)){g.set(x,de);continue}if(!Pe(mt)&&!Ee(mt))throw mt;P({path:x,size:null,type:"file",reason:Ee(mt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await si(de,x,ge);continue}if(!ge.isFile()){pt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ye=pt.trackedObjectIds.get(x),Ve=Ye?A.get(x):void 0;if(T&&Ve?.gitObjectId!==void 0&&Ve.gitObjectId===Ye&&!q.has(x)&&!U.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Ve.size,type:"file",reason:"file-count"});continue}if(Ve.size>i.maxFileBytes){P({path:x,size:Ve.size,type:"file",reason:"file-size"});continue}if(E+Ve.size>i.maxTotalBytes){P({path:x,size:Ve.size,type:"file",reason:"total-size"});continue}m.push({...Ve}),E+=Ve.size,B.add(x);continue}let Xm=oe&&!q.has(x)&&!U.has(x)?Ye:void 0;await te(de,x,ge,Xm),Xm!==void 0&&ve.add(x)}if(await qt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await $N(n,e,a,pt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||T&&ve.size>0){let x=await Bl(n,s,["ls-files","--modified","-z"],Wh),de=new Set;for(let ge of x.toString("utf8").split("\0")){let Ye=pa(ge);Ye!==null&&de.add(Ye)}for(let ge of B){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);ue(ge,{path:ge,size:Ye?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of ve){if(!de.has(ge))continue;let Ye=m.find(Ve=>Ve.path===ge);Ye&&delete Ye.gitObjectId}}for(let x of pt.omissions)P(x);pt.overflow&&F(pt.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let PP=pt===null?{provider:"physical-tree",...y?{physicalSelection:y}:{}}:{provider:"git",...pt.evidence?{gitSelection:pt.evidence}:{}},Ym=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:PP,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:S,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:N}}:{}}),wd=Ym();for(;Yh(wd)>i.maxManifestBytes;){if(p.filter(A=>!zh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let T=0;T<A;T+=1){let q=ql(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))S+=1,$(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");wd=Ym()}return wd}async function Xh(e,t,i={}){let n=(await ye(e.projectRoot))?.native.snapshot??wh;return Gl(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Qh(e,t,i){let r=MN(e,t);await I(j(e,r),r),await ee(r,$i(i))}async function va(e,t){let i=MN(e,t),r=j(e,i);await I(r,i);try{let n=await Tl({root:r,file:i,maxBytes:rj,label:"Native baseline snapshot manifest"});return $i(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as u$}from"crypto";import d$ from"path";var Nt=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 n$}from"node:crypto";import{constants as Kl,promises as tt}from"node:fs";import bt from"node:path";import{TextDecoder as a$}from"node:util";import e$ from"path";var Yj=$n(nn(),1);var gW=4*1024*1024;var Xj=null;function Qj(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function FN(e,t){return(...i)=>{let r=Xj;if(r===null)return t(...i);let n=Qj(`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 kW=FN("hookWritePolicy",async e=>(await hh(e))?.hook??{allow_paths:[]});var BN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function es(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 Zo(e,t){let i=es(e,t);if(e$.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 t$(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 VN(e){if(!e.run_id)return null;let t=es(e,"run_id"),i=es(e,"skill"),r=es(e,"skill_version"),n=es(e,"skill_hash"),a=Zo(e,"pending_ref"),o=Zo(e,"trajectory_ref"),s=Zo(e,"context_ref"),c=Zo(e,"artifacts_ref"),l=Zo(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:BN(e,"current_step"),iteration:u,pending:BN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:t$(e)}}var w2=256*1024;var i$=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function r$(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=VN(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ul(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=>!i$.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 r$(t)}var Je={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 is(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function WN(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ts(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 o$(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cr(e,t,i){let r=Nt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=bt.resolve(e),a=bt.resolve(n,...r.slice(8).split("/"));if(!is(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function qN(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Zh(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!is(i,r))throw new Error("Native Run path is outside its change");let n=[await qN(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await qN(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!is(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Yl(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!o$(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function s$(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 mn(e,t,i,r,n){let a=await Zh(e,bt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.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=WN(o),c=await tt.realpath(t);if(!is(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Kl.O_RDONLY:Kl.O_RDONLY|Kl.O_NOFOLLOW|Kl.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Yl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!ts(s,d)||!ts(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await s$(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Yl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!ts(s,m)||!ts(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new a$("utf-8",{fatal:!0}).decode(v)}catch(S){throw new Error(`${r} is not valid UTF-8`,{cause:S})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function c$(e,t,i){let r=await Zh(e,bt.dirname(t));if(!r)return{exists:!1};let n;try{n=await tt.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 tt.realpath(t);if(!is(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Yl(r),{exists:!0,identity:WN(n),realPath:a}}async function l$(e,t,i,r){let n=await Zh(e,bt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await tt.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()||!ts(i.identity,a)||await tt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Yl(n)}async function Xl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await c$(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await he(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await l$(e.changeDir,e.file,i,e.label)}});let r=await mn(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 zN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function JN(e){return`${JSON.stringify(e,null,2)}
190
+ `}function xr(e){return Ul(e)}async function Oe(e,t){let i=Cr(e,"stateRef"),r=await mn(e,i,Je.runStateBytes,"Native Run state",t);return r?Ul(zN(r.text,"Native Run state")):null}async function vn(e,t,i){let r=Ul(t);await Xl({changeDir:e,file:Cr(e,"stateRef"),content:JN(r),maxBytes:Je.runStateBytes,label:"Native Run state",hooks:i})}async function it(e,t,i){let r=Cr(e,"trajectoryRef",t),n=await mn(e,r,Je.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>Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.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 GN(e,t,i){return(await mn(e,Cr(e,"trajectoryRef",t),Je.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function UN(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=Cr(e,"trajectoryRef",t),o=await mn(e,a,Je.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(n$("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await Xl({changeDir:e,file:a,content:i,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function KN(e,t,i,r){let n=Cr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
191
+ `;if(Buffer.byteLength(a,"utf8")>Je.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Je.trajectoryEventBytes} bytes`);let o=await mn(e,n,Je.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);await Xl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function ga(e,t,i){let r=await mn(e,Cr(e,"checkpointRef",t),Je.checkpointBytes,"Native Run checkpoint",i);return r?zN(r.text,"Native Run checkpoint"):null}async function YN(e,t,i,r){await Xl({changeDir:e,file:Cr(e,"checkpointRef",t),content:JN(i),maxBytes:Je.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var f$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ql=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 ep(e){return u$("sha256").update(e).digest("hex")}function h$(e,t){if(!f$.test(t))throw new Error(`Invalid Native change name: ${t}`);return d$.join(D(e,t),"trajectory.jsonl")}function p$(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 m$(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 v$(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=p$(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(`
192
+ `)])}catch(d){if(!m$(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:ep(t),targetHash:ep(l),tailHash:ep(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function XN(e,t){let i=h$(e,t);await I(j(e,i),i);let r=D(e,t),n=await GN(r,Nt.trajectoryRef);return n===null?{status:"clean",file:i}:v$(i,Buffer.from(n))}async function wa(e,t){let i=await XN(e,t);return"inspection"in i?i.inspection:i}async function Zl(e,t){let i=await wa(e,t);if(i.status!=="clean")throw new Ql(i)}async function QN(e,t,i){return se(e,`repair trajectory tail for ${t}`,async()=>{let r=await XN(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new Ql(r)}try{await UN(D(e,t),Nt.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 wa(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 g$}from"node:crypto";import{promises as eu}from"node:fs";import Oi from"node:path";var rs=/^[a-f0-9]{64}$/u,ZN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,w$=16*1024,ip=process.platform,y$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ya(e){return y$.has(e)}function ib(e,t){let i=Oi.relative(e,t);return Oi.isAbsolute(i)||i===".."||i.startsWith(`..${Oi.sep}`)?null:i.replaceAll("\\","/")||"."}function rb(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function nb(e,t){if(e.length===0||rb(e)||e.includes("\\")||Oi.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=Oi.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function rp(e,t){return g$("sha256").update(`${e}
193
+ ${t}`).digest("hex")}async function eb(e,t){let i=await eu.realpath(t),r=await eu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ip==="win32"?Oi.normalize(i).toLowerCase():i;return rp(e,`${n}
194
194
  ${r.dev}
195
195
  ${r.ino}
196
- ${r.birthtimeMs}`)}async function JN(e,t){let i=await zl.realpath(t),r=await zl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Uh==="win32"?ji.normalize(i).toLowerCase():i;return Kh(e,n)}function s$(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 Gh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||UN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function YN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Gh(e.changeBranch,"Native workspace change branch"),Gh(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 c$(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"||!WN.test(t.baseCommit)||typeof t.targetCommit!="string"||!WN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Gh(t.targetBranch,"Native workspace Git target branch")}function Xo(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"||!Yo.test(String(t.projectRootId))||!Yo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");s$(t.capturedAt),KN(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&&!Yo.test(String(t.projectRootPathId))||a&&!Yo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Yo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&c$(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(YN(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 da(e,t){return ji.join(H(e,t),"workspace.json")}function l$(e,t){let i=da(e,t),r=j(e,i),n=GN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:KN(n,"Native workspace file ref")}}async function XN(e,t){try{let i=l$(e,t),r=await Z({root:i.root,ref:i.ref,maxBytes:a$});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function QN(e,t){let i=fe(e.projectRoot),r={projectRoot:ji.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await kt(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 fa({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 Yh(e,t){let i=await XN(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:(Xo(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function ZN(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=GN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=fe(e.paths.projectRoot),r=i.isGitWorktree?xi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:xi(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([zN("comet.native.workspace-project-root.v2",e.paths.projectRoot),zN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),JN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),JN("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&&YN(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:Kh("comet.native.workspace-session.v2",`${s}
196
+ ${r.birthtimeMs}`)}async function tb(e,t){let i=await eu.realpath(t),r=await eu.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ip==="win32"?Oi.normalize(i).toLowerCase():i;return rp(e,n)}function N$(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function tp(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||rb(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function ab(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(tp(e.changeBranch,"Native workspace change branch"),tp(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function b$(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"||!ZN.test(t.baseCommit)||typeof t.targetCommit!="string"||!ZN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");tp(t.targetBranch,"Native workspace Git target branch")}function ns(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"||!rs.test(String(t.projectRootId))||!rs.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");N$(t.capturedAt),nb(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&&!rs.test(String(t.projectRootPathId))||a&&!rs.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!rs.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&b$(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(ab(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 Na(e,t){return Oi.join(D(e,t),"workspace.json")}function k$(e,t){let i=Na(e,t),r=j(e,i),n=ib(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:nb(n,"Native workspace file ref")}}async function ob(e,t){try{let i=k$(e,t),r=await Z({root:i.root,ref:i.ref,maxBytes:w$});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function sb(e,t){let i=fe(e.projectRoot),r={projectRoot:Oi.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await kt(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 ba({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 np(e,t){let i=await ob(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:(ns(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function cb(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=ib(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=fe(e.paths.projectRoot),r=i.isGitWorktree?Ai(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Ai(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([eb("comet.native.workspace-project-root.v2",e.paths.projectRoot),eb("comet.native.workspace-native-root.v2",e.paths.nativeRoot),tb("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),tb("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&&ab(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:rp("comet.native.workspace-session.v2",`${s}
197
197
  ${c}
198
- ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Xo(h),h}async function Jl(e){let t=await ZN(e),i=da(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ee(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await XN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Xo(i),i)}async function eb(e){return await Yh(e.paths,e.name)?Jl(e):null}async function Qo(e){Xo(e.identity);let t=await ZN({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")),Uh==="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 fa(e){if(Xo(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 Qo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=fe(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function tb(e,t){let i=await kt(e,t);if(i===null)return null;let r=await fa({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var rb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],u$=new Set(rb),nb=new Set([...rb,"minimum_runtime_version","revision"]),d$=new Set([...nb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),f$=new Set(["capability","operation","source","base_hash"]),h$=new Set(["shape","build","verify","archive"]),p$=new Set(["implicit","confirmed"]),m$=new Set(["pending","pass","fail"]),Te="comet-state.yaml",Qh=/^[a-f0-9]{64}$/u,ab=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,v$=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Zo=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"},fn=class extends Error{constructor(i,r){super(i!==Ne||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"},es=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"},ts=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"},ha=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"},M2=Us("en");function rs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ob(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 Ul(e){if(!ab.test(e))throw new Error(`Invalid Native change name: ${e}`)}function g$(e){if(!ab.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function sb(e,t){if(e.length===0||mi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function w$(e,t){let i=rs(e,`spec_changes[${t}]`);if(ob(i,f$,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(g$(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"&&sb(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"||!Qh.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"||!Qh.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 y$(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 Zh(e,t){if(ob(e,t,Te),typeof e.name!="string")throw new Error("Native change name is required");if(Ul(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"||!h$.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&&!p$.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(w$),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"||!m$.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"&&sb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!y$(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 on(e){let t=rs(e,Te);if(t.schema!==et)throw new Error(`Expected ${et}`);return{schema:et,...Zh(t,u$)}}function is(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xh(e,t,i){if(e===null)return null;let r=typeof e=="string"?v$.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 N$(e){if(e==null)return null;if(typeof e!="string"||!Qh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function b$(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 di(e){let t=rs(e,Te);if(t.schema!==be)throw new Error(`Expected ${be}`);if(is(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${be} minimum_runtime_version must be 2`);return{schema:be,minimum_runtime_version:2,revision:is(t.revision,"Native v2 revision"),...Zh(t,nb)}}function lt(e){let t=rs(e,Te);if(t.schema!==Ne){if(t.schema===et||t.schema===be){let o=t.schema===et?on(t):di(t);throw new Zo(o.name,o.schema)}throw new fn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=is(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new fn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=is(t.revision,"Native revision"),n=Zh(t,d$),a=N$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ne,minimum_runtime_version:3,revision:r,verification_protocol:b$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xh(t.partial_allowance,"Native partial_allowance","allowances")}}function cb(e){let t=rs(e,Te);if(t.schema===et){let n=on(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema===be){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema!==Ne){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 fn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=is(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new fn(t.schema,i).message};let r=lt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function dn(e){let t=lt(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 Kl(e){let t=di(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 ne(e,t){Ul(t);let i=mi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function pa(e,t){let i=H(e,t),r=mi.join(i,"schema-migration.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await ib.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ma(e,t){let i=H(e,t),r=mi.join(i,"checkpoint-journal.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await ib.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Yl(e,t=mi.dirname(e)){let i=mi.relative(t,e).split(mi.sep).join("/"),r=await Z({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,Gl.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 vi(e,t){let i=mi.join(ne(e,t),Te);await T(e.nativeRoot,i);let r=cb(await Yl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await pa(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 k$(e,r.state),r)}async function Xl(e,t){let i=mi.join(ne(e,t),Te);await T(e.nativeRoot,i);let r=cb(await Yl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function k$(e,t){if(await sa(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function He(e,t){let i=await vi(e,t);if(i.status==="migration-required")throw new Zo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new fn(i.schema,i.minimumRuntimeVersion);return await tb(e,t),i.state}async function lb(e,t,i){let r={...t,schema:Ne,minimum_runtime_version:3,revision:i+1},n=await cN({expectedRevision:i,next:r,read:async()=>{let a=lt(await Yl(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>he(e,(0,Gl.stringify)(dn(a))),equals:(a,o)=>JSON.stringify(dn(a))===JSON.stringify(dn(o)),conflict:a=>new es(t.name,i,a)});return Object.assign(t,n),n}async function Ql(e,t,i,r){if(await Wn(e.projectRoot),await pa(e,t.name))throw new Zo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await ma(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await He(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Wl(e,t.name);let a=mi.join(ne(e,t.name),Te);return await T(e.nativeRoot,a),lb(a,t,i)}async function ub(e,t){return lb(e,t,t.revision)}async function db(e){return lt(await Yl(e))}var hb=["outcome","scope","nonGoals","acceptanceExamples"],S$=[...hb,"constraints","decisions","openQuestions","verificationExpectations"],E$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],pb={maxFileBytes:So};function mb(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
199
- `).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 P$(e,t){let i=fb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await ep.realpath(e),n=await ep.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ep.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function ns(e){return{valid:e.length===0,findings:e}}async function tp(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:pb.maxFileBytes})).text}catch(o){return ns([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of mb(r))n.set(Gs(o)??o,s);for(let o of S$)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of hb)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("openQuestions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),ns(i)}async function ip(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:pb.maxFileBytes})).text}catch(a){return ns([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of mb(r))n.set(Zm(a)??a,o);for(let a of E$)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 ns(i)}function Zl(e,t){return fb.join(e.specsDir,t,"spec.md")}async function vb(e,t){let i=[],r=ne(e,t.name);for(let n of t.spec_changes){let a=Zl(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 P$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return ns(i)}import{promises as TH}from"node:fs";import Zk from"node:path";import gb from"node:path";var R$="comet.native.archive-preflight.v1",C$="comet.native.archive-preflight.v1",x$="comet.native.archive-operation.v1",A$=/^[a-f0-9]{64}$/u,wb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function eu(e,t){return e<t?-1:e>t?1:0}function T$(e,t){if(typeof e!="string"||!A$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $i(e,t){return e===null?null:T$(e,t)}function I$(e,t){let i=gb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||gb.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 j$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function $$(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 O$(e,t){if(!wb.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=$i(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=$i(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=$i(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 H$(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:$i(e.contractHash,"Native archive contract hash"),acceptanceHash:$i(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:$i(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:$i(e.reportHash,"Native archive report hash"),envelopeHash:$i(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:$i(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 D$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!_$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(eu);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function L$(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(eu)}function yb(e){if(!wb.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(O$).sort((l,u)=>eu(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(x$,l)})),r=H$(e.evidence),n=$$(e.workspace),a=[...new Set([...D$(e.findingCodes??[]),...L$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(eu),o=j$(e.revision),s=I$(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:R$,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:D(C$,c)}}import{createHash as M$}from"node:crypto";import Nb from"node:path";var F$="comet.native.conflict-radar.v1",ut=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}),B$="comet.native.conflict-radar.v1",V$="comet.native.conflict-radar-signals.v1",q$=/^[a-f0-9]{64}$/u,Sb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,W$=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),z$=new Set(["capability","operation","baseHash"]),J$=new Set(["path","kind"]);function va(e,t){return e<t?-1:e>t?1:0}function rp(e){return Buffer.byteLength(e,"utf8")}function np(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 ap(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(rp(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function G$(e,t){let i=ap(e,t,ut.maxArtifactPathBytes),r=Nb.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)||Nb.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 Eb(e,t){if(typeof e!="string"||!q$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function U$(e,t){let i=np(e,z$,t),r=ap(i.capability,`${t} capability`,ut.maxCapabilityBytes);if(!Sb.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:Eb(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 K$(e,t){let i=np(e,J$,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:G$(i.path,`${t} path`),kind:i.kind}}function Y$(e,t){let i=np(e,W$,`Conflict radar change ${t}`),r=ap(i.name,`Conflict radar change ${t} name`,ut.maxNameBytes);if(!Sb.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>ut.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>ut.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>U$(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>va(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)=>K$(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>va(c.path,l.path)||va(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:Eb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function X$(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ut.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(Y$).sort((n,a)=>va(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)>ut.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ut.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function Q$(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 Z$(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 eO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function tO(e,t){let i=[],r=M$("sha256").update(`${V$}
200
- [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Oo(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ut.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(Q$(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Z$(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:eO(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function bb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function iO(e,t){return bb(e.classification)-bb(t.classification)||va(e.left,t.left)||va(e.right,t.right)}function kb(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:F$,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 Pb(e){let t=X$(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(tO(t[s],t[c]));i.sort(iO);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D(B$,{changes:t,relationships:r}),a=i.slice(0,ut.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=kb(t,i,a,n);for(;a.length>0&&rp(JSON.stringify(o))>ut.maxSerializedBytes;)a=a.slice(0,-1),o=kb(t,i,a,n);if(rp(JSON.stringify(o))>ut.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as h0}from"node:crypto";import{promises as ri}from"node:fs";import yi from"node:path";import{createHash as jb}from"node:crypto";import Rb from"path";var op="comet.native.implementation-scope.v2",$b="comet.native.content-snapshot-projection.v1",as="comet.native.content-snapshot-projection.v1",Ob="comet.native.implementation-scope.v2",rO="comet.native.unresolved-scope-id.v1",nO="comet.native.scope-detail-overflow.v1",aO="comet.native.snapshot-projection-overflow.v2",up=/^[a-f0-9]{64}$/u,pn=1024*1024,oO=128,sO=128;function Ge(e,t){return e<t?-1:e>t?1:0}function sp(e){if(!up.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cO(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function Rr(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=Rb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Rb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Hb(e,t){return e==="."?e:Rr(e,t)}function ga(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lO(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:Rr(e.path,`${t} path`),hash:e.hash,size:ga(e.size,`${t} size`),type:"file"}}function uO(e,t){return{path:Hb(e.path,`${t} path`),size:e.size===null?null:ga(e.size,`${t} size`),type:e.type,reason:e.reason}}function dO(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function fO(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ss(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
201
- `,"utf8")}function Pr(e,t,i){let r=`${t}
202
- ${Oo(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function hO(e){if(ss(e)<=pn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=jb("sha256");a.update(`${aO}
203
- `),e.omissionOverflow&&Pr(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Pr(a,"omission",f)},s=f=>{r+=1,n+=1,Pr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let 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(;ss(u)>pn;){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 m=c();if(m===null)break;o(m,!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 cp(e){let t=Ii(e),i=t.entries.map((n,a)=>lO(n,`Snapshot entry ${a}`));if(i.sort(dO),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)=>uO(n,`Snapshot omission ${a}`));return r.sort(fO),hO({schema:$b,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 cs(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:Rr(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)=>Ge(i.path,r.path)||Ge(i.kind,r.kind))}function ls(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Cb(e){return e?{hash:e.hash,size:e.size}:null}function dp(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:Ge(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:Cb(c),after:Cb(l)})}}function Db(e,t){return{...e,attributedTo:t.filter(i=>ls(i,e.path))}}function fp(e){let t=cs(e.declaredArtifacts),i=[];return dp(e.baseline,e.current,r=>{i.push(Db(r,t))}),i}function Oi(e,t){return{id:`scope:${D(rO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function pO(e,t){let i=t.omitted.map(r=>Oi({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(Oi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Oi({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 xb(e,t){return pO(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function lp(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||cO(e.path,t.path)||Ge(e.id,t.id)}function mO(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(lp)}function Lb(e){return[...new Set(e.map((t,i)=>Rr(t,`Git path ${i}`)))].sort(Ge)}function Ab(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 vO(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 Mb(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Lb(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Ab(e.baseCommit,"Native external drift base commit"),targetBranch:vO(e.targetBranch,"Native external drift target branch"),targetCommit:Ab(e.targetCommit,"Native external drift target commit"),paths:t}}function Fb(e){if(typeof e.contractHash!="string"||!up.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:cs(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Lb(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Mb(e.externalDrift)}}}function gO(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 dp(e,t,h=>{let v=i.some(m=>ls(m,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<oO){let m=Db(h,i),p=ss(m);l+p<=pn?(a.push(m),l+=p):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Bb(e,t){return Oi({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 wO(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:ga(Number(t[1]),"Scope overflow change count"),unresolved:ga(Number(t[2]),"Scope overflow unresolved count"),unattributed:ga(Number(t[3]),"Scope overflow unattributed count")},r=hn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Bb(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function yO(e){let t=jb("sha256");t.update(`${nO}
204
- `);let i=0;dp(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Pr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)ls(o,n.path)&&(a+=1,Pr(t,"change-attribution",o));Pr(t,"change-end",{attributionCount:a}),a===0&&Pr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Pr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Vb(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=gO(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(F=>ls(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(as,e),c=D(as,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=sO)break;l.push(Oi({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...xb("baseline",e),...xb("current",t),...o.totalChanges===0&&a===null?[Oi({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(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},v=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(Vt=>Vt.attributedTo.length===0&&!u.has(Vt.path)),P=o.totalChanges-N.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Fe=F+$,ue=[...w.map(Vt=>Oi({kind:"unattributed-change",source:"implementation-scope",path:Vt.path,evidence:{after:Vt.after,before:Vt.before,changeKind:Vt.kind}},`Changed path is not covered by a declared artifact: ${Vt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Fe>0?[Bb(R.overflowHash,{changes:P,unattributed:F,unresolved:Fe})]:[]],te=mO(ue),ai=R.includeGitAdvisory?h():void 0;return{schema:op,contractHash:r,baselineProjectionRef:sp(s),baselineProjectionHash:s,currentProjectionRef:sp(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:te,noCodeReason:a,...ai?{gitAdvisory:ai}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(ss({...R,scopeHash:g})<=pn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let E=o.totalChanges>m||d>p?yO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:E}),S={...k,scopeHash:D(Ob,k)};if(ss(S)>pn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function hp(e){let t=cp(e.baseline),i=cp(e.current),r=Fb(e);return{authority:r,baseline:t,current:i,scope:Vb(t,i,r)}}var NO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wi(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 hn(e,t){if(typeof e!="string"||!up.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _b(e,t,i){let r=sp(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function wa(e,t){let i=gi(e,"Native snapshot projection");if(wi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==$b)throw new Error("Native snapshot projection schema is invalid");let r=Ii({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=cp(r);if(D(as,i)!==D(as,n))throw new Error("Native snapshot projection is not canonical");let a=D(as,n);if(t!==void 0&&hn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function pp(e,t){let i=gi(e,`Declared artifact ${t}`);if(wi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Rr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Tb(e,t){if(e===null)return null;let i=gi(e,t);return wi(i,["hash","size"],[],t),{hash:hn(i.hash,`${t} hash`),size:ga(i.size,`${t} size`)}}function Ib(e,t){let i=gi(e,`Implementation change ${t}`);if(wi(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(pp),n=cs(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Tb(i.before,`Implementation change ${t} before`),o=Tb(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:Rr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function bO(e,t){let i=gi(e,`Unresolved scope ${t}`);wi(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"?Hb(i.path,`Unresolved scope ${t} path`):Rr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function os(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)=>Rr(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function qb(e){let t=gi(e,"Native implementation external drift");if(wi(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=os(t.paths,"Native external drift paths");return Mb({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function ya(e){let t=gi(e,"Native implementation scope"),i=[...NO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(wi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==op)throw new Error("Native implementation scope schema is invalid");let r=hn(t.contractHash,"Implementation scope contractHash"),n=hn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_b(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=hn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_b(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(pp);if(JSON.stringify(c)!==JSON.stringify(cs(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Ib),u=[...l].sort((w,P)=>Ge(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>ls(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Ib),h=t.externalDrift===void 0?void 0:qb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map(bO),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:wO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,E=[...m.map(w=>Oi({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&y===null?[Oi({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=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(lp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(E.sort(lp))||t.complete!==(p.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let S;if(t.gitAdvisory!==void 0){let w=gi(t.gitAdvisory,"Implementation scope Git advisory");if(wi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=os(w.changedPaths,"Git changed paths"),F=os(w.pathsPresentInSnapshotChanges,"Git present paths"),$=os(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Fe=[...F,...$].sort(Ge);if(JSON.stringify(Fe)!==JSON.stringify(P)||$.some(ue=>l.some(te=>te.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:op,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:y,...S?{gitAdvisory:S}:{},...h?{externalDrift:h}:{}},N=hn(t.scopeHash,"Implementation scope scopeHash");if(D(Ob,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function kO(e){let t=gi(e,"Native implementation scope authority");if(wi(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(pp);if(JSON.stringify(i)!==JSON.stringify(cs(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=os(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:qb(t.externalDrift),a=Fb({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 us(e){let t=gi(e,"Native implementation scope bundle");wi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=kO(t.authority),r=wa(t.baseline),n=wa(t.current),a=ya(t.scope),o=Vb(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 Wb(e){let t=ya(e.scope);return us({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 zb from"node:path";var SO=/\b(Bearer|Basic)\s+[^\s"']+/giu,EO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,PO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,RO=/\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,CO=/("(?:[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,xO=/(["'])((?:[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,AO=/\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 $t(e){return e.replace(SO,"$1 [REDACTED]").replace(EO,"[REDACTED PRIVATE KEY]").replace(PO,"$1[REDACTED]@").replace(RO,"[REDACTED TOKEN]").replace(CO,'$1"[REDACTED]"').replace(xO,"$1$2$1$3$4[REDACTED]$4").replace(AO,"$1$2[REDACTED]")}var Gb=/^[a-f0-9]{64}$/u;var _O="comet.native.acceptance-trace.v2",TO="comet.native.partial-allowance.v1",IO="comet.native.verification-evidence.v2";function Hi(e,t){if(!Gb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ub(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Kb(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 mp(e,t,i=2e3){let r=$t(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ds(e,t){let i=zb.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})||zb.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 jO(e,t,i){let r=ds(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ci(r),a=r.toLowerCase(),o=i?ds(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 vp(e){let t=ds(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 Na(e,t){return e<t?-1:e>t?1:0}function tu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function iu(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 Yb(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 Jb(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 $O(e){let t=tu(e,"Native acceptance trace");if(iu(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"||!Gb.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=ds(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=tu(o,`Native acceptance trace entry ${s}`);if(iu(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=>vp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Na))||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:ds(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:mp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Na(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=Hi(t.traceHash,"Native acceptance trace hash");if(D(_O,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function ru(e){let t=tu(e,"Native partial allowance");if(iu(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(Na))||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:Kb(t.change),scopeHash:Hi(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:mp(t.reason,"Partial allowance reason"),confirmedSummary:mp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ub(t.sourceRevision),confirmedAt:Yb(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=Hi(t.allowanceHash,"Native partial allowance hash");if(D(TO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function fs(e){let t=tu(e,"Native verification evidence");if(iu(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=Hi(t.implementationScopeHash,"Native verification implementation scope hash"),r=$O(t.acceptanceTrace),n=Hi(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:Hi(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>vp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Na)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Na);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=>vp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Na)))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:Kb(t.change),sourceRevision:Ub(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Hi(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Jb(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:jO(t.reportRef,"Native verification report ref"),reportHash:Hi(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Jb(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Yb(t.createdAt,"Native verification timestamp")},d=Hi(t.envelopeHash,"Native verification envelope hash");if(D(IO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Xb from"node:path";var Qb="comet.native.check-receipt.v1",OO="comet.native.check-receipt.v1",ba="scoped-text-safety",gp=1,dt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),HO=/^[a-f0-9]{64}$/u,DO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LO="comet.native.checker-policy.v1",MO="comet.native.check-input.v1",FO=2048,Zb=D(LO,{policy:ba,version:gp,limits:dt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),BO=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),ek=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],ik=["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"],VO=new Set(ik);function Cr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xr(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 Di(e,t){if(typeof e!="string"||!HO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rk(e,t){let i=St(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function tk(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 qO(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>FO||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=Xb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Xb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function WO(e){let t=Cr(e,"Native check receipt checker");xr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Cr(t.limits,"Native check receipt limits");if(xr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ba||t.version!==gp||t.hash!==Zb||i.maxFiles!==dt.maxFiles||i.maxFileBytes!==dt.maxFileBytes||i.maxTotalBytes!==dt.maxTotalBytes||i.maxIssues!==dt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ba,version:gp,hash:Zb,limits:{...dt}}}function zO(e){let t=Cr(e,"Native check receipt contract");return xr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Di(t.expectedHash,"Native check expected contract hash"),beforeHash:Di(t.beforeHash,"Native check before contract hash"),afterHash:Di(t.afterHash,"Native check after contract hash")}}function JO(e){let t=Cr(e,"Native check receipt implementation");return xr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Di(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Di(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Di(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Di(t.afterSnapshotHash,"Native check after snapshot hash")}}function GO(e,t){let i=Cr(e,`Native check batch ${t}`);xr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:St(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:St(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:St(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:St(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:St(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:St(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>dt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>dt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function UO(e){let t=Cr(e,"Native check receipt counts");xr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:St(t.filesSelected,"Native check filesSelected"),filesScanned:St(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:St(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:St(t.bytesScanned,"Native check bytesScanned"),issueCount:St(t.issueCount,"Native check issueCount"),recordedIssueCount:St(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(GO):(()=>{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>dt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>dt.maxFiles||i.bytesScanned>dt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function KO(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||ek.indexOf(e.kind)-ek.indexOf(t.kind)}function YO(e){if(!Array.isArray(e)||e.length>dt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Cr(r,`Native check issue ${n}`);if(xr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!BO.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:qO(a.path,`Native check issue ${n} path`),line:rk(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(KO);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function XO(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!VO.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=ik.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 QO(e){return D(MO,e)}function nu(e){let t=Cr(e,"Native check receipt");if(xr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Qb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!DO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=rk(t.sourceRevision,"Native check source revision"),r=WO(t.checker),n=zO(t.contract),a=JO(t.implementation),o=QO({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Di(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=tk(t.startedAt,"Native check receipt startedAt"),c=tk(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=UO(t.counts),u=YO(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=XO(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>dt.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>dt.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Qb,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=Di(t.receiptHash,"Native check receipt content hash");if(D(OO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var yp="comet.native.verification-receipt.v3",ZO=yp,e0="comet.native.declared-artifacts.v1",t0=/^[a-f0-9]{64}$/u,i0=/^acceptance-[a-f0-9]{64}$/u,r0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,n0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,a0=4096,o0=256,s0=1024;function ka(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 Ar(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 Li(e,t){if(typeof e!="string"||!t0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ii(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=$t(e).trim();if(!i||i.length>a0||i!==e.trim())throw new Error(`${t} is invalid`);return i}function wp(e,t){let i=ii(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 hs(e,t,i=ii,r=!1,n=o0){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 c0(e,t){if(typeof e!="string"||!i0.test(e))throw new Error(`${t} is invalid`);return e}function l0(e){let t=ka(e,"Native verification receipt bindings");if(Ar(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!r0.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:Li(t.contractHash,"Native verification receipt contract hash"),scopeHash:Li(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Li(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Li(t.artifactHash,"Native verification receipt artifact hash")}}function u0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=n0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function d0(e,t,i,r){let n=ka(t,`Native ${e} evidence`);if(e==="automated-check"){if(Ar(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=wp(n.startedAt,"Native automated-check start time"),o=wp(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=ka(n.worktree,"Native automated-check worktree");if(Ar(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=ka(n.afterFence,"Native automated-check after fence");if(Ar(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:ii(n.executable,"Native automated-check executable"),args:hs(n.args,"Native automated-check arguments",ii,!0),cwd:ii(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:ii(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Li(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Li(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Li(n.outputHash,"Native automated-check output hash"),outputSummary:ii(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Ar(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=u0(n.checkReceiptRef);if(Li(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:hs(n.subjects,"Native static inspection subjects",ii,r==="required-check"),rule:ii(n.rule,"Native static inspection rule"),resultSummary:ii(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Ar(n,["steps","observations"],"Native manual-evidence evidence"),{steps:hs(n.steps,"Native manual evidence steps"),observations:hs(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function f0(e){let t=ka(e,"Native verification receipt");if(Ar(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=ii(t.actor,"Native verification receipt actor"),o=hs(t.acceptanceIds,"Native receipt acceptance IDs",c0,r==="required-check",s0).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:yp,kind:i,role:r,status:n,bindings:l0(t.bindings),acceptanceIds:o,actor:a,issuedAt:wp(t.issuedAt,"Native verification receipt issue time"),evidence:d0(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ba||s.actor!==`native-runtime:${ba}`))throw new Error("Native required check policy identity is invalid");return s}function au(e){let t=ka(e,"Native verification receipt");if(Ar(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==yp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=f0(r),a=Li(t.receiptHash,"Native verification receipt hash");if(D(ZO,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Np(e){return D(e0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var sk=/^[a-f0-9]{64}$/u,_r=pn,_z=3*_r;function bp(e,t){let i=yi.relative(e,t);return i===""||!yi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${yi.sep}`)}function p0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ou(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function nk(e){let t=await ri.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ri.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function m0(e,t){let i=yi.resolve(e),r=yi.resolve(t);if(!bp(i,r))throw new Error("Native evidence path is outside its change");let n=[await nk(i)],a=i;for(let o of yi.relative(i,r).split(yi.sep).filter(Boolean)){a=yi.join(a,o);let s=await nk(a);if(!bp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ak(e){for(let t of e){let i=await ri.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!p0(t,i)||await ri.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function v0(e,t,i={}){let r=await m0(t,yi.dirname(e));await i.afterParentChainCaptured?.();let n=await ri.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ri.realpath(e);if(!bp(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ri.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ri.lstat(e),ri.realpath(e)]);if(await ak(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ou(s,n)||!ou(s,c))throw new Error("Native evidence document changed while opening");if(s.size>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=_r+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ri.lstat(e),ri.realpath(e)]);if(await ak(r),!v.isFile()||v.isSymbolicLink()||m!==a||!ou(s,h)||!ou(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 Ea(e,t){if(!sk.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ck(e){return Ea("reports",e)}async function g0(e,t,i,r,n){if(!sk.test(i))throw new Error("Native report evidence hash is invalid");let a=await mn({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"||h0("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 Sa(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 w0(e,t,i,r,n){let a=Ea(i,r);return n?yi.join(n,...a.split("/")):lr(H(e,t),a)}async function mn(e){let t=w0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),v0(t,i,e.hooks)}function ok(e,t){return wa(e,t)}function y0(e,t){let i=ya(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function N0(e,t,i){let r=ru(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function b0(e,t,i){let r=fs(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function k0(e,t,i,r=!1,n){let a=await su(e,t,i.implementationScopeRef,void 0,n);if(r&&await g0(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 lk(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 ps(e,t,i,r,n){let a=Sa(i,"scopes"),o=y0(await mn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Sa(o.baselineProjectionRef,"snapshots"),c=Sa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([mn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ok(d,s)),mn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ok(d,c))]);return Wb({baseline:l,current:u,scope:o})}async function su(e,t,i,r,n){return(await ps(e,t,i,r,n)).scope}async function lk(e,t,i,r,n){let a=Sa(i,"allowances");return N0(await mn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ms(e,t,i,r,n){let a=Sa(i,"receipts"),o=au(await mn({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 Pa(e,t,i,r,n){let a=Sa(i,"verifications"),o=b0(await mn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await k0(e,t,o,!1,n),o}var S0=4096;async function E0(e,t=ut.maxChanges){try{let i=await wt({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 uk(e,t){let i=await He(e,t),[r,n]=await Promise.all([i.implementation_scope?su(e,t,i.implementation_scope):null,kt(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 cu(e,t,i={}){let n=(await E0(e,S0)).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 uk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await uk(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Pb([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 B0}from"fs";import V0 from"path";import{isDeepStrictEqual as uu}from"util";var Ra={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var P0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function R0(e,t){return e<t?-1:e>t?1:0}function C0(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"||!P0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(R0)}function kp(e=[]){return C0(e,"Native repair failed check IDs",Ra.maxFailedCheckIds,!0)}function dk(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function x0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:dk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&dk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Sp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(x0(r,a))break;i+=1,r=a}return i}function Ep(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 fk="repairStagnation",Et={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},_0=/^[a-f0-9]{64}$/u;var T0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),I0=["data","runId","sequence","timestamp","type"],hk=["disposition","overrideSummaryHash","signatureHash"],j0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],pk=12;function Rp(e,t){return e<t?-1:e>t?1:0}function mk(e,t,i){let r=Object.keys(e).sort(Rp);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function lu(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 vs(e,t){if(typeof e!="string"||!_0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $0(e){if(!Array.isArray(e)||e.length>Ra.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(Rp)}function vk(e){if(typeof e!="string"||e.length===0||e.length>Et.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 Pp(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Et.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Et.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>Et.maxTextCharacters&&(!n||e.length>Et.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Et.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>Et.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Pp(s,t+1,i,`${r}[${c}]`));return}let a=lu(e,r),o=Object.keys(a);if(o.length>Et.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Et.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Pp(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function O0(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 H0(e,t,i){let r=lu(e,`Native repair trajectory event ${t+1}`);if(mk(r,I0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(O0(r.timestamp),typeof r.type!="string"||!T0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(vk(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 Pp(r.data,0,n,"Native trajectory event data"),lu(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Cp(e){let t=lu(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Rp),r=i.length===hk.length&&i.every((l,u)=>l===hk[u]);r||mk(t,j0,"Native repair trajectory projection");let n=vs(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:vs(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=vs(t.contractHash,"Native repair trajectory contract hash"),s=$0(t.failedAcceptanceIds),c=kp(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 D0(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 L0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??pk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Sp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Ra.warningAtConsecutiveFailures?"continue":a<Ra.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function M0(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??pk;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 gk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Et.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=vk(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=H0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Et.maxTotalDataNodes||c>Et.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?vs(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?vs(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,fk)){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=Cp(f[fk]);if(D0(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),L0(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");M0(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Ra.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function wk(e){return gk(e).history}function yk(e){let t=gk(e).latestProjection;return t?{...t}:null}var Ni={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:[]},gs=L("comet-native-runtime:v3:scope-reopen"),F0=[{skillVersion:"3",skillHash:L("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:L("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:L("comet-native-runtime:v1")}];function Nk(e){return e.skillVersion===Ni.definition.metadata.version&&e.skillHash===gs||F0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var xp={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 Tr(e){let i={sequence:(await it(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await FN(e.changeDir,e.run.trajectoryRef,i),i}async function vn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:L(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await BN(e.changeDir,e.run.checkpointRef,t),t}function bk(e){return L(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 Ak=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],q0=new Set(Ak),_k=new Set([...Ak,"minimum_runtime_version","revision"]),W0=new Set([..._k,"operation"]),z0=512*1024,Ap=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),J0=new Set([...Ap,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),ws=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 Ue(e,t){return V0.join(H(e,t),"transition.json")}function G0(e){return`transition-${e}`}async function U0(e,t,i){let r=G0(t);return dr(e,r,i)}async function gn(e,t,i,r){let n=await U0(e,t,i);try{return await r()}finally{await fr(n)}}function fu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Tp(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 du(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function bi(e,t){return uu(e,t)}function _p(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=>!J0.has(u)),a=[...Ap].find(u=>!Object.hasOwn(i,u)),o=Ap.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(Ep(i.summary,"Native transition journal event summary"),$t(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&&(Ep(i.noCodeReason,"Native transition journal event no-code reason"),$t(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")?Cp(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 K0(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 _p({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return _p(e,t)}function Ip(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?K0(e.eventData,e.evidenceHash):_p(e.eventData,e.evidenceHash),n=Er(e.nextRun),a=e.previousRun===null?null:Er(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function kk(e,t,i=!1){if(e.skill!==Ni.definition.metadata.name||(i?!Nk(e):e.skillVersion!==Ni.definition.metadata.version||e.skillHash!==gs)||e.orchestration!==Ni.definition.orchestration.mode||e.pendingRef!==Nt.pendingRef||e.trajectoryRef!==Nt.trajectoryRef||e.contextRef!==Nt.contextRef||e.artifactsRef!==Nt.artifactsRef||e.checkpointRef!==Nt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Sk(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 Ek(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 jp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(kk(o,"next Run",r||a!==null),Ek(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(kk(a,"previous Run",!0),Ek(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(!uu(Sk(a),Sk(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Y0(e,t,i){return L(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Tk(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Pk(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function $p(e,t,i,r,n=!1){let a=i.eventData,o=Pk(e),s=Pk(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&&uu(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&&uu(e.spec_changes,t.spec_changes),l=bk({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=Y0(e.name,a.summary,t.spec_changes),l=L(`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 Op(e,t){let i=fu(e);if(Tp(i,W0),i.schema!==pr)throw new Error(`Expected Native transition schema ${pr}`);let r=du(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 ${pr} minimum_runtime_version must be ${3}`);let n=du(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=Ip(i,t),o=lt(i.previousState),s=lt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if($p(o,s,a,i.operation),jp(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:pr,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 X0(e,t){let i=fu(e);if(Tp(i,q0),i.schema!==an)throw new Error(`Expected Native transition schema ${an}`);let r=Ip(i,t,!0),n=on(i.previousState),a=on(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return $p(n,a,r,Tk(n,a,r.eventData),!0),jp(n,a,r,!0),{schema:an,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function Hp(e,t){let i=fu(e);if(Tp(i,_k),i.schema!==Ti)throw new Error(`Expected Native transition schema ${Ti}`);if(du(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ti} minimum_runtime_version must be 2`);let n=du(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ip(i,t,!0),o=di(i.previousState),s=di(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if($p(o,s,a,Tk(o,s,a.eventData),!0),jp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ti,minimum_runtime_version:2,revision: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 Q0(e,t){let i=fu(e);if(i.schema===pr)return{status:"current",journal:Op(i,t)};if(i.schema===an)return{status:"migration-required",journal:X0(i,t)};if(i.schema===Ti)return{status:"migration-required",journal:Hp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Dp(e,t){let i=Ue(e,t),r=j(e,i);await T(r,i);try{let n=await re({root:r,file:i,maxBytes:z0,label:`Native transition journal ${t}`});return Q0(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Mi(e,t){let i=await Dp(e,t);if(!i)return null;if(i.status==="migration-required")throw new ws(t);return i.journal}function Rk(e,t){if(bi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(bi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Ck(e,t){if(bi(e,t.nextState))return"next";if(bi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function Z0(e){let{journal:t}=e;return Ik({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 Ik(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function xk(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=Z0({sequence:a.index+1,journal:t,type:a.event.type});if(!bi(Ik(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 hu(e,t,i){if(await pa(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Wl(e,t);let r=await Mi(e,t);if(!r)return null;let n=H(e,t),a=xk(await it(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([$e(n),He(e,t)]),c=Rk(o,r),l=Ck(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 un(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!bi(await $e(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await Ql(e,r.nextState,r.previousState.revision);if(!bi(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!bi(await He(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Mi(e,t);if(!u||!bi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=xk(await it(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Tr({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 Tr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await vn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([$e(n),He(e,t)]);Rk(h,{...r,previousRun:r.nextRun}),Ck(v,{...r,previousState:r.nextState});let m=await Mi(e,t);if(!m||!bi(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await B0.rm(Ue(e,t),{force:!0}),r.nextState}async function jk(e,t,i){return se(e,`continue transition ${t}`,()=>gn(e,t,`continue transition ${t}`,()=>hu(e,t,i)))}import $k from"node:path";var eH="comet.native.contract.v1",tH="comet.native.acceptance-set.v1",Ok=/^[a-f0-9]{64}$/u,ys={maxAcceptanceCriteria:Do.maxCriteria};function Hk(e,t){let i=$k.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})||$k.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 Dk(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
205
- `))}function iH(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(Ok))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(Ok))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Hk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Dk(e.markdown)},markdown:e.markdown}}function rH(e,t){return Lk(e.id,t.id)}function Lk(e,t){return e<t?-1:e>t?1:0}function Mk(e){let t=Hk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(iH).sort((d,f)=>Lk(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=dl(e.briefMarkdown,t,ys.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...fl(f,d.source,ys.maxAcceptanceCriteria-a.length)),a.push(...Ay(f,d.source,ys.maxAcceptanceCriteria-a.length)));if(a.sort(rH),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>ys.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${ys.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:Dk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(tH,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(eH,u)}}var pu={maxSpecs:64,maxFileBytes:So,maxTotalBytes:4*1024*1024};async function Ca(e){if(e.specChanges.length>pu.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Z({root:e.changeDir,ref:e.briefRef,maxBytes:pu.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 Z({root:e.changeDir,ref:n.source,maxBytes:pu.maxFileBytes});if(i+=a.size,i>pu.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:Mk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as kH}from"node:child_process";import{promisify as SH}from"node:util";var IJ=["$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 uH}from"fs";import xa from"path";var jr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Aa=/^[a-f0-9]{64}$/u;function mu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vu(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 Ir(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 Fk(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Lp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function nH(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||xa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=xa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Mp(e,t){return xa.join(H(e,t),"checkpoints","progress.json")}function $r(e,t){return xa.join(H(e,t),"checkpoint-journal.json")}function Fp(e,t,i){if(!Aa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return xa.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function aH(e){if(!Aa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Bp(e,t,i){let r=await re({root:e,file:t,maxBytes:jr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function oH(e,t){let i=mu(e,`checkpoint manifest artifact ${t}`);vu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=nH(Ir(i.path,`checkpoint artifact ${t} path`,4096)),n=ci(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Aa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Lp(i.size,`checkpoint artifact ${t} size`)}}function gu(e,t){let i=mu(e,"Native checkpoint manifest");if(vu(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>jr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(oH),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=Lp(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>jr.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 Vp(e){return L(JSON.stringify(gu(e,e.change)))}function qp(e,t){let i=mu(e,"Native progress checkpoint");if(vu(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=Fk(i.previousRevision,"Native checkpoint previousRevision"),a=Fk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Ir(i.manifestHash,"Native checkpoint manifestHash",64);if(!Aa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=aH(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Ir(i.inputHash,"Native checkpoint inputHash",64);if(!Aa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Ir(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Lp(i.artifactCount,"Native checkpoint artifactCount");if(u>jr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Ir(i.summary,"Native checkpoint summary"),f=Ir(i.nextAction,"Native checkpoint nextAction");if($t(d)!==d||$t(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Ir(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 sH(e,t){let i=mu(e,"Native checkpoint journal");if(vu(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=lt(i.previousState),n=lt(i.nextState),a=qp(i.checkpoint,t),o=gu(i.manifest,t),s=Ir(i.inputHash,"Native checkpoint journal inputHash",64),c=L(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Aa.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!==Vp(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 cH(e,t,i){let r=xa.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Kf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await re({root:e.projectRoot,file:r,maxBytes:jr.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 lH(e,t){let i=Mp(e,t),r=j(e,i);await T(r,i);try{return qp(await Bp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Wp(e,t,i){let r=Fp(e,t,i),n=j(e,r);await T(n,r);let a=await Bp(n,r,"Native checkpoint manifest"),o=gu(a,t);if(zp(e,o),Vp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Or(e,t){let i=$r(e,t),r=j(e,i);await T(r,i);try{let n=sH(await Bp(r,i,"Native checkpoint journal"),t);return zp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Bk(e,t,i,r){let n=gu(i,t);zp(e,n);let a=Vp(n),o=Fp(e,t,a),s=j(e,o);await T(s,o);try{let c=await Wp(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 ee(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function zp(e,t){for(let i of t.artifacts){let r=Kf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Vk(e,t){let i=qp(t,t.change),r=await Wp(e,i.change,i.manifestHash),n=L(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=Mp(e,t.change),o=j(e,a);await T(o,a),await ee(a,i,{containedRoot:o})}async function qk(e){let t;try{t=await lH(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:Mp(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 Wp(e.paths,e.name,t.manifestHash);let a=L(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 cH(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Fp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Wk(e,t,i){let r=await Or(e,t);if(!r)return null;if(await Bk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Ql(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Vk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await uH.rm($r(e,t),{force:!0}),r}async function zk(e,t,i){return se(e,`continue checkpoint ${t}`,()=>gn(e,t,`continue checkpoint ${t}`,async()=>(await hu(e,t),Wk(e,t,i))))}import{constants as Jp,promises as Ot}from"node:fs";import _a from"node:path";var dH=/^[a-f0-9]{64}$/u,fH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ns=512*1024;function hH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function pH(e,t){let i=_a.resolve(e),r=_a.resolve(t);if(!O(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",..._a.relative(i,r).split(_a.sep).filter(Boolean)]){o&&(a=_a.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(n.length>0&&!O(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 Jk(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!hH(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function mH(e){if(!dH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function vH(e){let t=fH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function gH(e,t,i){return lr(H(e,t),mH(i))}async function wH(e,t,i){let r=await pH(i,_a.dirname(e)),n=await Ot.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Ns)throw new Error(`Native check receipt exceeds ${Ns} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Jp.O_RDONLY|Jp.O_NOFOLLOW|Jp.O_NONBLOCK,c=await Ot.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(),Ot.lstat(e),Ot.realpath(e)]);if(await Jk(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!wu(n,l)||!wu(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=Ns+1-h,y=await c.read(v,0,Math.min(v.length,g),null);if(y.bytesRead===0)break;if(h+=y.bytesRead,h>Ns)throw new Error(`Native check receipt exceeds ${Ns} bytes`);f.push(Buffer.from(v.subarray(0,y.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Jk(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!wu(l,m)||!wu(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Gk(e,t,i){let r=vH(i),n=H(e,t),a=gH(e,t,r),o=j(e,a);await T(o,a);let s=nu(await wH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var bs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var CG=64*1024;var xG=3600*1e3;var AG=SH(kH);var EH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Uk(e,t){let i=[];for(let r of EH){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 Kk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Gk(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 Hr=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 PH(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 RH(e){let t=PH(e.bundle.baseline),i=await qh(e.paths,t,{origin:"explicit",now:e.now});return hp({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 Xk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ps(e.paths,e.state.name,e.state.implementation_scope),i=await Ca({changeDir:ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await RH({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 Qk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Xk(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 CH(e){let t=await Z({root:ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Ty(t.text)}}function xH(e){let{receipt:t,implementationScope:i}=e,r=[],n=fp({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 AH(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:Np(e.implementationScope.scope.declaredArtifacts)}}async function Yk(e){let t=await ms(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Uk(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 Hr([{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 Kk({paths:e.paths,state:e.state,receipt:t});if(n){let a=xH({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 _H(e){let t=AH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Yk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Hr)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 Yk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Hr)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 Hr(i)}function Gp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function yu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Gp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Xk(e),Pa(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:Gp(e.state.verification_result,"stale"),envelope:null};let r=await CH({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 _H({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:Gp(e.state.verification_result,"invalid"),envelope:null}}}function IH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function eS(e){try{return await TH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jH(e,t){try{return(await Z({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function $H(e,t,i){let r=Zl(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Zk.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await jH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Z({root:ne(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 OH(e,t){return eS(Ue(e,t))}async function Nu(e){let t=e.now??new Date,i=await He(e.paths,e.name),r=await kt(e.paths,e.name),n=await ye(e.paths.projectRoot),a=IH(i.name,t),o=Zk.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(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=>$H(e.paths,i.name,v))),yu({paths:e.paths,state:i,now:t}),cu(e.paths,i.name),pa(e.paths,i.name),ma(e.paths,i.name),OH(e.paths,i.name),eS(o)]);return yb({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 Up}from"node:fs";import Fi from"node:path";var HH="comet.native.archive-tree.v1",DH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function rS(e){let t={...DH,...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 tS(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 iS(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 nS(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await wt({root:e,directory:t,label:`Native Archive content directory ${Fi.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=tS(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Fi.join(t,u.name),f=Fi.relative(e,d).replaceAll("\\","/"),h=await Up.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()){iS(i,{ref:f,kind:"directory"},r,n),await nS(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 re({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`);iS(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await wt({root:e,directory:t,label:`Native Archive content directory ${Fi.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(tS(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Fi.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function aS(e,t={}){let i=rS(t);e=Fi.resolve(e);let r=await Up.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await nS(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 L(`${HH}\0${o}`)}async function ni(e,t={}){let i=rS(t);e=Fi.resolve(e);let r;try{r=await Up.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 re({root:Fi.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Fi.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await aS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as rt}from"node:fs";import xe from"node:path";var Yp=16*1024*1024,LH=256*1024,MH=16*1024,ks="comet.native.archive-cas.v1";function FH(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=xe.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function De(e,t){let i=FH(e,t);return T(j(e,i),i)}function Dr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Ta(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ft(e){let t=await ni(e.target);if(!Dr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Ta(t)}`);return t}async function Xp(e,t){let i=await hi(e,t),r=await re({root:e.runtimeDir,file:i.journal,maxBytes:LH,label:`Native Archive transaction journal ${t}`}),n=xl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function bu(e,t,i){let r=xl({...t,status:i}),n=await hi(e,r.id);return await ee(n.journal,r,{containedRoot:e.runtimeDir}),r}function ku(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function oS(e){return{...ku(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function BH(e,t){return Lr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ie(e){try{return await rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ki(e){let t=await rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=oS(t),r=await re({root:j(e.paths,e.file),file:e.file,maxBytes:Yp,label:e.label}),n=await rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!BH(i,oS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:ku(n),size:r.size}}function VH(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!==ks||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:ks,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Si(e,t,i,r){let n=await hi(e,t.id),a=xe.join(n.backups,".cas"),o=`.${xe.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:xe.join(a,`${i.id}.original.json`),postRecord:xe.join(a,`${i.id}.post.json`),candidate:xe.join(a,`${i.id}.candidate`),originalQuarantine:xe.join(xe.dirname(r),`${o}.original`),rollbackQuarantine:xe.join(xe.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Ht(e){if(!await ie(e.file))return null;let t=await re({root:e.paths.runtimeDir,file:e.file,maxBytes:MH,label:`Archive CAS ${e.operation.id} ${e.role} record`});return VH(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Su(e){let t=await Ht(e);if(t){if(!Lr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await fi({root:e.paths.runtimeDir,directory:xe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ks,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ee(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ht(e);if(!r||!Lr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Re(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Lr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function qH(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Su({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Re({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function WH(e){if(!await ie(e.quarantine)||await ie(e.target))return;let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([rt.lstat(e.quarantine),rt.lstat(e.target)]);if(!Lr(ku(i),ku(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rt.unlink(e.quarantine),await t.verify()}async function uS(e){if(await ie(e.quarantine)){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Re({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 Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rt.rename(e.target,e.quarantine),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await WH(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 wn(e){if(!await ie(e.file))return;await Re(e);let t=await Qt({root:j(e.paths,e.file),directory:xe.dirname(e.file),label:e.label});await t.verify(),await Re(e),await rt.unlink(e.file),await t.verify()}async function sS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await De(e,t.target),n=await De(e,t.backup),a=await ni(n);if(a!==null){if(!Dr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ft({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await wr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Yp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ft({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function dS(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 Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ie(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Re({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await sS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await qH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await sS(e.paths,e.operation,e.hooks),await uS({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 cS(e){let t=await Si(e.paths,e.journal,e.operation,e.target);return await ie(t.candidate)?(await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await fi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await wr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Yp,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 zH(e){let t=e.operation.stagedHash,i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ie(e.target))return await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ie(i.candidate)&&await wn({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ie(e.target)){let c=await cS(e),l=await ki({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Lr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Su({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await wn({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await cS(e),a=await ki({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await fi({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Re({paths:e.paths,file:n,operation:e.operation,record:{schema:ks,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rt.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 ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Lr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Su({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await wn({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function JH(e,t,i,r){let n=await De(e,i.target),a=await De(e,i.staged);if(await ft({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Si(e,t,i,n);(!await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ie(n))&&await dS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await ni(n);if(o!==null&&!Dr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Ta(o)}`)}await zH({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ft({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function GH(e,t,i,r){let n=await De(e,i.target);await dS({paths:e,journal:t,operation:i,target:n,hooks:r}),await ft({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function UH(e,t){let i=await De(e,t.source),r=await De(e,t.target),[n,a]=await Promise.all([ni(i),ni(r)]);if(!(n===null&&Dr(a,t.expectedSourceHash,"directory"))){if(!Dr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Ta(n)}, target=${Ta(a)}`);await rt.mkdir(xe.dirname(r),{recursive:!0}),await rt.rename(i,r),await ft({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function KH(e,t,i,r){return i.type==="write"?JH(e,t,i,r):i.type==="remove"?GH(e,t,i,r):UH(e,i)}function YH(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 XH(e,t,i,r){let n=await De(e,i.target);if(i.type==="write"){let a=await De(e,i.staged);await ft({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Si(e,t,i,n),s=await Ht({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 Re({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ft({target:await De(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ht({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 ie(o.originalQuarantine))await Re({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 ft({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ft({target:await De(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Si(e,t,i,n),o=await Ht({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 ie(a.originalQuarantine))await Re({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 ft({target:await De(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ft({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function fS(e,t,i){let r=t.status==="prepared"?await bu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Nr(e,r.id),a=YH({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 XH(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 Tt(e,r.id,"operation-started",l.id),await KH(e,r,l,i),await Tt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Xp(e,r.id),r}async function QH(e){try{return await Re(e),!0}catch{return!1}}async function ZH(e){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rt.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 Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Kp(e){if(e.operation.type!=="write")return;let t=await Si(e.paths,e.journal,e.operation,e.target);if(!await ie(t.candidate))return;let i=await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await wn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ks,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function eD(e,t,i,r){let n=await De(e,i.target),a=await Si(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ht({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ie(a.candidate)&&await ie(n)){let l=await ki({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await ki({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Lr(l.identity,u.identity)&&(c=await Su({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Re({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ie(n)&&!(s!==null&&await QH({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ni(n);if(Dr(u,o)){await Kp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await uS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ie(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ie(n)){if(!s||!await ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await ZH({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ie(a.originalQuarantine)&&await wn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ie(a.rollbackQuarantine)&&await wn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Kp({paths:e,journal:t,operation:i,target:n}),await ft({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function tD(e,t){let i=await De(e,t.source),r=await De(e,t.target),[n,a]=await Promise.all([ni(i),ni(r)]);if(!(Dr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Dr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Ta(n)}, target=${Ta(a)}`);await rt.mkdir(xe.dirname(i),{recursive:!0}),await rt.rename(r,i)}}async function hS(e,t,i){let r=await Nr(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 bu(e,t,"rolling-back");await Tt(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 tD(e,o):await eD(e,n,o,i));return await Tt(e,n.id,"rollback-completed"),n=await bu(e,n,"rolled-back"),n}async function lS(e,t,i){let r=await De(e,i.target);if(i.type==="write"){let n=await Si(e,t,i,r),a=await Ht({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 Re({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ft({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function iD(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await De(e,i.target),n=await Si(e,t,i,r);if(await ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await lS(e,t,i),i.expectedTargetHash!==null){let a=await Ht({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 ie(n.originalQuarantine)&&await wn({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Kp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await lS(e,t,i)}async function Eu(e,t,i){return i==="commit"&&await iD(e,t),await Tt(e,t.id,i),i==="commit"?bu(e,t,"committed"):t}var SU=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as rD}from"fs";import nD from"path";var Qp="comet.selection.v2",aD=16*1024;function Pu(e){return nD.join(e,".comet","current-change.json")}function oD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pS(e){return e===null||typeof e=="string"}function sD(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(!oD(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&&!pS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Qp,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Qp)throw new Error(`current change selection schema must be ${Qp}`);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(!pS(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 Zp(e){let t;try{let r=Pu(e),{bytes:n}=await en(r,aD,{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",...sD(t)}}async function mS(e){await rD.rm(Pu(e),{force:!0})}async function vS(e,t,i){let r=await Zp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await mS(e),!0)}import{promises as _s}from"node:fs";import Vr from"node:path";var om=Rn(Qr(),1);import{promises as HS}from"node:fs";import Dt from"node:path";import{execFileSync as cD}from"node:child_process";var lD=3e4,uD=8*1024*1024,em=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 dD(e,t){try{return cD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:lD,maxBuffer:uD,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new em(e,t,r)}}function Ae(e,t){return dD(e,t).trim()}function Ss(e){return Ae(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import Le from"node:path";import{promises as xu}from"node:fs";import Ru from"node:path";function gS(...e){if(e.length===0)return Ru.resolve();if(Ru.win32.isAbsolute(e[0])){let t=Ru.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Ru.resolve(...e)}var Cu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var im="comet.native.supervisor.v2",fD=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function hD(e,t){let i=Le.relative(Le.resolve(e),Le.resolve(t));return i===""||!Le.isAbsolute(i)&&!i.startsWith(`..${Le.sep}`)}function pD(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function mD(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return gS(e,".worktrees",`${t}-${i}`)}function bS(e,t){return Le.join(We(e,t),"supervisor")}function kS(e,t){return Le.join(bS(e,t),"state.json")}function SS(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==im)throw new Error(`Native Supervisor state schema must be ${im}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Es(t.integration.targetCommit,"Native Supervisor target commit"),Es(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Es(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Es(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Mr(e,t){try{let i=await xu.readFile(kS(e,t),"utf8"),r=JSON.parse(i);return SS(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ia(e,t){SS(t),await xu.mkdir(e.changesRuntimeDir,{recursive:!0}),await ee(kS(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Es(e,t){if(!fD.test(e))throw new Error(`${t} must be a Git commit`)}function rm(e){return structuredClone(e)}function ES(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function PS(e){Es(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:im,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function nm(e){let t=pD(e.parent),i=xi(e.paths.projectRoot,t);if(!i)return null;let r=xi(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Jt(e.paths.projectRoot).map(o=>Le.resolve(o)).find(o=>fe(o).currentBranch===t);if(!n)return null;let a=PS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return ES(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function RS(e){if(!Ss(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ae(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Le.resolve(t)!==Le.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=Ae(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return Ae(e.integration.worktree,["rev-parse","HEAD"])}async function vD(e){let t=xi(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if(RS(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ae(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=Ae(i.integration.worktree,["rev-parse","HEAD"]),a=rm(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},ES(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Ia(e.paths,a),a}async function Ps(e){let i=await Mr(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Jt(e.paths.projectRoot).map(v=>Le.resolve(v)).find(v=>fe(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!Ss(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=Ae(n,["rev-parse","HEAD"]);if((()=>{try{return Ae(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await yS({paths:e.paths,state:i,targetCommit:a});if(await NS({paths:e.paths,plan:v}),i.children.every(({status:p})=>p==="archived"))return await tm(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=rm(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await Ia(e.paths,m),await tm(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=RS(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=xi(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return Ae(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await vD({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await yS({paths:e.paths,state:i,targetCommit:c});l!==c&&Ae(n,["merge","--ff-only",i.integration.branch]);let f=Ae(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=rm(i);for(let v of h.children)v.status="archived";return await NS({paths:e.paths,plan:d}),h.stateVersion+=1,await Ia(e.paths,h),await tm(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function CS(e,t){return Le.join(bS(e,t),"cleanup.json")}function wS(e){let t=Jt(e.paths.projectRoot).map(s=>Le.resolve(s)),i=Le.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:mD(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Le.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(hD(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Ss(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=fe(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{Ae(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(ko(e.paths.projectRoot,s))try{Ae(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function yS(e){let t=CS(e.paths,e.state.parent);try{let r=JSON.parse(await xu.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=wS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=wS(e);return await ee(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function NS(e){for(let t of e.plan.worktrees){if(!Jt(e.paths.projectRoot).map(a=>Le.resolve(a)).includes(Le.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=fe(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);Ae(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)ko(e.paths.projectRoot,t)&&Ae(e.paths.projectRoot,["branch","-d",t])}async function tm(e,t){await xu.rm(CS(e,t),{force:!0})}function xS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var AS="children.yaml",Rs="comet.native.children.v1",ja="comet.native.children.v2",DS=ja,gD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_S=new Set(["schema","children"]),wD=new Set(["schema","acceptance_index","children"]),yD=new Set(["name","depends_on","covers"]),ND=new Set(["name","summary","depends_on"]),bD=new Set(["name","depends_on","covers"]);function _u(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Au(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){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function TS(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 am(e,t){let i=Dt.normalize(Dt.resolve(e)),r=Dt.normalize(Dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function kD(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 IS(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 SD(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===DS&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);r.missing=n.filter(c=>!(c in e.acceptance_index)),r.extra=a.filter(c=>!n.includes(c));let o=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),u=e.acceptance_index[c];l&&u&&(u.source!==l.source||u.text!==l.text)&&r.mismatched.push(c)}let s=new Set(a);for(let c of e.children)r.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return r.uncovered=a.filter(c=>!jS(e.children,c)),$S(r)?r:null}if(e.schema===Rs&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!jS(e.children,a)),$S(r)?r:null}return null}function jS(e,t){return e.some(i=>i.covers.includes(t))}function $S(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function sm(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 ED(e){let t=_u(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=_u(n,`Native children acceptance_index.${r}`);if(Au(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 PD(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){let d=["source","text"].filter(f=>u[f]!==l[f]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function RD(e,t,i={}){let r=(0,om.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=_u(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Rs&&a!==ja)throw Au(n,_S,"Native children contract"),new Error(`Native children schema must be ${Rs} or ${ja}`);let o=a===Rs?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Au(n,o==="indexed-v2"?wD:_S,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let v=_u(f,`Native child ${h}`);if(Au(v,o==="indexed-v2"?bD:o==="summary-v2"?ND:yD,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!gD.test(v.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:TS(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?TS(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}kD(c);let d=i.policy==="advisory";if(a===DS){if(o==="indexed-v2"){let f=ED(n.acceptance_index);d||PD(f,t,i);let h=Object.keys(f);return d||IS(c,h,h),{schema:ja,acceptance_index:f,children:c}}return{schema:ja,children:c}}return t&&!d&&IS(c,t),{schema:Rs,children:c}}async function cm(e){let t=Dt.join(e.changeDir,AS);try{await HS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await Z({root:e.changeDir,ref:AS}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=RD(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?SD(a,e.acceptanceIds,e.validation??{}):null}}function CD(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function xD(e){let t=CD(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function LS(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return xD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function lm(e){return D("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 AD(e){let t=Jt(e.projectRoot);t.some(r=>am(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Dt.resolve(n)))]){let n=await ye(r);n&&i.push({projectRoot:r,paths:await qe(r,n.native.artifact_root),parent:am(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function _D(e,t){let i=Dt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ze(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function TD(e,t){let i;try{i=await HS.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=Dt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ze(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function ID(e,t,i){let r=Dt.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Dt.sep}`))return null;let n=r.split(Dt.sep).join("/");try{let a=(0,om.parseDocument)(Ae(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ct(a.toJS({mapAsMap:!1}))}catch{return null}}function jD(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 OS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Cs(e){let t=Dt.join(e.paths.changesDir,e.state.name),i=await LS(t),r=await cm({changeDir:t,validation:sm(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=lm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===ja){let p=await Mr(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let E=await nm({paths:e.paths,parent:e.state.name,targetBranch:y,contract:r.contract});E&&(p=E,await Ia(e.paths,E))}}if(p){let y=xS(p);return e.state.children_contract_hash!==n||r.drift?{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(y=>[y.name,y])),g=r.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(E=>r.contract.children.filter(({name:k})=>k!==y.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await AD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await TD(p,c)){let y={...g,source:p,committedState:ID(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await _D(p,g);y&&u.set(g,[...u.get(g)??[],{source:p,state:y}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&OS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=u.get(p.name)??[];y.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&d.set(p.name,jD(y[0].state,y[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),E=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),S=k?.kind==="active"&&E?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>am(F.projectRoot,k.projectRoot)&&$?.name===P&&OS($,a))):[],R,N=k?.message??null;k?.kind==="done"?(R=E?"done":"blocked",E||(N=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=E&&S.length===0?"active":"blocked",E?S.length>0&&(N=`Native child ${p} does not include merged dependencies: ${S.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&E?"ready":"pending",o||(N="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:N};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var xs="skill-coordinated";function OD(e){return e.state_version+1}function HD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function DD(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:hr(e.summary),completed_at:e.completedAt}}function um(e){let t=ct(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=Yn(t,DD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?HD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ct({...r,phase:"build",status:"active",state_version:OD(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as FS}from"node:fs";import As from"node:path";function Tu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Iu(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 Ei(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 MS(e,t){return e===null?null:Ei(e,t)}function $u(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 LD(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 MD(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ju(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function dm(e,t){if(e===null)return null;let i=Ei(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function fm(e,t){let i=Ei(e,t);if(!As.isAbsolute(i))throw new Error(`${t} must be absolute`);return As.resolve(i)}function FD(e,t){let i=`Native local checks[${t}]`,r=Tu(e,i);if(Iu(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)=>Ei(l,`${i}.argv[${u}]`,!0)),a=ju(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=dm(r.startedAt,`${i}.startedAt`),s=dm(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=$u(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ei(r.id,`${i}.id`),name:Ei(r.name,`${i}.name`),operationId:Ei(r.operationId,`${i}.operationId`),status:a,repeatable:MD(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:$u(r.executionCount,`${i}.executionCount`),argv:n,cwd:fm(r.cwd,`${i}.cwd`),exitCode:LD(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ei(r.log,`${i}.log`)}}function hm(e){let t="Native local execution state",i=Tu(e,t);if(Iu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Lo)throw new Error(`Native local execution schema must be ${Lo}`);let r=Tu(i.workspace,"Native local workspace");Iu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Tu(i.execution,"Native local execution");Iu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=dm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ei(o.operationId,"Native local execution.operationId"),stage:ju(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ju(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:MS(o.executionId,"Native local execution.executionId"),status:ju(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:$u(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(FD);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:Lo,change:Ei(i.change,"Native local change"),basedOnStateVersion:$u(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:fm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:fm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:MS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function yn(e){return hm({schema:Lo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:As.resolve(e.projectRoot),worktreeRoot:As.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ou(e){let t;try{t=await FS.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 hm(i)}async function Fr(e,t,i={}){let r=hm(t);await FS.mkdir(As.dirname(e),{recursive:!0}),await ee(e,r,i)}import{promises as BD}from"node:fs";function Br(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
206
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Bi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function VD(e){return e.archived?qt(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?qt(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?qt(e.language,"Verification passed; ready to archive","验收通过,可归档"):qt(e.language,"Verification passed","验收通过")}function qD(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?qt(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?VD(e):e.verification_result==="blocked"?qt(t,"Blocked","已阻塞"):e.verification_result==="fail"?qt(t,"Failed","未通过"):qt(t,"Pending","待处理")}function WD(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===xs?xs:"host-attested"),i=t===xs&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":i?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":i?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function zD(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let i=e.language,r=d=>fd(i,d),n=(d,f)=>qt(i,d,f),a=e.acceptance.map(d=>`| ${Bi(d.id)} | ${Bi(d.result)} | ${Bi(d.source)} | ${Bi(d.text)} | ${Bi(Br(d.reason))} |`).join(`
207
- `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(Br).join(" ");return`| ${Bi(Br(d.name))} | ${Bi(f||"—")} | ${Bi(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
208
- `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Br(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
209
- `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Br(d)}`).join(`
210
- `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Bi(Br(d.summary))} | ${d.completed_at} |`)].join(`
198
+ ${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ns(h),h}async function tu(e){let t=await cb(e),i=Na(e.paths,e.name),r=j(e.paths,i);return await I(r,i),await ee(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await ob(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ns(i),i)}async function lb(e){return await np(e.paths,e.name)?tu(e):null}async function as(e){ns(e.identity);let t=await cb({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")),ip==="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 ba(e){if(ns(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 as(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=fe(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function ub(e,t){let i=await kt(e,t);if(i===null)return null;let r=await ba({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var fb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],S$=new Set(fb),hb=new Set([...fb,"minimum_runtime_version","revision"]),E$=new Set([...hb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),P$=new Set(["capability","operation","source","base_hash"]),R$=new Set(["shape","build","verify","archive"]),C$=new Set(["implicit","confirmed"]),x$=new Set(["pending","pass","fail"]),Te="comet-state.yaml",op=/^[a-f0-9]{64}$/u,pb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A$=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,os=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"},wn=class extends Error{constructor(i,r){super(i!==Ne||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"},ss=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"},cs=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"},ka=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"},fz=tc("en");function us(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mb(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 ru(e){if(!pb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function _$(e){if(!pb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function vb(e,t){if(e.length===0||vi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function I$(e,t){let i=us(e,`spec_changes[${t}]`);if(mb(i,P$,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(_$(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"&&vb(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"||!op.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"||!op.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 T$(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 sp(e,t){if(mb(e,t,Te),typeof e.name!="string")throw new Error("Native change name is required");if(ru(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"||!R$.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&&!C$.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(I$),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"||!x$.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"&&vb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!T$(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function fn(e){let t=us(e,Te);if(t.schema!==et)throw new Error(`Expected ${et}`);return{schema:et,...sp(t,S$)}}function ls(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ap(e,t,i){if(e===null)return null;let r=typeof e=="string"?A$.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 j$(e){if(e==null)return null;if(typeof e!="string"||!op.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function $$(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 fi(e){let t=us(e,Te);if(t.schema!==be)throw new Error(`Expected ${be}`);if(ls(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${be} minimum_runtime_version must be 2`);return{schema:be,minimum_runtime_version:2,revision:ls(t.revision,"Native v2 revision"),...sp(t,hb)}}function lt(e){let t=us(e,Te);if(t.schema!==Ne){if(t.schema===et||t.schema===be){let o=t.schema===et?fn(t):fi(t);throw new os(o.name,o.schema)}throw new wn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=ls(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new wn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=ls(t.revision,"Native revision"),n=sp(t,E$),a=j$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ne,minimum_runtime_version:3,revision:r,verification_protocol:$$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:ap(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ap(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ap(t.partial_allowance,"Native partial_allowance","allowances")}}function gb(e){let t=us(e,Te);if(t.schema===et){let n=fn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema===be){let n=fi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema!==Ne){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 wn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=ls(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new wn(t.schema,i).message};let r=lt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function gn(e){let t=lt(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 nu(e){let t=fi(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 ne(e,t){ru(t);let i=vi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Sa(e,t){let i=D(e,t),r=vi.join(i,"schema-migration.json");await I(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await db.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Ea(e,t){let i=D(e,t),r=vi.join(i,"checkpoint-journal.json");await I(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await db.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function au(e,t=vi.dirname(e)){let i=vi.relative(t,e).split(vi.sep).join("/"),r=await Z({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,iu.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 gi(e,t){let i=vi.join(ne(e,t),Te);await I(e.nativeRoot,i);let r=gb(await au(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Sa(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 O$(e,r.state),r)}async function ou(e,t){let i=vi.join(ne(e,t),Te);await I(e.nativeRoot,i);let r=gb(await au(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function O$(e,t){if(await va(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function De(e,t){let i=await gi(e,t);if(i.status==="migration-required")throw new os(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new wn(i.schema,i.minimumRuntimeVersion);return await ub(e,t),i.state}async function wb(e,t,i){let r={...t,schema:Ne,minimum_runtime_version:3,revision:i+1},n=await gN({expectedRevision:i,next:r,read:async()=>{let a=lt(await au(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>he(e,(0,iu.stringify)(gn(a))),equals:(a,o)=>JSON.stringify(gn(a))===JSON.stringify(gn(o)),conflict:a=>new ss(t.name,i,a)});return Object.assign(t,n),n}async function su(e,t,i,r){if(await Zn(e.projectRoot),await Sa(e,t.name))throw new os(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 De(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Zl(e,t.name);let a=vi.join(ne(e,t.name),Te);return await I(e.nativeRoot,a),wb(a,t,i)}async function yb(e,t){return wb(e,t,t.revision)}async function Nb(e){return lt(await au(e))}var kb=["outcome","scope","nonGoals","acceptanceExamples"],H$=[...kb,"constraints","decisions","openQuestions","verificationExpectations"],D$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],Sb={maxFileBytes:Io};function Eb(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
199
+ `).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 L$(e,t){let i=bb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await cp.realpath(e),n=await cp.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await cp.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function ds(e){return{valid:e.length===0,findings:e}}function lp(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),i=null;for(let r of e.split(/\r?\n/u)){let n=r.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];i===null?i=s:i===s&&(i=null);continue}if(i!==null)continue;let a=r.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function up(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:Sb.maxFileBytes})).text}catch(a){return ds([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Eb(r))n.set(ec(a)??a,o);for(let a of H$)n.has(a)||i.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of kb)(n.get(a)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return lp(r)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),ds(i)}async function dp(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:Sb.maxFileBytes})).text}catch(a){return ds([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Eb(r))n.set(sv(a)??a,o);for(let a of D$)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 ds(i)}function cu(e,t){return bb.join(e.specsDir,t,"spec.md")}async function Pb(e,t){let i=[],r=ne(e,t.name);for(let n of t.spec_changes){let a=cu(e,n.capability),o=null;try{await I(e.nativeRoot,a),o=await ti(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 L$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return ds(i)}import{promises as WH}from"node:fs";import cS from"node:path";import Rb from"node:path";var M$="comet.native.archive-preflight.v1",F$="comet.native.archive-preflight.v1",B$="comet.native.archive-operation.v1",V$=/^[a-f0-9]{64}$/u,Cb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,q$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function lu(e,t){return e<t?-1:e>t?1:0}function W$(e,t){if(typeof e!="string"||!V$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Hi(e,t){return e===null?null:W$(e,t)}function z$(e,t){let i=Rb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Rb.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 J$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function G$(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 U$(e,t){if(!Cb.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=Hi(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Hi(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Hi(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 K$(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:Hi(e.contractHash,"Native archive contract hash"),acceptanceHash:Hi(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Hi(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Hi(e.reportHash,"Native archive report hash"),envelopeHash:Hi(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Hi(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 Y$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!q$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(lu);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function X$(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(lu)}function xb(e){if(!Cb.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(U$).sort((l,u)=>lu(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:H(B$,l)})),r=K$(e.evidence),n=G$(e.workspace),a=[...new Set([...Y$(e.findingCodes??[]),...X$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(lu),o=J$(e.revision),s=z$(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:M$,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:H(F$,c)}}import{createHash as Q$}from"node:crypto";import Ab from"node:path";var Z$="comet.native.conflict-radar.v1",ut=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}),eO="comet.native.conflict-radar.v1",tO="comet.native.conflict-radar-signals.v1",iO=/^[a-f0-9]{64}$/u,Tb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rO=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),nO=new Set(["capability","operation","baseHash"]),aO=new Set(["path","kind"]);function Pa(e,t){return e<t?-1:e>t?1:0}function fp(e){return Buffer.byteLength(e,"utf8")}function hp(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 pp(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(fp(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function oO(e,t){let i=pp(e,t,ut.maxArtifactPathBytes),r=Ab.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)||Ab.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 jb(e,t){if(typeof e!="string"||!iO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function sO(e,t){let i=hp(e,nO,t),r=pp(i.capability,`${t} capability`,ut.maxCapabilityBytes);if(!Tb.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:jb(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 cO(e,t){let i=hp(e,aO,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:oO(i.path,`${t} path`),kind:i.kind}}function lO(e,t){let i=hp(e,rO,`Conflict radar change ${t}`),r=pp(i.name,`Conflict radar change ${t} name`,ut.maxNameBytes);if(!Tb.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>ut.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>ut.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>sO(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Pa(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)=>cO(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Pa(c.path,l.path)||Pa(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:jb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function uO(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ut.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(lO).sort((n,a)=>Pa(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)>ut.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ut.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function dO(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 fO(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 hO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function pO(e,t){let i=[],r=Q$("sha256").update(`${tO}
200
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Vo(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ut.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(dO(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=fO(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:hO(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function _b(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function mO(e,t){return _b(e.classification)-_b(t.classification)||Pa(e.left,t.left)||Pa(e.right,t.right)}function Ib(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:Z$,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 $b(e){let t=uO(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(pO(t[s],t[c]));i.sort(mO);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=H(eO,{changes:t,relationships:r}),a=i.slice(0,ut.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Ib(t,i,a,n);for(;a.length>0&&fp(JSON.stringify(o))>ut.maxSerializedBytes;)a=a.slice(0,-1),o=Ib(t,i,a,n);if(fp(JSON.stringify(o))>ut.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as R0}from"node:crypto";import{promises as ai}from"node:fs";import Ni from"node:path";import{createHash as Vb}from"node:crypto";import Ob from"path";var mp="comet.native.implementation-scope.v2",qb="comet.native.content-snapshot-projection.v1",fs="comet.native.content-snapshot-projection.v1",Wb="comet.native.implementation-scope.v2",vO="comet.native.unresolved-scope-id.v1",gO="comet.native.scope-detail-overflow.v1",wO="comet.native.snapshot-projection-overflow.v2",yp=/^[a-f0-9]{64}$/u,Nn=1024*1024,yO=128,NO=128;function Ge(e,t){return e<t?-1:e>t?1:0}function vp(e){if(!yp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function bO(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function _r(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=Ob.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Ob.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function zb(e,t){return e==="."?e:_r(e,t)}function Ra(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function kO(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:_r(e.path,`${t} path`),hash:e.hash,size:Ra(e.size,`${t} size`),type:"file"}}function SO(e,t){return{path:zb(e.path,`${t} path`),size:e.size===null?null:Ra(e.size,`${t} size`),type:e.type,reason:e.reason}}function EO(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function PO(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ps(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
201
+ `,"utf8")}function Ar(e,t,i){let r=`${t}
202
+ ${Vo(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function RO(e){if(ps(e)<=Nn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Vb("sha256");a.update(`${wO}
203
+ `),e.omissionOverflow&&Ar(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Ar(a,"omission",f)},s=f=>{r+=1,n+=1,Ar(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(;ps(u)>Nn;){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 m=c();if(m===null)break;o(m,!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 gp(e){let t=$i(e),i=t.entries.map((n,a)=>kO(n,`Snapshot entry ${a}`));if(i.sort(EO),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)=>SO(n,`Snapshot omission ${a}`));return r.sort(PO),RO({schema:qb,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 ms(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:_r(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)=>Ge(i.path,r.path)||Ge(i.kind,r.kind))}function vs(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Hb(e){return e?{hash:e.hash,size:e.size}:null}function Np(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:Ge(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:Hb(c),after:Hb(l)})}}function Jb(e,t){return{...e,attributedTo:t.filter(i=>vs(i,e.path))}}function bp(e){let t=ms(e.declaredArtifacts),i=[];return Np(e.baseline,e.current,r=>{i.push(Jb(r,t))}),i}function Di(e,t){return{id:`scope:${H(vO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function CO(e,t){let i=t.omitted.map(r=>Di({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(Di({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Di({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 Db(e,t){return CO(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function wp(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||bO(e.path,t.path)||Ge(e.id,t.id)}function xO(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(wp)}function Gb(e){return[...new Set(e.map((t,i)=>_r(t,`Git path ${i}`)))].sort(Ge)}function Lb(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 AO(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 Ub(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Gb(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Lb(e.baseCommit,"Native external drift base commit"),targetBranch:AO(e.targetBranch,"Native external drift target branch"),targetCommit:Lb(e.targetCommit,"Native external drift target commit"),paths:t}}function Kb(e){if(typeof e.contractHash!="string"||!yp.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ms(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Gb(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Ub(e.externalDrift)}}}function _O(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 Np(e,t,h=>{let v=i.some(m=>vs(m,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<yO){let m=Jb(h,i),p=ps(m);l+p<=Nn?(a.push(m),l+=p):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Yb(e,t){return Di({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 IO(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:Ra(Number(t[1]),"Scope overflow change count"),unresolved:Ra(Number(t[2]),"Scope overflow unresolved count"),unattributed:Ra(Number(t[3]),"Scope overflow unattributed count")},r=yn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Yb(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function TO(e){let t=Vb("sha256");t.update(`${gO}
204
+ `);let i=0;Np(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Ar(t,"change",n);let a=0;for(let o of e.declaredArtifacts)vs(o,n.path)&&(a+=1,Ar(t,"change-attribution",o));Ar(t,"change-end",{attributionCount:a}),a===0&&Ar(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&&Ar(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Xb(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=_O(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),y=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!y.has(P)||n.some(F=>vs(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=H(fs,e),c=H(fs,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,y]of[["baseline",e],["current",t]])for(let w of y.omitted){if(l.length>=NO)break;l.push(Di({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Db("baseline",e),...Db("current",t),...o.totalChanges===0&&a===null?[Di({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(y=>R.has(y)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(y=>!R.has(y))}},v=R=>{let y=o.candidates.slice(0,R.detailedChangeCount),w=y.filter(qt=>qt.attributedTo.length===0&&!u.has(qt.path)),P=o.totalChanges-y.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Be=F+$,ue=[...w.map(qt=>Di({kind:"unattributed-change",source:"implementation-scope",path:qt.path,evidence:{after:qt.after,before:qt.before,changeKind:qt.kind}},`Changed path is not covered by a declared artifact: ${qt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Be>0?[Yb(R.overflowHash,{changes:P,unattributed:F,unresolved:Be})]:[]],te=xO(ue),si=R.includeGitAdvisory?h():void 0;return{schema:mp,contractHash:r,baselineProjectionRef:vp(s),baselineProjectionHash:s,currentProjectionRef:vp(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:n,changes:y,unattributed:w,unresolvedScopes:te,noCodeReason:a,...si?{gitAdvisory:si}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(ps({...R,scopeHash:g})<=Nn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>m||d>p?TO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:N}),E={...k,scopeHash:H(Wb,k)};if(ps(E)>Nn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return E}function kp(e){let t=gp(e.baseline),i=gp(e.current),r=Kb(e);return{authority:r,baseline:t,current:i,scope:Xb(t,i,r)}}var jO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function yi(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 yn(e,t){if(typeof e!="string"||!yp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Mb(e,t,i){let r=vp(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function Ca(e,t){let i=wi(e,"Native snapshot projection");if(yi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==qb)throw new Error("Native snapshot projection schema is invalid");let r=$i({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=gp(r);if(H(fs,i)!==H(fs,n))throw new Error("Native snapshot projection is not canonical");let a=H(fs,n);if(t!==void 0&&yn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Sp(e,t){let i=wi(e,`Declared artifact ${t}`);if(yi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:_r(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Fb(e,t){if(e===null)return null;let i=wi(e,t);return yi(i,["hash","size"],[],t),{hash:yn(i.hash,`${t} hash`),size:Ra(i.size,`${t} size`)}}function Bb(e,t){let i=wi(e,`Implementation change ${t}`);if(yi(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(Sp),n=ms(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Fb(i.before,`Implementation change ${t} before`),o=Fb(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:_r(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function $O(e,t){let i=wi(e,`Unresolved scope ${t}`);yi(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"?zb(i.path,`Unresolved scope ${t} path`):_r(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function hs(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)=>_r(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Qb(e){let t=wi(e,"Native implementation external drift");if(yi(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=hs(t.paths,"Native external drift paths");return Ub({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function xa(e){let t=wi(e,"Native implementation scope"),i=[...jO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(yi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==mp)throw new Error("Native implementation scope schema is invalid");let r=yn(t.contractHash,"Implementation scope contractHash"),n=yn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Mb(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=yn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Mb(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(Sp);if(JSON.stringify(c)!==JSON.stringify(ms(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Bb),u=[...l].sort((w,P)=>Ge(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>vs(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Bb),h=t.externalDrift===void 0?void 0:Qb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map($O),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:IO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...m.map(w=>Di({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&S===null?[Di({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=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(wp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(N.sort(wp))||t.complete!==(p.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 E;if(t.gitAdvisory!==void 0){let w=wi(t.gitAdvisory,"Implementation scope Git advisory");if(yi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=hs(w.changedPaths,"Git changed paths"),F=hs(w.pathsPresentInSnapshotChanges,"Git present paths"),$=hs(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Be=[...F,...$].sort(Ge);if(JSON.stringify(Be)!==JSON.stringify(P)||$.some(ue=>l.some(te=>te.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");E={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:mp,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:S,...E?{gitAdvisory:E}:{},...h?{externalDrift:h}:{}},y=yn(t.scopeHash,"Implementation scope scopeHash");if(H(Wb,R)!==y)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:y}}function OO(e){let t=wi(e,"Native implementation scope authority");if(yi(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(Sp);if(JSON.stringify(i)!==JSON.stringify(ms(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=hs(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Qb(t.externalDrift),a=Kb({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 gs(e){let t=wi(e,"Native implementation scope bundle");yi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=OO(t.authority),r=Ca(t.baseline),n=Ca(t.current),a=xa(t.scope),o=Xb(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 Zb(e){let t=xa(e.scope);return gs({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 ek from"node:path";var HO=/\b(Bearer|Basic)\s+[^\s"']+/giu,DO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,LO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,MO=/\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,FO=/("(?:[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,BO=/(["'])((?:[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,VO=/\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 $t(e){return e.replace(HO,"$1 [REDACTED]").replace(DO,"[REDACTED PRIVATE KEY]").replace(LO,"$1[REDACTED]@").replace(MO,"[REDACTED TOKEN]").replace(FO,'$1"[REDACTED]"').replace(BO,"$1$2$1$3$4[REDACTED]$4").replace(VO,"$1$2[REDACTED]")}var ik=/^[a-f0-9]{64}$/u;var qO="comet.native.acceptance-trace.v2",WO="comet.native.partial-allowance.v1",zO="comet.native.verification-evidence.v2";function Li(e,t){if(!ik.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function nk(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 Ep(e,t,i=2e3){let r=$t(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ws(e,t){let i=ek.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})||ek.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 JO(e,t,i){let r=ws(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ui(r),a=r.toLowerCase(),o=i?ws(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 Pp(e){let t=ws(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 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=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 ak(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 tk(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 GO(e){let t=uu(e,"Native acceptance trace");if(du(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"||!ik.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=ws(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=uu(o,`Native acceptance trace entry ${s}`);if(du(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=>Pp(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:ws(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Ep(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=Li(t.traceHash,"Native acceptance trace hash");if(H(qO,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function fu(e){let t=uu(e,"Native partial allowance");if(du(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:nk(t.change),scopeHash:Li(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Ep(t.reason,"Partial allowance reason"),confirmedSummary:Ep(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:rk(t.sourceRevision),confirmedAt:ak(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=Li(t.allowanceHash,"Native partial allowance hash");if(H(WO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function ys(e){let t=uu(e,"Native verification evidence");if(du(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=Li(t.implementationScopeHash,"Native verification implementation scope hash"),r=GO(t.acceptanceTrace),n=Li(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:Li(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Pp(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=>Pp(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:nk(t.change),sourceRevision:rk(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Li(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:tk(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:JO(t.reportRef,"Native verification report ref"),reportHash:Li(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:tk(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:ak(t.createdAt,"Native verification timestamp")},d=Li(t.envelopeHash,"Native verification envelope hash");if(H(zO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import ok from"node:path";var sk="comet.native.check-receipt.v1",UO="comet.native.check-receipt.v1",_a="scoped-text-safety",Rp=1,dt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),KO=/^[a-f0-9]{64}$/u,YO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XO="comet.native.checker-policy.v1",QO="comet.native.check-input.v1",ZO=2048,ck=H(XO,{policy:_a,version:Rp,limits:dt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),e0=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),lk=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],dk=["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"],t0=new Set(dk);function Ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tr(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 Mi(e,t){if(typeof e!="string"||!KO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function fk(e,t){let i=St(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function uk(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 i0(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>ZO||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=ok.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||ok.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function r0(e){let t=Ir(e,"Native check receipt checker");Tr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Ir(t.limits,"Native check receipt limits");if(Tr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==_a||t.version!==Rp||t.hash!==ck||i.maxFiles!==dt.maxFiles||i.maxFileBytes!==dt.maxFileBytes||i.maxTotalBytes!==dt.maxTotalBytes||i.maxIssues!==dt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:_a,version:Rp,hash:ck,limits:{...dt}}}function n0(e){let t=Ir(e,"Native check receipt contract");return Tr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Mi(t.expectedHash,"Native check expected contract hash"),beforeHash:Mi(t.beforeHash,"Native check before contract hash"),afterHash:Mi(t.afterHash,"Native check after contract hash")}}function a0(e){let t=Ir(e,"Native check receipt implementation");return Tr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Mi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Mi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Mi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Mi(t.afterSnapshotHash,"Native check after snapshot hash")}}function o0(e,t){let i=Ir(e,`Native check batch ${t}`);Tr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:St(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:St(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:St(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:St(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:St(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:St(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>dt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>dt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function s0(e){let t=Ir(e,"Native check receipt counts");Tr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:St(t.filesSelected,"Native check filesSelected"),filesScanned:St(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:St(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:St(t.bytesScanned,"Native check bytesScanned"),issueCount:St(t.issueCount,"Native check issueCount"),recordedIssueCount:St(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(o0):(()=>{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>dt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>dt.maxFiles||i.bytesScanned>dt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function c0(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||lk.indexOf(e.kind)-lk.indexOf(t.kind)}function l0(e){if(!Array.isArray(e)||e.length>dt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Ir(r,`Native check issue ${n}`);if(Tr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!e0.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:i0(a.path,`Native check issue ${n} path`),line:fk(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(c0);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function u0(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!t0.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=dk.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 d0(e){return H(QO,e)}function hu(e){let t=Ir(e,"Native check receipt");if(Tr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==sk)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!YO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=fk(t.sourceRevision,"Native check source revision"),r=r0(t.checker),n=n0(t.contract),a=a0(t.implementation),o=d0({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Mi(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=uk(t.startedAt,"Native check receipt startedAt"),c=uk(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=s0(t.counts),u=l0(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=u0(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>dt.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>dt.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:sk,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=Mi(t.receiptHash,"Native check receipt content hash");if(H(UO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var xp="comet.native.verification-receipt.v3",f0=xp,h0="comet.native.declared-artifacts.v1",p0=/^[a-f0-9]{64}$/u,m0=/^acceptance-[a-f0-9]{64}$/u,v0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,g0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,w0=4096,y0=256,N0=1024;function Ia(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 jr(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 Fi(e,t){if(typeof e!="string"||!p0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ni(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=$t(e).trim();if(!i||i.length>w0||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Cp(e,t){let i=ni(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 Ns(e,t,i=ni,r=!1,n=y0){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 b0(e,t){if(typeof e!="string"||!m0.test(e))throw new Error(`${t} is invalid`);return e}function k0(e){let t=Ia(e,"Native verification receipt bindings");if(jr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!v0.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:Fi(t.contractHash,"Native verification receipt contract hash"),scopeHash:Fi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Fi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Fi(t.artifactHash,"Native verification receipt artifact hash")}}function S0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=g0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function E0(e,t,i,r){let n=Ia(t,`Native ${e} evidence`);if(e==="automated-check"){if(jr(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=Cp(n.startedAt,"Native automated-check start time"),o=Cp(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=Ia(n.worktree,"Native automated-check worktree");if(jr(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=Ia(n.afterFence,"Native automated-check after fence");if(jr(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:ni(n.executable,"Native automated-check executable"),args:Ns(n.args,"Native automated-check arguments",ni,!0),cwd:ni(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:ni(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Fi(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Fi(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Fi(n.outputHash,"Native automated-check output hash"),outputSummary:ni(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){jr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=S0(n.checkReceiptRef);if(Fi(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Ns(n.subjects,"Native static inspection subjects",ni,r==="required-check"),rule:ni(n.rule,"Native static inspection rule"),resultSummary:ni(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return jr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Ns(n.steps,"Native manual evidence steps"),observations:Ns(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function P0(e){let t=Ia(e,"Native verification receipt");if(jr(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=ni(t.actor,"Native verification receipt actor"),o=Ns(t.acceptanceIds,"Native receipt acceptance IDs",b0,r==="required-check",N0).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:xp,kind:i,role:r,status:n,bindings:k0(t.bindings),acceptanceIds:o,actor:a,issuedAt:Cp(t.issuedAt,"Native verification receipt issue time"),evidence:E0(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==_a||s.actor!==`native-runtime:${_a}`))throw new Error("Native required check policy identity is invalid");return s}function pu(e){let t=Ia(e,"Native verification receipt");if(jr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==xp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=P0(r),a=Fi(t.receiptHash,"Native verification receipt hash");if(H(f0,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Ap(e){return H(h0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var vk=/^[a-f0-9]{64}$/u,$r=Nn,rJ=3*$r;function _p(e,t){let i=Ni.relative(e,t);return i===""||!Ni.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ni.sep}`)}function C0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function hk(e){let t=await ai.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ai.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function x0(e,t){let i=Ni.resolve(e),r=Ni.resolve(t);if(!_p(i,r))throw new Error("Native evidence path is outside its change");let n=[await hk(i)],a=i;for(let o of Ni.relative(i,r).split(Ni.sep).filter(Boolean)){a=Ni.join(a,o);let s=await hk(a);if(!_p(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function pk(e){for(let t of e){let i=await ai.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!C0(t,i)||await ai.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function A0(e,t,i={}){let r=await x0(t,Ni.dirname(e));await i.afterParentChainCaptured?.();let n=await ai.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ai.realpath(e);if(!_p(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ai.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ai.lstat(e),ai.realpath(e)]);if(await pk(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!mu(s,n)||!mu(s,c))throw new Error("Native evidence document changed while opening");if(s.size>$r)throw new Error(`Native evidence document exceeds ${$r} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=$r+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>$r)throw new Error(`Native evidence document exceeds ${$r} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ai.lstat(e),ai.realpath(e)]);if(await pk(r),!v.isFile()||v.isSymbolicLink()||m!==a||!mu(s,h)||!mu(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 ja(e,t){if(!vk.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function gk(e){return ja("reports",e)}async function _0(e,t,i,r,n){if(!vk.test(i))throw new Error("Native report evidence hash is invalid");let a=await bn({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"||R0("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 Ta(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 I0(e,t,i,r,n){let a=ja(i,r);return n?Ni.join(n,...a.split("/")):pr(D(e,t),a)}async function bn(e){let t=I0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await I(i,t),A0(t,i,e.hooks)}function mk(e,t){return Ca(e,t)}function T0(e,t){let i=xa(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function j0(e,t,i){let r=fu(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function $0(e,t,i){let r=ys(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function O0(e,t,i,r=!1,n){let a=await vu(e,t,i.implementationScopeRef,void 0,n);if(r&&await _0(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 wk(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 bs(e,t,i,r,n){let a=Ta(i,"scopes"),o=T0(await bn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Ta(o.baselineProjectionRef,"snapshots"),c=Ta(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([bn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>mk(d,s)),bn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>mk(d,c))]);return Zb({baseline:l,current:u,scope:o})}async function vu(e,t,i,r,n){return(await bs(e,t,i,r,n)).scope}async function wk(e,t,i,r,n){let a=Ta(i,"allowances");return j0(await bn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ks(e,t,i,r,n){let a=Ta(i,"receipts"),o=pu(await bn({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 $a(e,t,i,r,n){let a=Ta(i,"verifications"),o=$0(await bn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await O0(e,t,o,!1,n),o}var H0=4096;async function D0(e,t=ut.maxChanges){try{let i=await wt({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 yk(e,t){let i=await De(e,t),[r,n]=await Promise.all([i.implementation_scope?vu(e,t,i.implementation_scope):null,kt(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 gu(e,t,i={}){let n=(await D0(e,H0)).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 yk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await yk(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=$b([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 eH}from"fs";import tH from"path";import{isDeepStrictEqual as yu}from"util";var Oa={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var L0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function M0(e,t){return e<t?-1:e>t?1:0}function F0(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"||!L0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(M0)}function Ip(e=[]){return F0(e,"Native repair failed check IDs",Oa.maxFailedCheckIds,!0)}function Nk(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function B0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Nk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Nk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Tp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(B0(r,a))break;i+=1,r=a}return i}function jp(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 bk="repairStagnation",Et={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},q0=/^[a-f0-9]{64}$/u;var W0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),z0=["data","runId","sequence","timestamp","type"],kk=["disposition","overrideSummaryHash","signatureHash"],J0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Sk=12;function Op(e,t){return e<t?-1:e>t?1:0}function Ek(e,t,i){let r=Object.keys(e).sort(Op);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function wu(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 Ss(e,t){if(typeof e!="string"||!q0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function G0(e){if(!Array.isArray(e)||e.length>Oa.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(Op)}function Pk(e){if(typeof e!="string"||e.length===0||e.length>Et.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 $p(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Et.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Et.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>Et.maxTextCharacters&&(!n||e.length>Et.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Et.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>Et.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>$p(s,t+1,i,`${r}[${c}]`));return}let a=wu(e,r),o=Object.keys(a);if(o.length>Et.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Et.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");$p(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function U0(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 K0(e,t,i){let r=wu(e,`Native repair trajectory event ${t+1}`);if(Ek(r,z0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(U0(r.timestamp),typeof r.type!="string"||!W0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Pk(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 $p(r.data,0,n,"Native trajectory event data"),wu(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Hp(e){let t=wu(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Op),r=i.length===kk.length&&i.every((l,u)=>l===kk[u]);r||Ek(t,J0,"Native repair trajectory projection");let n=Ss(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:Ss(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=Ss(t.contractHash,"Native repair trajectory contract hash"),s=G0(t.failedAcceptanceIds),c=Ip(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 Y0(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 X0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??Sk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Tp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Oa.warningAtConsecutiveFailures?"continue":a<Oa.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function Q0(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??Sk;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 Rk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Et.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Pk(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=K0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Et.maxTotalDataNodes||c>Et.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?Ss(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Ss(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,bk)){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=Hp(f[bk]);if(Y0(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),X0(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");Q0(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Oa.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Ck(e){return Rk(e).history}function xk(e){let t=Rk(e).latestProjection;return t?{...t}:null}var bi={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:[]},Es=L("comet-native-runtime:v3:scope-reopen"),Z0=[{skillVersion:"3",skillHash:L("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:L("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:L("comet-native-runtime:v1")}];function Ak(e){return e.skillVersion===bi.definition.metadata.version&&e.skillHash===Es||Z0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Dp={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 Or(e){let i={sequence:(await it(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await KN(e.changeDir,e.run.trajectoryRef,i),i}async function kn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:L(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await YN(e.changeDir,e.run.checkpointRef,t),t}function _k(e){return L(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 Lk=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],iH=new Set(Lk),Mk=new Set([...Lk,"minimum_runtime_version","revision"]),rH=new Set([...Mk,"operation"]),nH=512*1024,Lp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),aH=new Set([...Lp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),Ps=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 Ue(e,t){return tH.join(D(e,t),"transition.json")}function oH(e){return`transition-${e}`}async function sH(e,t,i){let r=oH(t);return vr(e,r,i)}async function Sn(e,t,i,r){let n=await sH(e,t,i);try{return await r()}finally{await gr(n)}}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Fp(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 Nu(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ki(e,t){return yu(e,t)}function Mp(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=>!aH.has(u)),a=[...Lp].find(u=>!Object.hasOwn(i,u)),o=Lp.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(jp(i.summary,"Native transition journal event summary"),$t(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&&(jp(i.noCodeReason,"Native transition journal event no-code reason"),$t(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")?Hp(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 cH(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 Mp({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Mp(e,t)}function Bp(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?cH(e.eventData,e.evidenceHash):Mp(e.eventData,e.evidenceHash),n=xr(e.nextRun),a=e.previousRun===null?null:xr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Ik(e,t,i=!1){if(e.skill!==bi.definition.metadata.name||(i?!Ak(e):e.skillVersion!==bi.definition.metadata.version||e.skillHash!==Es)||e.orchestration!==bi.definition.orchestration.mode||e.pendingRef!==Nt.pendingRef||e.trajectoryRef!==Nt.trajectoryRef||e.contextRef!==Nt.contextRef||e.artifactsRef!==Nt.artifactsRef||e.checkpointRef!==Nt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Tk(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 jk(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 Vp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Ik(o,"next Run",r||a!==null),jk(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(Ik(a,"previous Run",!0),jk(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(!yu(Tk(a),Tk(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function lH(e,t,i){return L(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Fk(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function $k(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function qp(e,t,i,r,n=!1){let a=i.eventData,o=$k(e),s=$k(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&&yu(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&&yu(e.spec_changes,t.spec_changes),l=_k({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=lH(e.name,a.summary,t.spec_changes),l=L(`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 Wp(e,t){let i=bu(e);if(Fp(i,rH),i.schema!==wr)throw new Error(`Expected Native transition schema ${wr}`);let r=Nu(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 ${wr} minimum_runtime_version must be ${3}`);let n=Nu(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=Bp(i,t),o=lt(i.previousState),s=lt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(qp(o,s,a,i.operation),Vp(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:wr,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 uH(e,t){let i=bu(e);if(Fp(i,iH),i.schema!==dn)throw new Error(`Expected Native transition schema ${dn}`);let r=Bp(i,t,!0),n=fn(i.previousState),a=fn(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return qp(n,a,r,Fk(n,a,r.eventData),!0),Vp(n,a,r,!0),{schema:dn,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 zp(e,t){let i=bu(e);if(Fp(i,Mk),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);if(Nu(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ji} minimum_runtime_version must be 2`);let n=Nu(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Bp(i,t,!0),o=fi(i.previousState),s=fi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(qp(o,s,a,Fk(o,s,a.eventData),!0),Vp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ji,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 dH(e,t){let i=bu(e);if(i.schema===wr)return{status:"current",journal:Wp(i,t)};if(i.schema===dn)return{status:"migration-required",journal:uH(i,t)};if(i.schema===ji)return{status:"migration-required",journal:zp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Jp(e,t){let i=Ue(e,t),r=j(e,i);await I(r,i);try{let n=await re({root:r,file:i,maxBytes:nH,label:`Native transition journal ${t}`});return dH(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Bi(e,t){let i=await Jp(e,t);if(!i)return null;if(i.status==="migration-required")throw new Ps(t);return i.journal}function Ok(e,t){if(ki(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(ki(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Hk(e,t){if(ki(e,t.nextState))return"next";if(ki(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function fH(e){let{journal:t}=e;return Bk({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 Bk(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Dk(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=fH({sequence:a.index+1,journal:t,type:a.event.type});if(!ki(Bk(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 ku(e,t,i){if(await Sa(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Zl(e,t);let r=await Bi(e,t);if(!r)return null;let n=D(e,t),a=Dk(await it(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([Oe(n),De(e,t)]),c=Ok(o,r),l=Hk(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 vn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!ki(await Oe(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await su(e,r.nextState,r.previousState.revision);if(!ki(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!ki(await De(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Bi(e,t);if(!u||!ki(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Dk(await it(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Or({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 Or({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await kn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([Oe(n),De(e,t)]);Ok(h,{...r,previousRun:r.nextRun}),Hk(v,{...r,previousState:r.nextState});let m=await Bi(e,t);if(!m||!ki(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await eH.rm(Ue(e,t),{force:!0}),r.nextState}async function Vk(e,t,i){return se(e,`continue transition ${t}`,()=>Sn(e,t,`continue transition ${t}`,()=>ku(e,t,i)))}import qk from"node:path";var hH="comet.native.contract.v1",pH="comet.native.acceptance-set.v1",Wk=/^[a-f0-9]{64}$/u,Rs={maxAcceptanceCriteria:Wo.maxCriteria};function zk(e,t){let i=qk.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})||qk.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 Jk(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
205
+ `))}function mH(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(Wk))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(Wk))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=zk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Jk(e.markdown)},markdown:e.markdown}}function vH(e,t){return Gk(e.id,t.id)}function Gk(e,t){return e<t?-1:e>t?1:0}function Uk(e){let t=zk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(mH).sort((d,f)=>Gk(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=bl(e.briefMarkdown,t,Rs.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...kl(f,d.source,Rs.maxAcceptanceCriteria-a.length)),a.push(...Dy(f,d.source,Rs.maxAcceptanceCriteria-a.length)));if(a.sort(vH),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Rs.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Rs.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:Jk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(pH,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(hH,u)}}var Su={maxSpecs:64,maxFileBytes:Io,maxTotalBytes:4*1024*1024};async function Ha(e){if(e.specChanges.length>Su.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Z({root:e.changeDir,ref:e.briefRef,maxBytes:Su.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 Z({root:e.changeDir,ref:n.source,maxBytes:Su.maxFileBytes});if(i+=a.size,i>Su.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:Uk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as OH}from"node:child_process";import{promisify as HH}from"node:util";var aG=["$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 SH}from"fs";import Da from"path";var Dr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},La=/^[a-f0-9]{64}$/u;function Eu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Pu(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 Hr(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 Kk(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 gH(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Da.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Da.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Up(e,t){return Da.join(D(e,t),"checkpoints","progress.json")}function Lr(e,t){return Da.join(D(e,t),"checkpoint-journal.json")}function Kp(e,t,i){if(!La.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Da.join(D(e,t),"checkpoints","manifests",`${i}.json`)}function wH(e){if(!La.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Yp(e,t,i){let r=await re({root:e,file:t,maxBytes:Dr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function yH(e,t){let i=Eu(e,`checkpoint manifest artifact ${t}`);Pu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=gH(Hr(i.path,`checkpoint artifact ${t} path`,4096)),n=ui(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!La.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 Ru(e,t){let i=Eu(e,"Native checkpoint manifest");if(Pu(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>Dr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(yH),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>Dr.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 Xp(e){return L(JSON.stringify(Ru(e,e.change)))}function Qp(e,t){let i=Eu(e,"Native progress checkpoint");if(Pu(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=Kk(i.previousRevision,"Native checkpoint previousRevision"),a=Kk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Hr(i.manifestHash,"Native checkpoint manifestHash",64);if(!La.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=wH(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Hr(i.inputHash,"Native checkpoint inputHash",64);if(!La.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Hr(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>Dr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Hr(i.summary,"Native checkpoint summary"),f=Hr(i.nextAction,"Native checkpoint nextAction");if($t(d)!==d||$t(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Hr(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 NH(e,t){let i=Eu(e,"Native checkpoint journal");if(Pu(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=lt(i.previousState),n=lt(i.nextState),a=Qp(i.checkpoint,t),o=Ru(i.manifest,t),s=Hr(i.inputHash,"Native checkpoint journal inputHash",64),c=L(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!La.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!==Xp(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 bH(e,t,i){let r=Da.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=oh(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await re({root:e.projectRoot,file:r,maxBytes:Dr.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 kH(e,t){let i=Up(e,t),r=j(e,i);await I(r,i);try{return Qp(await Yp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Zp(e,t,i){let r=Kp(e,t,i),n=j(e,r);await I(n,r);let a=await Yp(n,r,"Native checkpoint manifest"),o=Ru(a,t);if(em(e,o),Xp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Mr(e,t){let i=Lr(e,t),r=j(e,i);await I(r,i);try{let n=NH(await Yp(r,i,"Native checkpoint journal"),t);return em(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Yk(e,t,i,r){let n=Ru(i,t);em(e,n);let a=Xp(n),o=Kp(e,t,a),s=j(e,o);await I(s,o);try{let c=await Zp(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 ee(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function em(e,t){for(let i of t.artifacts){let r=oh(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Xk(e,t){let i=Qp(t,t.change),r=await Zp(e,i.change,i.manifestHash),n=L(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=Up(e,t.change),o=j(e,a);await I(o,a),await ee(a,i,{containedRoot:o})}async function Qk(e){let t;try{t=await kH(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:Up(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 Zp(e.paths,e.name,t.manifestHash);let a=L(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 bH(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:Kp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Zk(e,t,i){let r=await Mr(e,t);if(!r)return null;if(await Yk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await su(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Xk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await SH.rm(Lr(e,t),{force:!0}),r}async function eS(e,t,i){return se(e,`continue checkpoint ${t}`,()=>Sn(e,t,`continue checkpoint ${t}`,async()=>(await ku(e,t),Zk(e,t,i))))}import{constants as tm,promises as Ot}from"node:fs";import Ma from"node:path";var EH=/^[a-f0-9]{64}$/u,PH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Cs=512*1024;function RH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function CH(e,t){let i=Ma.resolve(e),r=Ma.resolve(t);if(!O(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 Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(n.length>0&&!O(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 tS(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!RH(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function xH(e){if(!EH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function AH(e){let t=PH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function _H(e,t,i){return pr(D(e,t),xH(i))}async function IH(e,t,i){let r=await CH(i,Ma.dirname(e)),n=await Ot.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([Ot.realpath(t),Ot.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":tm.O_RDONLY|tm.O_NOFOLLOW|tm.O_NONBLOCK,c=await Ot.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(),Ot.lstat(e),Ot.realpath(e)]);if(await tS(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Cu(n,l)||!Cu(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=Cs+1-h,S=await c.read(v,0,Math.min(v.length,g),null);if(S.bytesRead===0)break;if(h+=S.bytesRead,h>Cs)throw new Error(`Native check receipt exceeds ${Cs} bytes`);f.push(Buffer.from(v.subarray(0,S.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await tS(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!Cu(l,m)||!Cu(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function iS(e,t,i){let r=AH(i),n=D(e,t),a=_H(e,t,r),o=j(e,a);await I(o,a);let s=hu(await IH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var xs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var eU=64*1024;var tU=3600*1e3;var iU=HH(OH);var DH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function rS(e,t){let i=[];for(let r of DH){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 nS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await iS(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 Fr=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 LH(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 MH(e){let t=LH(e.bundle.baseline),i=await Xh(e.paths,t,{origin:"explicit",now:e.now});return kp({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 oS(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await bs(e.paths,e.state.name,e.state.implementation_scope),i=await Ha({changeDir:ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await MH({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 sS(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await oS(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 FH(e){let t=await Z({root:ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:My(t.text)}}function BH(e){let{receipt:t,implementationScope:i}=e,r=[],n=bp({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 VH(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:Ap(e.implementationScope.scope.declaredArtifacts)}}async function aS(e){let t=await ks(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=rS(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 Fr([{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 nS({paths:e.paths,state:e.state,receipt:t});if(n){let a=BH({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 qH(e){let t=VH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await aS({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Fr)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 aS({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Fr)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 Fr(i)}function im(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function xu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:im(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([oS(e),$a(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:im(e.state.verification_result,"stale"),envelope:null};let r=await FH({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 qH({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:im(e.state.verification_result,"invalid"),envelope:null}}}function zH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function lS(e){try{return await WH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function JH(e,t){try{return(await Z({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GH(e,t,i){let r=cu(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=cS.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await JH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Z({root:ne(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 UH(e,t){return lS(Ue(e,t))}async function Au(e){let t=e.now??new Date,i=await De(e.paths,e.name),r=await kt(e.paths,e.name),n=await ye(e.paths.projectRoot),a=zH(i.name,t),o=cS.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(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=>GH(e.paths,i.name,v))),xu({paths:e.paths,state:i,now:t}),gu(e.paths,i.name),Sa(e.paths,i.name),Ea(e.paths,i.name),UH(e.paths,i.name),lS(o)]);return xb({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 rm}from"node:fs";import Vi from"node:path";var KH="comet.native.archive-tree.v1",YH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function fS(e){let t={...YH,...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 uS(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 dS(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 hS(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=uS(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Vi.join(t,u.name),f=Vi.relative(e,d).replaceAll("\\","/"),h=await rm.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()){dS(i,{ref:f,kind:"directory"},r,n),await hS(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 re({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`);dS(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await wt({root:e,directory:t,label:`Native Archive content directory ${Vi.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(uS(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Vi.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function pS(e,t={}){let i=fS(t);e=Vi.resolve(e);let r=await rm.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await hS(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 L(`${KH}\0${o}`)}async function oi(e,t={}){let i=fS(t);e=Vi.resolve(e);let r;try{r=await rm.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 re({root:Vi.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Vi.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await pS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as rt}from"node:fs";import Ae from"node:path";var am=16*1024*1024,XH=256*1024,QH=16*1024,As="comet.native.archive-cas.v1";function ZH(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Ae.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Le(e,t){let i=ZH(e,t);return I(j(e,i),i)}function Br(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Fa(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ft(e){let t=await oi(e.target);if(!Br(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Fa(t)}`);return t}async function om(e,t){let i=await pi(e,t),r=await re({root:e.runtimeDir,file:i.journal,maxBytes:XH,label:`Native Archive transaction journal ${t}`}),n=Dl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function _u(e,t,i){let r=Dl({...t,status:i}),n=await pi(e,r.id);return await ee(n.journal,r,{containedRoot:e.runtimeDir}),r}function Iu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function mS(e){return{...Iu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Vr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function eD(e,t){return Vr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ie(e){try{return await rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Si(e){let t=await rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=mS(t),r=await re({root:j(e.paths,e.file),file:e.file,maxBytes:am,label:e.label}),n=await rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!eD(i,mS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Iu(n),size:r.size}}function tD(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!==As||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:As,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Ei(e,t,i,r){let n=await pi(e,t.id),a=Ae.join(n.backups,".cas"),o=`.${Ae.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Ae.join(a,`${i.id}.original.json`),postRecord:Ae.join(a,`${i.id}.post.json`),candidate:Ae.join(a,`${i.id}.candidate`),originalQuarantine:Ae.join(Ae.dirname(r),`${o}.original`),rollbackQuarantine:Ae.join(Ae.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>I(j(e,c),c))),s}async function Ht(e){if(!await ie(e.file))return null;let t=await re({root:e.paths.runtimeDir,file:e.file,maxBytes:QH,label:`Archive CAS ${e.operation.id} ${e.role} record`});return tD(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Tu(e){let t=await Ht(e);if(t){if(!Vr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await hi({root:e.paths.runtimeDir,directory:Ae.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:As,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ee(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ht(e);if(!r||!Vr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Re(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Vr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function iD(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Tu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Re({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function rD(e){if(!await ie(e.quarantine)||await ie(e.target))return;let t=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([rt.lstat(e.quarantine),rt.lstat(e.target)]);if(!Vr(Iu(i),Iu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rt.unlink(e.quarantine),await t.verify()}async function yS(e){if(await ie(e.quarantine)){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Re({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 Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rt.rename(e.target,e.quarantine),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await rD(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 En(e){if(!await ie(e.file))return;await Re(e);let t=await ei({root:j(e.paths,e.file),directory:Ae.dirname(e.file),label:e.label});await t.verify(),await Re(e),await rt.unlink(e.file),await t.verify()}async function vS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await Le(e,t.target),n=await Le(e,t.backup),a=await oi(n);if(a!==null){if(!Br(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ft({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await kr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:am,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ft({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function NS(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 Ei(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ie(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Re({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await vS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await iD({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await vS(e.paths,e.operation,e.hooks),await yS({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 gS(e){let t=await Ei(e.paths,e.journal,e.operation,e.target);return await ie(t.candidate)?(await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await hi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await kr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:am,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 nD(e){let t=e.operation.stagedHash,i=await Ei(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ie(e.target))return await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ie(i.candidate)&&await En({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ie(e.target)){let c=await gS(e),l=await Si({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Vr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Tu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await En({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await gS(e),a=await Si({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await hi({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Re({paths:e.paths,file:n,operation:e.operation,record:{schema:As,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rt.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 Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Vr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Tu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await En({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function aD(e,t,i,r){let n=await Le(e,i.target),a=await Le(e,i.staged);if(await ft({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Ei(e,t,i,n);(!await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ie(n))&&await NS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await oi(n);if(o!==null&&!Br(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Fa(o)}`)}await nD({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ft({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function oD(e,t,i,r){let n=await Le(e,i.target);await NS({paths:e,journal:t,operation:i,target:n,hooks:r}),await ft({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function sD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([oi(i),oi(r)]);if(!(n===null&&Br(a,t.expectedSourceHash,"directory"))){if(!Br(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Fa(n)}, target=${Fa(a)}`);await rt.mkdir(Ae.dirname(r),{recursive:!0}),await rt.rename(i,r),await ft({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function cD(e,t,i,r){return i.type==="write"?aD(e,t,i,r):i.type==="remove"?oD(e,t,i,r):sD(e,i)}function lD(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 uD(e,t,i,r){let n=await Le(e,i.target);if(i.type==="write"){let a=await Le(e,i.staged);await ft({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Ei(e,t,i,n),s=await Ht({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 Re({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ht({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 ie(o.originalQuarantine))await Re({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 ft({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ft({target:await Le(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Ei(e,t,i,n),o=await Ht({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 ie(a.originalQuarantine))await Re({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 ft({target:await Le(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ft({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function bS(e,t,i){let r=t.status==="prepared"?await _u(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Er(e,r.id),a=lD({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 uD(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 It(e,r.id,"operation-started",l.id),await cD(e,r,l,i),await It(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await om(e,r.id),r}async function dD(e){try{return await Re(e),!0}catch{return!1}}async function fD(e){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await ei({root:j(e.paths,e.target),directory:Ae.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rt.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 Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function nm(e){if(e.operation.type!=="write")return;let t=await Ei(e.paths,e.journal,e.operation,e.target);if(!await ie(t.candidate))return;let i=await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await En({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:As,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function hD(e,t,i,r){let n=await Le(e,i.target),a=await Ei(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ht({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ie(a.candidate)&&await ie(n)){let l=await Si({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Si({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Vr(l.identity,u.identity)&&(c=await Tu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Re({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ie(n)&&!(s!==null&&await dD({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await oi(n);if(Br(u,o)){await nm({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await yS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ie(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ie(n)){if(!s||!await ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await fD({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ie(a.originalQuarantine)&&await En({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ie(a.rollbackQuarantine)&&await En({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await nm({paths:e,journal:t,operation:i,target:n}),await ft({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function pD(e,t){let i=await Le(e,t.source),r=await Le(e,t.target),[n,a]=await Promise.all([oi(i),oi(r)]);if(!(Br(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Br(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Fa(n)}, target=${Fa(a)}`);await rt.mkdir(Ae.dirname(i),{recursive:!0}),await rt.rename(r,i)}}async function kS(e,t,i){let r=await Er(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 _u(e,t,"rolling-back");await It(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 pD(e,o):await hD(e,n,o,i));return await It(e,n.id,"rollback-completed"),n=await _u(e,n,"rolled-back"),n}async function wS(e,t,i){let r=await Le(e,i.target);if(i.type==="write"){let n=await Ei(e,t,i,r),a=await Ht({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 Re({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ft({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function mD(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await Le(e,i.target),n=await Ei(e,t,i,r);if(await ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await wS(e,t,i),i.expectedTargetHash!==null){let a=await Ht({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 ie(n.originalQuarantine)&&await En({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await nm({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await wS(e,t,i)}async function ju(e,t,i){return i==="commit"&&await mD(e,t),await It(e,t.id,i),i==="commit"?_u(e,t,"committed"):t}var YU=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as vD}from"fs";import gD from"path";var sm="comet.selection.v2",wD=16*1024;function $u(e){return gD.join(e,".comet","current-change.json")}function yD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function SS(e){return e===null||typeof e=="string"}function ND(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(!yD(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&&!SS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:sm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==sm)throw new Error(`current change selection schema must be ${sm}`);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(!SS(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function cm(e){let t;try{let r=$u(e),{bytes:n}=await on(r,wD,{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",...ND(t)}}async function ES(e){await vD.rm($u(e),{force:!0})}async function PS(e,t,i){let r=await cm(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await ES(e),!0)}import{promises as Rn}from"node:fs";import zr from"node:path";var mm=$n(nn(),1);import{promises as WS}from"node:fs";import Lt from"node:path";import{execFileSync as bD}from"node:child_process";var kD=3e4,SD=8*1024*1024,lm=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 ED(e,t){try{return bD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:kD,maxBuffer:SD,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new lm(e,t,r)}}function Ce(e,t){return ED(e,t).trim()}function _s(e){return Ce(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import Me from"node:path";import{promises as Du}from"node:fs";import Ou from"node:path";function RS(...e){if(e.length===0)return Ou.resolve();if(Ou.win32.isAbsolute(e[0])){let t=Ou.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Ou.resolve(...e)}var Hu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var dm="comet.native.supervisor.v2",PD=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function RD(e,t){let i=Me.relative(Me.resolve(e),Me.resolve(t));return i===""||!Me.isAbsolute(i)&&!i.startsWith(`..${Me.sep}`)}function CD(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function xD(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return RS(e,".worktrees",`${t}-${i}`)}function _S(e,t){return Me.join(We(e,t),"supervisor")}function Lu(e,t){return Me.join(_S(e,t),"state.json")}function IS(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==dm)throw new Error(`Native Supervisor state schema must be ${dm}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Ba(t.integration.targetCommit,"Native Supervisor target commit"),Ba(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Ba(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Ba(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Dt(e,t){try{let i=await Du.readFile(Lu(e,t),"utf8"),r=JSON.parse(i);return IS(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pn(e,t){IS(t),await Du.mkdir(e.changesRuntimeDir,{recursive:!0}),await ee(Lu(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Ba(e,t){if(!PD.test(e))throw new Error(`${t} must be a Git commit`)}function Is(e){return structuredClone(e)}function fm(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function TS(e){Ba(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:dm,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function hm(e){let t=CD(e.parent),i=Ai(e.paths.projectRoot,t);if(!i)return null;let r=Ai(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Gt(e.paths.projectRoot).map(o=>Me.resolve(o)).find(o=>fe(o).currentBranch===t);if(!n)return null;let a=TS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return fm(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Mu(e){if(!_s(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ce(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Me.resolve(t)!==Me.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=Ce(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return Ce(e.integration.worktree,["rev-parse","HEAD"])}async function AD(e){let t=Ai(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if(Mu(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ce(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=Ce(i.integration.worktree,["rev-parse","HEAD"]),a=Is(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},fm(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Pn(e.paths,a),a}function _D(e,t){if(Ba(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let i=Is(e);if(t.headCommit!==i.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(i.children.some(({status:r})=>r!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return i.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},i.stateVersion+=1,i}function jS(e){let t=Mu(e);if(t===e.integration.headCommit)return e;try{Ce(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let i=Is(e);return i.integration.headCommit=t,fm(i,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),i.stateVersion+=1,i}function $S(e,t){let i=t.verification;if(i===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let r=Mu(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=i.checks.length>0&&i.checks.every(({status:o})=>o==="passed");return _D(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:i.summary.text,headCommit:r,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:i.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:i.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function Ts(e){let i=await Dt(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Gt(e.paths.projectRoot).map(v=>Me.resolve(v)).find(v=>fe(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!_s(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=Ce(n,["rev-parse","HEAD"]);if((()=>{try{return Ce(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await xS({paths:e.paths,state:i,targetCommit:a});if(await AS({paths:e.paths,plan:v,targetRoot:n}),i.children.every(({status:p})=>p==="archived"))return await um(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=Is(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await Pn(e.paths,m),await um(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=Mu(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=Ai(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return Ce(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await AD({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await xS({paths:e.paths,state:i,targetCommit:c});l!==c&&Ce(n,["merge","--ff-only",i.integration.branch]);let f=Ce(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=Is(i);for(let v of h.children)v.status="archived";return await AS({paths:e.paths,plan:d,targetRoot:n}),h.stateVersion+=1,await Pn(e.paths,h),await um(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function OS(e,t){return Me.join(_S(e,t),"cleanup.json")}function CS(e){let t=Gt(e.paths.projectRoot).map(s=>Me.resolve(s)),i=Me.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:xD(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Me.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(RD(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!_s(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=fe(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(_o(e.paths.projectRoot,s))try{Ce(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function xS(e){let t=OS(e.paths,e.state.parent);try{let r=JSON.parse(await Du.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=CS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=CS(e);return await ee(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function AS(e){for(let t of e.plan.worktrees){if(!Gt(e.paths.projectRoot).map(a=>Me.resolve(a)).includes(Me.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=fe(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);Ce(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)_o(e.paths.projectRoot,t)&&Ce(e.targetRoot,["branch","-d",t])}async function um(e,t){await Du.rm(OS(e,t),{force:!0})}function HS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var DS="children.yaml",js="comet.native.children.v1",Va="comet.native.children.v2",zS=Va,ID=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LS=new Set(["schema","children"]),TD=new Set(["schema","acceptance_index","children"]),jD=new Set(["name","depends_on","covers"]),$D=new Set(["name","summary","depends_on"]),OD=new Set(["name","depends_on","covers"]);function Bu(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Fu(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){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function MS(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 pm(e,t){let i=Lt.normalize(Lt.resolve(e)),r=Lt.normalize(Lt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function HD(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 FS(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 DD(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===zS&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=i.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);r.missing=n.filter(l=>!(l in e.acceptance_index)),r.extra=o.filter(l=>!a.includes(l));let s=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&r.mismatched.push(l)}let c=new Set(o);for(let l of e.children)r.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return r.uncovered=o.filter(l=>!BS(e.children,l)),VS(r)?r:null}if(e.schema===js&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!BS(e.children,a)),VS(r)?r:null}return null}function BS(e,t){return e.some(i=>i.covers.includes(t))}function VS(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function vm(e){let t=new Set(e.acceptance.map(({id:n})=>n)),i=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),r=new Set(i);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&r.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])i.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...i],allowedAcceptanceIds:[...r]}}function LD(e){let t=Bu(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Bu(n,`Native children acceptance_index.${r}`);if(Fu(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 MD(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=i.allowedAcceptanceIds??r,a=Object.keys(e),o=r.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((i.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function FD(e,t,i={}){let r=(0,mm.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Bu(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==js&&a!==Va)throw Fu(n,LS,"Native children contract"),new Error(`Native children schema must be ${js} or ${Va}`);let o=a===js?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Fu(n,o==="indexed-v2"?TD:LS,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let v=Bu(f,`Native child ${h}`);if(Fu(v,o==="indexed-v2"?OD:o==="summary-v2"?$D:jD,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!ID.test(v.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:MS(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?MS(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}HD(c);let d=i.policy==="advisory";if(a===zS){if(o==="indexed-v2"){let f=LD(n.acceptance_index);d||MD(f,t,i);let h=Object.keys(f);return d||FS(c,h,h),{schema:Va,acceptance_index:f,children:c}}return{schema:Va,children:c}}return t&&!d&&FS(c,t),{schema:js,children:c}}async function $s(e){let t=Lt.join(e.changeDir,DS);try{await WS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await Z({root:e.changeDir,ref:DS}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=FD(i.text,e.acceptanceIds,n);return{contract:a,hash:i.hash,size:i.size,drift:r?DD(a,e.acceptanceIds,e.validation??{}):null}}function BD(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function VD(e){let t=BD(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function JS(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return VD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function gm(e){return H("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 qD(e){let t=Gt(e.projectRoot);t.some(r=>pm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Lt.resolve(n)))]){let n=await ye(r);n&&i.push({projectRoot:r,paths:await qe(r,n.native.artifact_root),parent:pm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function WD(e,t){let i=Lt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ze(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function zD(e,t){let i;try{i=await WS.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=Lt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ze(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function JD(e,t,i){let r=Lt.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Lt.sep}`))return null;let n=r.split(Lt.sep).join("/");try{let a=(0,mm.parseDocument)(Ce(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ct(a.toJS({mapAsMap:!1}))}catch{return null}}function GD(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 qS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Os(e){let t=Lt.join(e.paths.changesDir,e.state.name),i=await JS(t),r=await $s({changeDir:t,validation:vm(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=gm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===Va){let p=await Dt(e.paths,e.state.name);if(!p){let S=e.state.workspace.target_branch??e.state.workspace.change_branch;if(S){let N=await hm({paths:e.paths,parent:e.state.name,targetBranch:S,contract:r.contract});N&&(p=N,await Pn(e.paths,N))}}if(p){let S=HS(p);return e.state.children_contract_hash!==n||r.drift?{...S,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:S.children.map(N=>({...N,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...S,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(S=>[S.name,S])),g=r.contract.children.map(S=>({name:S.name,summary:S.summary,dependsOn:[...S.depends_on],covers:[],status:o&&S.depends_on.every(N=>r.contract.children.filter(({name:k})=>k!==S.name).every(({name:k})=>k!==N))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let S of g){if(S.status!=="ready")continue;b.get(S.name).depends_on.length>0&&(S.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:S})=>S==="ready").map(({name:S})=>S),allDone:!1}}let s=await qD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await zD(p,c)){let S={...g,source:p,committedState:JD(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],S])}for(let g of c){let S=await WD(p,g);S&&u.set(g,[...u.get(g)??[],{source:p,state:S}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:N,committedState:k})=>N.parent&&k?.name===p.name&&qS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let S=u.get(p.name)??[];S.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):S[0]&&d.set(p.name,GD(S[0].state,S[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),N=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),E=k?.kind==="active"&&N?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>pm(F.projectRoot,k.projectRoot)&&$?.name===P&&qS($,a))):[],R,y=k?.message??null;k?.kind==="done"?(R=N?"done":"blocked",N||(y=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=N&&E.length===0?"active":"blocked",N?E.length>0&&(y=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):y=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&N?"ready":"pending",o||(y="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:y};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var Hs="skill-coordinated";function KD(e){return e.state_version+1}function YD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function XD(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:Ti(e.summary),completed_at:e.completedAt}}function wm(e){let t=ct(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=ln(t,XD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?YD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ct({...r,phase:"build",status:"active",state_version:KD(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as US}from"node:fs";import Ds from"node:path";function Vu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qu(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 Pi(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 GS(e,t){return e===null?null:Pi(e,t)}function zu(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 QD(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 ZD(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Wu(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ym(e,t){if(e===null)return null;let i=Pi(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Nm(e,t){let i=Pi(e,t);if(!Ds.isAbsolute(i))throw new Error(`${t} must be absolute`);return Ds.resolve(i)}function eL(e,t){let i=`Native local checks[${t}]`,r=Vu(e,i);if(qu(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)=>Pi(l,`${i}.argv[${u}]`,!0)),a=Wu(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=ym(r.startedAt,`${i}.startedAt`),s=ym(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=zu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Pi(r.id,`${i}.id`),name:Pi(r.name,`${i}.name`),operationId:Pi(r.operationId,`${i}.operationId`),status:a,repeatable:ZD(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:zu(r.executionCount,`${i}.executionCount`),argv:n,cwd:Nm(r.cwd,`${i}.cwd`),exitCode:QD(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Pi(r.log,`${i}.log`)}}function bm(e){let t="Native local execution state",i=Vu(e,t);if(qu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==zo)throw new Error(`Native local execution schema must be ${zo}`);let r=Vu(i.workspace,"Native local workspace");qu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Vu(i.execution,"Native local execution");qu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=ym(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Pi(o.operationId,"Native local execution.operationId"),stage:Wu(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Wu(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:GS(o.executionId,"Native local execution.executionId"),status:Wu(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:zu(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(eL);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:zo,change:Pi(i.change,"Native local change"),basedOnStateVersion:zu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Nm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Nm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:GS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function qr(e){return bm({schema:zo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ds.resolve(e.projectRoot),worktreeRoot:Ds.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ju(e){let t;try{t=await US.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 bm(i)}async function qi(e,t,i={}){let r=bm(t);await US.mkdir(Ds.dirname(e),{recursive:!0}),await ee(e,r,i)}import{promises as tL}from"node:fs";function Wr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
206
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Wi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function iL(e){return e.archived?Wt(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Wt(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Wt(e.language,"Verification passed; ready to archive","验收通过,可归档"):Wt(e.language,"Verification passed","验收通过")}function rL(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Wt(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?iL(e):e.verification_result==="blocked"?Wt(t,"Blocked","已阻塞"):e.verification_result==="fail"?Wt(t,"Failed","未通过"):Wt(t,"Pending","待处理")}function nL(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Hs?Hs:"host-attested"),i=t===Hs&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":i?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":i?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function aL(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let i=e.language,r=d=>Sd(i,d),n=(d,f)=>Wt(i,d,f),a=e.acceptance.map(d=>`| ${Wi(d.id)} | ${Wi(d.result)} | ${Wi(d.source)} | ${Wi(d.text)} | ${Wi(Wr(d.reason))} |`).join(`
207
+ `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(Wr).join(" ");return`| ${Wi(Wr(d.name))} | ${Wi(f||"—")} | ${Wi(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
208
+ `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Wr(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
209
+ `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Wr(d)}`).join(`
210
+ `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Wi(Wr(d.summary))} | ${d.completed_at} |`)].join(`
211
211
  `),u=t?.finalVerification.layers?`
212
212
  ## ${n("Supervisor evidence layers","Supervisor 分层证据")}
213
213
 
@@ -224,13 +224,13 @@ generated_from_state_version: ${e.state_version}
224
224
 
225
225
  ## ${r("currentResult")}
226
226
 
227
- - ${n("Result","结果")}: **${qD(e)}**
228
- - ${n("Verification status","验证情况")}: **${WD(e)}**
227
+ - ${n("Result","结果")}: **${rL(e)}**
228
+ - ${n("Verification status","验证情况")}: **${nL(e)}**
229
229
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
230
230
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
231
231
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
232
232
  - ${n("Completed","完成时间")}: ${e.verification.completed_at}
233
- - ${n("Summary","摘要")}: ${Br(e.verification.summary)}
233
+ - ${n("Summary","摘要")}: ${Wr(e.verification.summary)}
234
234
 
235
235
  ## ${r("acceptance")}
236
236
 
@@ -260,27 +260,28 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
260
260
 
261
261
  `:""}## ${r("conclusion")}
262
262
 
263
- ${Br(e.verification.summary)}
264
- `}function JD(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 Hu(e){let t;try{t=await BD.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=JD(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function Du(e){await he(e.file,zD(e.state,e.supervisor))}var BS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GD="comet-state.yaml",UD="state.json",EY=Us("en");function Lt(e,t){if(!BS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Vr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Pt(e,t){return Vr.join(Lt(e,t),GD)}function Nn(e,t){return Vr.join(We(e,t),UD)}async function qr(e,t){try{let i=await _s.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function KD(e){return fe(e).currentBranch}async function $a(e,t){return Ze(Pt(e,t))}async function YD(e){let t=await nn({file:Pt(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=Vr.join(Lt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await _s.rm(i,{force:!0})}return t}async function XD(e){let t=Lt(e.paths,e.state.name),i=Vr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await _s.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(!BS.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=Vr.join(t,...s.split("/")),l=await _s.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Vr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await _s.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 QD(e){let t=Lt(e.paths,e.state.name),i=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return hl({briefMarkdown:i.text,specs:r})}async function VS(e){let t=await XD(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 QD({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Oy(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await cm({changeDir:Lt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:sm({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?lm({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 qS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Yn(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:hr(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 YD({paths:e.paths,previous:t,next:r});return await Fr(Nn(e.paths,t.name),yn({portableState:n,projectRoot:e.paths.projectRoot,branch:KD(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Lu(e){if(e.state.verification===null)return"not-applicable";let t=Vr.join(Lt(e.paths,e.state.name),"verification.md");return await Hu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Du({file:t,state:e.state}),"rebuilt")}async function WS(e){let t=await $a(e.paths,e.name),i=Nn(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 IY=16*1024;async function Mu(e){let t=await Zp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Ul(t.selection.change),t.selection)}function zS(e){return Pu(e.projectRoot)}async function Ts(e,t){return await Wn(e.projectRoot),vS(e.projectRoot,"native",t)}var s4=16*1024*1024,Fu=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"},Is=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 GS(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 Oa.resolve(e.nativeRoot,...i.target.split("/"))}async function US(e,t,i){let r=await Nr(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await ni(GS(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=GS(e,t),o=Oa.join(a,Te),s=await db(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 $e(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 p=Um(Ni,l,new Set,xp,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=Km(Ni,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},xp,void 0)}let d=L(`archive:${t.id}:${s.name}`),f=await it(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!ZD(v.data,m)||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 Eu(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await ta(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await ub(o,p)}v||(v=await Tr({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await vn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await un(c,u),await Ts(e,s.name),t.schema==="comet.native.transaction.v2"?await Eu(e,t,"archive-finalized"):await ta(e,t,"archive-finalized")}async function pm(e,t){let i=We(e,t);try{let r=await JS.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 JS.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 eL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Nr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Nu({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Is(c,"Native Archive facts changed before the first transaction operation")}let o=await fS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await He(e,t.change),u=await yu({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 US(e,o,i);let s=await Eu(e,o,"commit");return{journal:s,runtimeCleanupWarning:await pm(e,s.change)}}let r=await oN(e,t);await US(e,r,i);let n=await ta(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await pm(e,n.change):null}}function tL(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(Oa.resolve(t.projectRoot)!==Oa.resolve(e.projectRoot)||Oa.resolve(t.nativeRoot)!==Oa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function KS(e){return se(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await dr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await yt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Xp(e.paths,e.transactionId):i;return tL(e.paths,r),r.status==="committed"?(r.change&&await pm(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await eL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?hS(e.paths,r):_l(e.paths,r)}finally{await fr(t)}},{allowedTransactionId:e.transactionId})}import{promises as vL}from"fs";async function YS(e,t){let i=[],r=H(e,t.name),n=lr(r,Nt.stateRef),a;try{a=await $e(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=lr(r,a.trajectoryRef),s=await la(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await it(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=lr(r,a.checkpointRef);try{let u=await ca(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 iL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function nL(e){return e?e.map(rL).join(" "):null}function aL(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 Mt(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 oL(e){return e.map(t=>Mt(t,[],null))}function sL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Mt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Mt("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(Mt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Mt("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(Mt("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(Mt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Mt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ke(e,t){let i=t.commandArgs===void 0?aL(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?nL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??oL(t.requiredInputs??[])}}function Bu(e){let i=(e.findings??[]).filter(d=>!ua(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||iL.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 Ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Mt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]});if(n)return Ke(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 Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ke(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"),Ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Mt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ke(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=sL(e.state);return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import js from"path";var XS=8,cL={"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 lL(e){let t=cL[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"}:ua(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 uL(e,t,i){if(!i.path)return null;let r;if(js.isAbsolute(i.path)?r=js.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=js.resolve(ne(e,t.name),...i.path.split(/[\\/]/u)):r=js.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=js.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function dL(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 mm(e){return e.findings.map(t=>{let i=lL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:uL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:dL(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 vm(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,XS),truncated:t.length>XS}}var QS=240,ZS=8,Vu=50;function eE(e){let t=Array.from(e);return t.length<=QS?e:`${t.slice(0,QS-1).join("")}…`}function fL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function hL(e){let t=[...new Set(e.map(fL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,ZS),reasonCount:e.length,codesTruncated:t.length>ZS};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Vu),reasonsTruncated:e.length>Vu}}}async function tE(e){let t=null;try{let s=await Or(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:$r(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:$r(e.paths,e.state.name)}}let i=await qk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=hL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:jr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:eE(i.checkpoint.summary),nextAction:eE(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:jr.maxArtifacts}}async function pL(e,t){let i=H(e,t.name),r=await $e(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 ca(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 it(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function mL(e,t){let i=await pL(e,t);return{committed:i,latest:yk(i),history:wk(i)}}async function iE(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await mL(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 gL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ha=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function gm(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function wL(e){return(await Mu(e))?.change??null}function yL(e,t,i=!1,r){return Bu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function NL(e,t){let i=ne(e,t.name),r=[...(await tp(i,t.brief)).findings,...(await vb(e,t)).findings,...await YS(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await sa(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 Dl(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 Ca({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 Mi(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 ip(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 wm(e,t,i){let r=await wL(e)===t,n=await jo(e,t),a=await QN(e,t),o;try{let w=await vi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected: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:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected: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:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){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:w.message}}if(n.status!=="available"){let w={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=mm({paths:e,state:o,findings:[w]}),F=Bu({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:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:vm(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await tE({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await iE(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,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 w=await Ca({changeDir:ne(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 Fe=await Pa(e,o.name,o.verification_evidence);for(let ue of Fe.acceptanceTrace.entries)P.set(ue.acceptanceId,ue.status==="failed"?"failed":ue.status==="missing"?"missing":"satisfied")}let F=xy({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:gm($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await cu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.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 w=await kt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await fa({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Qo({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.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 w=await Qk({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await Nu({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await NL(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=mm({paths:e,state:o,findings:b}),y=g.filter(w=>!ua(w.code)),E=o.phase==="archive"&&m?.ready===!0&&y.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),S=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=g.find(w=>w.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:S||R?null:yL(o,E,k,i?.clarificationMode),archiveReady:E,inspection:s.inspection,findingSummary:vm(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Bu({state:o,findings:g,archiveReady:E,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Vu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function bL(e){let t;try{t=await Qt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await vL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ha.maxChanges))throw new Error(`Native status exceeds ${Ha.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function qu(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function kL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=gL.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=D("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 SL(e,t){let i=await bL(e),r=D("comet.native.status-names.v1",i),n=kL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ha.maxItems).map(u=>wm(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?qu(r,f):null,nextPageCommand:f<i.length?gm(["comet","native","status","--cursor",qu(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",qu(r,f)]:null,limits:{...Ha}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Ha.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?qu(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?gm(l):null,nextPageArgs:l,limits:{...Ha}}}async function ym(e,t){return(await SL(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as VL,randomUUID as qL}from"node:crypto";import{constants as Em,promises as Q}from"node:fs";import le from"node:path";var Ju=Rn(Qr(),1);import{randomUUID as EL}from"crypto";import{promises as sE}from"fs";import bm from"path";import{isDeepStrictEqual as km}from"util";var bn=/^[a-f0-9]{64}$/u,PL=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),RL=new Set(["sourceHash","targetHash","nextJournal"]),CL=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),rE=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),xL=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Wu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function nE(e){return JSON.stringify(e,null,2)+`
265
- `}function Sm(e){return e.schema===be?Kl(e):dn(e)}function Nm(e,t){return{...e,schema:be,minimum_runtime_version:2,revision:t}}function AL(e){return{...e,schema:Ti,minimum_runtime_version:2,revision:1,previousState:Nm(e.previousState,1),nextState:Nm(e.nextState,2)}}function zu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ne,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 _L(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?L(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:pr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:zu(e.previousState),nextState:{...zu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Ni.definition.metadata.version,skillHash:gs}:e.nextRun}}function aE(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Da(e,t){return JSON.stringify(Kl(e))===JSON.stringify(Kl(t))}function oE(e,t){return JSON.stringify(dn(e))===JSON.stringify(dn(t))}function Vi(e,t){return km(e,t)}function TL(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(Wu(n,CL,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!bn.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"||!bn.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Er(n.previousRun),o=Er(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||!Vi(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!==rE.size||u.some(f=>!rE.has(f))||l.fromSchema!==be||l.toSchema!==Ne||!["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=L(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 $s(e,t){return bm.join(H(e,t),"schema-migration.json")}function IL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Wu(e,PL,"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===et&&i.toSchema===be,n=i.fromSchema===be&&i.toSchema===Ne;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"||!bn.test(i.sourceHash)||typeof i.targetHash!="string"||!bn.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?di(i.nextState):lt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(L((0,Ju.stringify)(Sm(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");Wu(i.transition,RL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!bn.test(l.sourceHash)||typeof l.targetHash!="string"||!bn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?Hp(l.nextJournal,t):Op(l.nextJournal,t);if(L(JSON.stringify(l.nextJournal,null,2)+`
266
- `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===be?Da(a,u.previousState)||Da(a,u.nextState):a.schema===Ne&&(oE(a,u.previousState)||oE(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!==Ne)throw new Error("Schema migration transition supersede target schema is invalid");s=TL(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");Wu(i.runRetreat,xL,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Er(l.previousRun),d=Er(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!bn.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!==Ne||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 Os(e,t){let i=$s(e,t),r=j(e,i);await T(r,i);try{let n=await Sl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return IL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function jL(e,t,i){let r=await sa(e,t),n=r?await Dl(e,r):await Ll(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Bh(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 ha(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Wh(e,t,n)}async function cE(e){try{return await Zt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function $L(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 lE(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await it(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&&!km(o.event,$L(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 OL(e,t,i){if(!t.transitionSupersede)return;let r=Ue(e,t.change),n=await cE(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 $e(a),s=await lE(e,t),c=await ca(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Vi(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!==L(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function HL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await $e(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Vi(a,r.nextRun)){if(!Vi(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await un(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Vi(await $e(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await lE(e,t);if(o.sequence===null){let l=await Tr({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 vn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ue(e,t.change),c=await cE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await sE.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function DL(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await $e(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Vi(n,t.runRetreat.nextRun)){if(!Vi(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await un(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await it(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Tr({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 vn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function LL(e,t,i){let r=await Os(e,t);if(!r)return null;if(await ma(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=bm.join(ne(e,t),Te),a=await Zt(n);if(await OL(e,r,a===r.targetHash),await jL(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 he(n,(0,Ju.stringify)(Sm(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ue(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 ee(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await HL(e,r,i),await DL(e,r,i),await sE.rm($s(e,t),{force:!0}),r.nextState}async function ML(e){let t=H(e.paths,e.state.name),i=await $e(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=L(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:be,toSchema:Ne,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function FL(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=Da(i,t.previousState),a=Da(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 $e(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Vi(s,t.previousRun),l=Vi(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 it(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).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(!km(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...zu(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,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=L(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(Ue(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:be,toSchema:Ne,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function BL(e){let t,i,r,n;if(e.state.schema===et){if(t=Nm(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==an)throw new Error("Native v1 change has a transition from another schema generation");let s=AL(e.pendingTransition.journal);if(aE(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(aE(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=Ue(e.paths,e.name);i={sourceHash:await Zt(c),targetHash:L(nE(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Ti)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 FL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=_L(s);if(Da(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Da(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=Ue(e.paths,e.name);i={sourceHash:await Zt(u),targetHash:L(nE(l)),nextJournal:l}}}else t=zu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await ML({paths:e.paths,state:e.state,migrationId:e.id}));let a=bm.join(ne(e.paths,e.name),Te),o=(0,Ju.stringify)(Sm(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===et?be:Ne,sourceHash:await Zt(a),targetHash:L(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function uE(e){return se(e.paths,`migrate schema for ${e.name}`,()=>gn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await LL(e.paths,e.name,e.hooks);if(i?.schema===Ne)return i;let r=await vi(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 ma(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!==et&&n.schema!==be)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Dp(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 BL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??EL()}),s=$s(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ee(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var qi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),WL=512*1024,kn=/^([a-f0-9]{64})\.json$/u,zL=/^\.([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,JL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Gu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Rm(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pi(e,t){return Rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function mE(e,t){return Rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function La(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return e<t?-1:e>t?1:0}function GL(e,t){let i=le.relative(e.projectRoot,t);if(i.length===0||le.isAbsolute(i)||i===".."||i.startsWith(`..${le.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(le.sep).join("/")}function vE(e,t){return le.join(H(e,t),"evidence")}function Uu(e,t){return GL(e,vE(e,t))}async function Ku(e,t){let i=le.resolve(e),r=le.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=le.relative(i,r).split(le.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=le.join(o,s));let c=await Q.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Q.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...La(c)})}return a}async function Ft(e){for(let t of e){let i=await Q.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Rm(t,i)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function gE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:Ea(e,t)}function dE(e){return e!==null&&JL.test(e)?[e]:[]}function UL(e,t,i,r){if(e==="snapshots")return{canonical:wa(i,t),dependencies:[]};if(e==="scopes"){let a=ya(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=ru(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[Ea("scopes",a.scopeHash)]}}if(e==="verifications"){let a=fs(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(dE));return{canonical:a,dependencies:[a.implementationScopeRef,ck(a.reportHash),...dE(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"||VL("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=au(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=nu(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 Wr(e){let t=await Q.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"?WL:_r;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await Q.realpath(e.file);if(!O(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Em.O_RDONLY|Em.O_NOFOLLOW|Em.O_NONBLOCK,a=await Q.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(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Pi(La(t),o)||!Pi(La(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,y=await a.read(u,0,Math.min(u.length,g),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,y.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Pi(La(o),f)||!Pi(La(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=UL(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
267
- `)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:La(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(nt)}}finally{await a.close()}}async function fE(e){try{return await Q.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function KL(e){let t=H(e.paths,e.name),i=t,r=vE(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Ku(t,r);n=await Q.readdir(r,{withFileTypes:!0}),await Ft(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Gu){if(!n.some(f=>f.name===s))continue;let c=le.join(r,s),l=await Ku(t,c),u=(await Q.readdir(c,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name)),d=new Map;for(let f of u){let h=zL.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],[m])=>nt(v,m))){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 m=le.join(c,f),p=kn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=gE(s,p),g=le.join(c,v.name),y=await Wr({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),E=await fE(m),k=E?null:await Wr({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:y,action:E?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ma(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Yu(o)}`),path:Uu(e.paths,e.name)}]};for(let s of a.sort((c,l)=>nt(c.ref,l.ref))){if(await Ft(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Wr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Wr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Pi(s.originalDocument.identity,d.identity)||!Pi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain);continue}if(!await fE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Q.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Pi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Q.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Wr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Wr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!mE(s.document.identity,l.identity)||!Pi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ma(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Yu(o)}`),path:Uu(e.paths,e.name)}]}}async function YL(e,t){let i=H(e,t),r=i,n=le.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Ku(i,n);a=await Q.readdir(n,{withFileTypes:!0}),await Ft(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Gu.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(nt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Yu(o)}`);let s=[],c=0;for(let l of Gu){if(!a.some(h=>h.name===l))continue;let u=le.join(n,l),d=await Ku(r,u),f=(await Q.readdir(u,{withFileTypes:!0})).sort((h,v)=>nt(h.name,v.name));await Ft(d);for(let h of f){if(s.length>=qi.maxDocuments)throw new Error(`Native evidence store exceeds ${qi.maxDocuments} documents`);let v=kn.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 m=gE(l,v[1]),p=le.join(u,h.name);await T(j(e,p),p);let b=await Wr({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>qi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${qi.maxScannedBytes} scanned bytes`);s.push(b)}await Ft(d)}return s}function hE(e,t){let i=new Set,r=[...e].sort(nt).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(nt).reverse())i.has(o)||r.push(o)}return i}function XL(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(nt),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(nt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function QL(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=hE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<qi.minimumAgeMs&&a.add(c.ref);for(let c of Gu){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,qi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=hE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=qi.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:XL(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Yu(e){let t=e.slice(0,qi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Ma(e){let t=qi.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 Pm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ma(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Yu(n)}`),path:r}}async function pE(e,t){try{await Q.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await Q.rename(e,t)}catch{}}async function ZL(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ft(e.directoryChain);let i=await Wr({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:kn.exec(le.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await Q.lstat(e.file),n=await Q.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Pi(e.identity,r)||!Pi(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=le.join(le.dirname(e.file),`.${le.basename(e.file)}.${qL()}.gc`);await Q.rename(e.file,a);try{let[o,s]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await Ft(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!mE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await pE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Q.rm(a),await Ft(e.directoryChain)}catch(o){throw await pE(a,e.file),o}}async function eM(e){if((await ye(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await Q.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 yt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function tM(e,t){if(t)return[t];let i;try{i=await Q.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(nt)}async function iM(e,t){let i=await vi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Mi(e,t),Os(e,t),Or(e,t)]);return r!==null||n!==null||a!==null}async function rM(e){if(await iM(e.paths,e.name))return[];let t=await vi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await KL({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 YL(e.paths,e.name),a=QL(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Uu(e.paths,e.name);if(!e.repair)return[...i.findings,Pm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await ZL(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Pm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ma(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Pm(e.name,a,!0,o)]}async function wE(e){if(e.deferAll||await eM(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 tM(e.paths,e.name))try{a.push(...await rM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ma(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Uu(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 se(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ma(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as nM,randomUUID as F6}from"crypto";import{promises as Ls}from"fs";import ae from"path";var xm=64*1024*1024,aM=256*1024,kE=16*1024*1024;async function at(e){try{return await Ls.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function oM(e){let t;try{t=await Ls.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 kt(e,i.name);if(r){await Jl({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 Ds(e,t){let i=[];async function r(n){let a=await wt({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=ae.join(n,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await Ls.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:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await re({root:e,file:c,maxBytes:xm,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.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 sM(e,t,i,r){await fi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await wt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await Ls.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await fi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await wr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:xm,label:`Native root move file ${ae.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 Fa(e,t,i,r){let n=await Ds(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await Ds(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ae.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 cM(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function lM(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function uM(e){return`${e}.removing`}function yE(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function SE(e,t,i){return ae.join(Al(e,t).directory,`root-move-cleanup-${i}.json`)}function dM(e){return JSON.stringify(e,null,2)+`
268
- `}function fM(e){return nM("sha256").update(e).digest("hex")}function hM(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("\\")||ae.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 pM(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(hM);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=ae.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 mM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=dM(t);if(Buffer.byteLength(i,"utf8")>kE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await he(SE(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),fM(i)}async function vM(e){let t=await re({root:e.paths.runtimeDir,file:SE(e.paths,e.id,e.cleanup.kind),maxBytes:kE,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 pM(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Cm(e){let t=await Ds(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 NE(e){return e.ref.split("/").length}async function gM(e){let i=[...await Cm({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>NE(a)-NE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ae.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await El({root:e.projectRoot,file:a,maxBytes:xm,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Ph({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 Cm({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Ph({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function EE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function wM(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 yM(e,t,i,r){for(let a of[e,t])try{let o=await yt(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=ae.join(i,"runtime","transactions",r,"transaction.json");try{let a=await re({root:i,file:n,maxBytes:aM,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 bE(e){let t=EE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await ur(e.projectRoot,t),t}async function Hs(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=EE(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 ur(e.projectRoot,i),i}async function Xu(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 at(e.target),a=await at(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 mM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ds(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await vM({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await at(e.target),a=await at(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 Uy({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 Hs({projectRoot:e.projectRoot,config:t,id:e.id})}return await Cm({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await gM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Hs({projectRoot:e.projectRoot,config:t,id:e.id})}async function NM(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await at(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=uM(e.staging);t=await Xu({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 Ds(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await sM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Fa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await bE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await at(e.destinationPaths.nativeRoot)){if(await at(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Fa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await at(e.staging))throw new Error("Native move staging tree is missing");await Fa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ls.rename(e.staging,e.destinationPaths.nativeRoot)}t=await bE({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 at(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=lM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await at(e.sourcePaths.nativeRoot)&&await Fa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Xu({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 oM(e.destinationPaths);let n=await yt(e.destinationPaths,e.pending.id);await ta(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 ur(e.projectRoot,o),o}async function PE(e){let t=await ye(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await qe(e.projectRoot,i.fromArtifactRoot),n=await qe(e.projectRoot,i.toArtifactRoot),a=cM(n,i.id),o=await at(r.nativeRoot)?r:n,s=await dr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await yM(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await at(r.nativeRoot))throw v;let m=wM({id:i.id,paths:r,now:new Date});await nN(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await NM({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 at(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=yE(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await at(n.nativeRoot)&&await Fa(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Xu({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=yE(a,i.id);!t.native.pending_root_move?.cleanup&&await at(a)&&await Fa(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Xu({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 yt(r,i.id);await _l(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 ur(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await fr(s)}}var Ba=4096,bM=4096,kM=1024;async function zr(e,t,i){try{let r=await wt({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 Zu(e,t){let i=new Map(e.map(r=>[Ie.resolve(r.file),{...r,file:Ie.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await $o(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 hh(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 SM(e,t){let i=zS(e),r;try{await T(e.projectRoot,i);let n=await Mu(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 qr(e,r.change)?[]:(await He(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 Qu.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 EM(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 PM(e,t){let i=[],r=[];for(let n of await zr(e,e.transactionsDir,bM)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await yt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ie.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 zn([e],`doctor archive recovery ${a.id}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,"archive.lock")}],i)?(await KS({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 RM(e,t,i){let r=[];for(let n of await zr(e,e.locksDir,kM)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ie.join(e.locksDir,n.name);try{let o=await $o(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 hh(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 CM(e,t,i=5){let r=[],n=t?await ym(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await ym(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:Ie.join(e.changesDir,a.name,Te)});continue}let o=await wm(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:Ie.join(e.projectRoot,s.path)}:{}})}return r}async function xM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await la(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 qN(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:Ie.join(H(e,n),"trajectory.jsonl")})}return i}async function AM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await jo(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=tn(e,n),s=We(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 zn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Qt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await Qu.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Qt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Qu.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 Qu.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 _M(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Yh(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:da(e,n),repair:"migrate"});continue}let a=await He(e,n);await eb({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:da(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:da(e,n)})}return i}async function TM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=$s(e,n);try{let o=await Os(e,n),s=await vi(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:Ie.join(e.changesDir,n,Te)});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:Ie.join(e.changesDir,n,Te),repair:"migrate"});continue}await uE({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:Ie.join(e.changesDir,n,Te)})}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 IM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Mi(e,n)}catch(o){if(o instanceof ws)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ue(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await zn([e],`doctor transition recovery ${n}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,`transition-${n}.lock`)}],i)?(await jk(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ue(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ue(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:Ue(e,n),repair:"continue"})}}return i}async function jM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=$r(e,n),o;try{o=await Or(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 zn([e],`doctor checkpoint recovery ${n}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,`transition-${n}.lock`)}],i)?(await zk(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 Ms(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await ye(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([qe(r.projectRoot,c.fromArtifactRoot),qe(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Zu([{paths:l,file:Ie.join(l.locksDir,"root-move.lock")},{paths:u,file:Ie.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await PE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await qe(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 EM(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await PM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await AM(r,{name:e.name,repair:t})),i.push(...await TM(r,{name:e.name,repair:t})),i.push(...await _M(r,{name:e.name,repair:t})),i.push(...await xM(r,{name:e.name,repair:t})),i.push(...await IM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await jM(r,{name:e.name,repair:t})),i.push(...await wE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await RM(r,t,s.unfinished)),i.push(...await SM(r,t)),e.projectOnly||i.push(...await CM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as $M}from"node:crypto";import{promises as Me}from"node:fs";import ht from"node:path";var Am=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 RE(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function CE(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=ht.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ed(e){try{return await Me.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function xE(e,t){let i=ht.normalize(ht.resolve(e)),r=ht.normalize(ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function OM(e,t){let i;try{i=await Me.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=ht.join(e.archiveDir,n.name);try{let o=await Ze(ht.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 HM(e,t){let i=await bl(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Sn(e,t){await Me.mkdir(e.transactionsDir,{recursive:!0}),await ee(mr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function DM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Jt(e.paths.projectRoot);i.some(a=>xE(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await ye(a);if(!o)continue;let s=await qe(a,o.native.artifact_root);r.some(c=>xE(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 Me.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 Ze(ht.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 Xl(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 LM(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 MM(e){let t=ht.join(e.paths.specsDir,e.change.capability),i=ht.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Me.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 Me.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([Me.realpath(e.paths.specsDir),Me.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Me.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Me.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Me.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=ht.join(Lt(e.paths,e.state.name),e.change.source);await he(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Me.mkdir(t,{recursive:!0}),await he(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function AE(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 FM(e,t){let i=Lt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Z({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function BM(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(AE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function _m(e){return se(e.paths,`archive portable change ${e.name}`,async()=>{let t=LM(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await HM(e.paths,e.name),r=Lt(e.paths,e.name),n=await ed(r),a=n?null:await OM(e.paths,e.name),o;if(n)o=await $a(e.paths,e.name);else if(i)o=await Ze(ht.join(CE(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}`);let s=await Mr(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await VS({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await qS({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}let c=CE(e.paths,i?.archive_ref??RE(o)),l=await ed(c);if(i&&BM(i,o),n&&l)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 Ts(e.paths,o.name),await Me.rm(We(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)AE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await DM({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Am(d);i={schema:Nl,id:$M(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:RE(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await FM(e.paths,o),created_at:new Date().toISOString()},await Sn(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await Sn(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await Ps({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await MM({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await Sn(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await Sn(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await Ps({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await nn({file:Pt(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Sn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await ed(r)?r:c;if(await Du({file:ht.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Hu({file:ht.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Sn(e.paths,i),s&&!u&&(await Ps({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await Ps({paths:e.paths,state:s}),await Me.mkdir(e.paths.archiveDir,{recursive:!0}),await ed(c))throw new Error(`Native Archive target already exists: ${c}`);await Me.rename(r,c),i={...i,status:"moved"},await Sn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await Ts(e.paths,o.name),await Me.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Me.rm(mr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function En(e,t,i){return e.language==="zh-CN"?i:t}function VM(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:En(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:En(e,"Reply A or B","回复 A 或 B"),agentInstruction:En(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready")return i(En(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(En(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(En(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function Im(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function td(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function _E(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function qM(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function WM(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function zM(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function Fs(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Im({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[td("summary","--summary"),_E(e.name,e.flag)]}}function Tm(e){return[Fs({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Fs({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function id(e,t){let i=WM(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:VM(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:[Fs({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Tm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Im({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:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:[Fs({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Tm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:Tm({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?Im({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:zM({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[qM("coordination-mode","--coordination-mode",Hy)]:[],_E("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,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:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,disposition:"continue",action:"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:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,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:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${En(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{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:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Fs({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as JM}from"node:crypto";import{promises as Va}from"node:fs";import DE from"node:path";var jm=["evidence.md","repair.md","archive.md","checkpoint.md"],GM="verification.md";async function UM(e){try{return await Va.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $m(e,t){let i=ne(e,t),r=[mr(e,{kind:"migration",change:t}),tn(e,t),...jm.map(n=>DE.join(i,n))];return(await Promise.all(r.map(UM))).some(Boolean)}async function KM(e,t){let i=await bl(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function TE(e,t){await Va.mkdir(e.transactionsDir,{recursive:!0}),await ee(mr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function IE(e,t,i={}){let r=i.removeVerificationReport===!1?jm:[...jm,GM];await Promise.all([Va.rm(We(e,t),{recursive:!0,force:!0}),Va.rm(tn(e,t),{recursive:!0,force:!0}),...r.map(n=>Va.rm(DE.join(ne(e,t),n),{force:!0}))])}async function jE(e,t){await Fr(Nn(e,t.name),yn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function $E(e,t){try{let i=await kt(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 OE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=fe(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 YM(e){let t=ne(e.paths,e.state.name),i=await Z({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 Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return hl({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function HE(e,t){let i=await Xl(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Bs(e){return se(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await KM(e.paths,e.name),i=await qr(e.paths,e.name)?await Ze(Pt(e.paths,e.name)):null;if(!t&&i)return await IE(e.paths,e.name,{removeVerificationReport:!1}),await jE(e.paths,i),i;let r=null,n=null;for(t||(r=await HE(e.paths,e.name),n=await $E(e.paths,e.name),OE(e.paths,n),t={schema:yl,id:JM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await TE(e.paths,t));;){let a=My(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await HE(e.paths,e.name),n??=await $E(e.paths,e.name),OE(e.paths,n),i=Ly({state:r,acceptance:await YM({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await wl(Pt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await IE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ze(Pt(e.paths,e.name)),await jE(e.paths,i)),t={...t,status:a.nextStatus},await TE(e.paths,t)}return await Va.rm(mr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ze(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as LE}from"node:fs";import ME from"node:path";function XM(e,t){let i=fe(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 QM(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function ZM(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:Yn(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:hr(t),completed_at:r});return ct({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?QM(e):e.acceptance,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 eF(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 FE(e){return se(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $a(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=XM(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Nn(e.paths,e.name),n=await eF(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 Fr(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=um({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await nn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await LE.rm(ME.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=yn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Fr(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=ZM(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.",l);t=await nn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=yn({portableState:t,projectRoot:e.paths.projectRoot,branch:fe(e.paths.projectRoot).currentBranch});return await LE.mkdir(ME.dirname(Nn(e.paths,t.name)),{recursive:!0}),await Fr(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 VE}from"node:fs";import iF from"node:path";function tF(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function BE(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:tF(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function rF(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function nF(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function aF(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:cF(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:lF(r,i)}))]:[]]}function oF(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 qE(e,t){let i=fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:iF.resolve(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}}function sF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function rd(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function cF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:rd(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function lF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:rd(e.summary,t)??""}}async function qa(e){let t=await WS(e),i=BE(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Cs({paths:e.paths,state:t.state}),a=await Mr(e.paths,e.name),o=a?{...qE(e.paths,t.state),projectRoot:"."}:qE(e.paths,t.state),s=id(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?sF(e.paths,a):[],u=a?(()=>{let h=a.children.filter(({status:y})=>y==="pending"||y==="ready").length,v=a.children.filter(({status:y})=>y==="active"||y==="verified").length,m=a.children.filter(({status:y})=>y==="integrated"||y==="archived").length,p=a.children.filter(({status:y})=>y==="blocked"||y==="needs-reverify").length,b=a.children.filter(({status:y})=>y==="active"||y==="blocked"||y==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:rd(y.blocker,l)})),g=a.children.flatMap(({blocker:y})=>{let E=rd(y,l);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:h,working:v,integrated:m,blocked:p,active:b,agents:{working:a.children.filter(({task:y})=>y!==null).length,completed:m},risks:g,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&m===a.children.length?"parent-verification":h>0?"dispatch-ready-child":p>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let h=a?.stateVersion??0,v=aF(t.state,a,l),m=nF(e.cursor,t.state.state_version,h),p=v.slice(m,m+32),b=m+p.length<v.length?rF(t.state.state_version,h,m+p.length):null;return{items:p,nextCursor:b,supervisorStateVersion:h}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:oF(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((h,v)=>({...h,[v.status]:(h[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function WE(e){let t;try{t=await VE.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 VE.readFile(`${Lt(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 Vs from"path";import{realpathSync as EF}from"fs";var Wi={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function zE(e){return e?e.command?`${Wi.next} ${e.command}`:e.ask_user?`${Wi.next} ${e.ask_user}`:null:null}function JE(e,t){let i=[e.summary],r=zE(e.next);return r&&i.push(r),e.user_message&&i.push("",Wi.relay,e.user_message),t!==void 0&&i.push("",Wi.details,JSON.stringify(t,null,2)),`${i.join(`
263
+ ${Wr(e.verification.summary)}
264
+ `}function oL(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 Gu(e){let t;try{t=await tL.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=oL(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function Uu(e){await he(e.file,aL(e.state,e.supervisor))}var KS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sL="comet-state.yaml",cL="state.json",t4=tc("en");function Mt(e,t){if(!KS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=zr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Pt(e,t){return zr.join(Mt(e,t),sL)}function Jr(e,t){return zr.join(We(e,t),cL)}async function Gr(e,t){try{let i=await Rn.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function YS(e){return fe(e).currentBranch}async function zi(e,t){return Ze(Pt(e,t))}async function XS(e){let t=await un({file:Pt(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=zr.join(Mt(e.paths,t.name),"verification.md");await I(e.paths.nativeRoot,i),await Rn.rm(i,{force:!0})}return t}async function lL(e){let t=Mt(e.paths,e.state.name),i=zr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Rn.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(!KS.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=zr.join(t,...s.split("/")),l=await Rn.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=zr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await Rn.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 uL(e){let t=Mt(e.paths,e.state.name),i=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(lp(i.text))throw new Error("Brief has a blocking open question");let r=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await Z({root:t,ref:a.source,maxBytes:null,includeHash:!1});r.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:H("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Sl({briefMarkdown:i.text,specs:r}),formalHash:H("comet.native.shape-formal-artifacts.v1",{brief:{source:i.ref,contentHash:H("comet.native.shape-artifact-content.v1",i.text)},specs:n})}}function dL(e){return H("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function QS(e){let t=await lL(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&(l.operation===d.operation||i?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await uL({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!qy(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await $s({changeDir:Mt(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:vm({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&dL({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?gm({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function ZS(e){let t=await zi(e.paths,e.name),i=await Dt(e.paths,e.name),r=await aa(e.paths,{kind:"archive",change:e.name}),n=r?.kind==="archive"?r:null;if(n&&i?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await Rn.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||i?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=jS(i);if(n||a.stateVersion!==i.stateVersion){let o=await fL({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await Rn.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await Pn(e.paths,$S(i,t)),{state:t,action:"recorded-final-verification"}}async function eE(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...ln(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ti(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:"prepare-shape-confirmation"}};delete r.shape_confirmation_hash,delete r.children_contract_hash;let n=await XS({paths:e.paths,previous:t,next:r});return await qi(Jr(e.paths,t.name),qr({portableState:n,projectRoot:e.paths.projectRoot,branch:YS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function fL(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let r={...ln(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ti(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await XS({paths:e.paths,previous:t,next:r});return await qi(Jr(e.paths,t.name),qr({portableState:n,projectRoot:e.paths.projectRoot,branch:YS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ku(e){if(e.state.verification===null)return"not-applicable";let t=zr.join(Mt(e.paths,e.state.name),"verification.md");return await Gu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Uu({file:t,state:e.state}),"rebuilt")}async function tE(e){let t=await zi(e.paths,e.name),i=Jr(e.paths,e.name);try{let r=await Ju(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 l4=16*1024;async function Yu(e){let t=await cm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(ru(t.selection.change),t.selection)}function iE(e){return $u(e.projectRoot)}async function Ls(e,t){return await Zn(e.projectRoot),PS(e.projectRoot,"native",t)}var L4=16*1024*1024,Xu=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"},Ms=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 nE(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 qa.resolve(e.nativeRoot,...i.target.split("/"))}async function aE(e,t,i){let r=await Er(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await oi(nE(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=nE(e,t),o=qa.join(a,Te),s=await Nb(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=D(e,s.name),l=await Oe(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 p=iv(bi,l,new Set,Dp,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=rv(bi,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Dp,void 0)}let d=L(`archive:${t.id}:${s.name}`),f=await it(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!hL(v.data,m)||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 ju(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await ua(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await yb(o,p)}v||(v=await Or({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await kn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await vn(c,u),await Ls(e,s.name),t.schema==="comet.native.transaction.v2"?await ju(e,t,"archive-finalized"):await ua(e,t,"archive-finalized")}async function km(e,t){let i=We(e,t);try{let r=await rE.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await I(e.runtimeDir,i),await rE.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 pL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Er(e,t.id)).some(c=>c.type==="operation-started")){let c=await Au({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Ms(c,"Native Archive facts changed before the first transaction operation")}let o=await bS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await De(e,t.change),u=await xu({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 aE(e,o,i);let s=await ju(e,o,"commit");return{journal:s,runtimeCleanupWarning:await km(e,s.change)}}let r=await mN(e,t);await aE(e,r,i);let n=await ua(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await km(e,n.change):null}}function mL(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(qa.resolve(t.projectRoot)!==qa.resolve(e.projectRoot)||qa.resolve(t.nativeRoot)!==qa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function oE(e){return se(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await vr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await yt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await om(e.paths,e.transactionId):i;return mL(e.paths,r),r.status==="committed"?(r.change&&await km(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await pL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?kS(e.paths,r):Ml(e.paths,r)}finally{await gr(t)}},{allowedTransactionId:e.transactionId})}import{promises as _L}from"fs";async function sE(e,t){let i=[],r=D(e,t.name),n=pr(r,Nt.stateRef),a;try{a=await Oe(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=pr(r,a.trajectoryRef),s=await wa(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await it(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=pr(r,a.checkpointRef);try{let u=await ga(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 vL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function gL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function wL(e){return e?e.map(gL).join(" "):null}function yL(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 Ft(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 NL(e){return e.map(t=>Ft(t,[],null))}function bL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Ft("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Ft("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(Ft("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Ft("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(Ft("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(Ft("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Ft("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ke(e,t){let i=t.commandArgs===void 0?yL(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?wL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??NL(t.requiredInputs??[])}}function Qu(e){let i=(e.findings??[]).filter(d=>!ya(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||vL.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 Ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Ft("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Ft("summary",["--summary"],"<summary>")]});if(n)return Ke(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 Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Ft("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ke(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"),Ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Ft("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ke(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=bL(e.state);return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Fs from"path";var cE=8,kL={"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 SL(e){let t=kL[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"}:ya(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 EL(e,t,i){if(!i.path)return null;let r;if(Fs.isAbsolute(i.path)?r=Fs.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Fs.resolve(ne(e,t.name),...i.path.split(/[\\/]/u)):r=Fs.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=Fs.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function PL(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 Sm(e){return e.findings.map(t=>{let i=SL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:EL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:PL(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 Em(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,cE),truncated:t.length>cE}}var lE=240,uE=8,Zu=50;function dE(e){let t=Array.from(e);return t.length<=lE?e:`${t.slice(0,lE-1).join("")}…`}function RL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function CL(e){let t=[...new Set(e.map(RL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,uE),reasonCount:e.length,codesTruncated:t.length>uE};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Zu),reasonsTruncated:e.length>Zu}}}async function fE(e){let t=null;try{let s=await Mr(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Lr(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:Lr(e.paths,e.state.name)}}let i=await Qk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=CL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Dr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:dE(i.checkpoint.summary),nextAction:dE(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:Dr.maxArtifacts}}async function xL(e,t){let i=D(e,t.name),r=await Oe(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 ga(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 it(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function AL(e,t){let i=await xL(e,t);return{committed:i,latest:xk(i),history:Ck(i)}}async function hE(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await AL(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 IL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Wa=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Pm(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function TL(e){return(await Yu(e))?.change??null}function jL(e,t,i=!1,r){return Qu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function $L(e,t){let i=ne(e,t.name),r=[...(await up(i,t.brief)).findings,...(await Pb(e,t)).findings,...await sE(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await va(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 Jl(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 Ha({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 Bi(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 dp(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 Rm(e,t,i){let r=await TL(e)===t,n=await Fo(e,t),a=await sb(e,t),o;try{let w=await gi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected: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:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected: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:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){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:w.message}}if(n.status!=="available"){let w={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=Sm({paths:e,state:o,findings:[w]}),F=Qu({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:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:Em(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await fE({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await hE(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,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 w=await Ha({changeDir:ne(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 Be=await $a(e,o.name,o.verification_evidence);for(let ue of Be.acceptanceTrace.entries)P.set(ue.acceptanceId,ue.status==="failed"?"failed":ue.status==="missing"?"missing":"satisfied")}let F=Hy({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:Pm($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await gu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.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 w=await kt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await ba({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await as({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.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 w=await sS({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await Au({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await $L(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=Sm({paths:e,state:o,findings:b}),S=g.filter(w=>!ya(w.code)),N=o.phase==="archive"&&m?.ready===!0&&S.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),E=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",y=g.find(w=>w.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:E||R?null:jL(o,N,k,i?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:Em(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Qu({state:o,findings:g,archiveReady:N,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Zu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...y?{error:y.message}:{}}}async function OL(e){let t;try{t=await ei({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await _L.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Wa.maxChanges))throw new Error(`Native status exceeds ${Wa.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function ed(e,t){let i=t.toString(36),r=H("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function HL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=IL.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=H("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 DL(e,t){let i=await OL(e),r=H("comet.native.status-names.v1",i),n=HL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Wa.maxItems).map(u=>Rm(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?ed(r,f):null,nextPageCommand:f<i.length?Pm(["comet","native","status","--cursor",ed(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",ed(r,f)]:null,limits:{...Wa}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Wa.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?ed(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?Pm(l):null,nextPageArgs:l,limits:{...Wa}}}async function Cm(e,t){return(await DL(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as iM,randomUUID as rM}from"node:crypto";import{constants as Tm,promises as Q}from"node:fs";import le from"node:path";var rd=$n(nn(),1);import{randomUUID as LL}from"crypto";import{promises as wE}from"fs";import Am from"path";import{isDeepStrictEqual as _m}from"util";var Cn=/^[a-f0-9]{64}$/u,ML=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),FL=new Set(["sourceHash","targetHash","nextJournal"]),BL=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),pE=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),VL=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function td(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function mE(e){return JSON.stringify(e,null,2)+`
265
+ `}function Im(e){return e.schema===be?nu(e):gn(e)}function xm(e,t){return{...e,schema:be,minimum_runtime_version:2,revision:t}}function qL(e){return{...e,schema:ji,minimum_runtime_version:2,revision:1,previousState:xm(e.previousState,1),nextState:xm(e.nextState,2)}}function id(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ne,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 WL(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?L(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:wr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:id(e.previousState),nextState:{...id(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:bi.definition.metadata.version,skillHash:Es}:e.nextRun}}function vE(e,t){return JSON.stringify(e)===JSON.stringify(t)}function za(e,t){return JSON.stringify(nu(e))===JSON.stringify(nu(t))}function gE(e,t){return JSON.stringify(gn(e))===JSON.stringify(gn(t))}function Ji(e,t){return _m(e,t)}function zL(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(td(n,BL,"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=xr(n.previousRun),o=xr(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!==pE.size||u.some(f=>!pE.has(f))||l.fromSchema!==be||l.toSchema!==Ne||!["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=L(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 Bs(e,t){return Am.join(D(e,t),"schema-migration.json")}function JL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");td(e,ML,"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===et&&i.toSchema===be,n=i.fromSchema===be&&i.toSchema===Ne;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?fi(i.nextState):lt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(L((0,rd.stringify)(Im(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");td(i.transition,FL,"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?zp(l.nextJournal,t):Wp(l.nextJournal,t);if(L(JSON.stringify(l.nextJournal,null,2)+`
266
+ `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===be?za(a,u.previousState)||za(a,u.nextState):a.schema===Ne&&(gE(a,u.previousState)||gE(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!==Ne)throw new Error("Schema migration transition supersede target schema is invalid");s=zL(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");td(i.runRetreat,VL,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=xr(l.previousRun),d=xr(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!==Ne||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 Vs(e,t){let i=Bs(e,t),r=j(e,i);await I(r,i);try{let n=await Tl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return JL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function GL(e,t,i){let r=await va(e,t),n=r?await Jl(e,r):await Gl(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Kh(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 ka(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Qh(e,t,n)}async function yE(e){try{return await ti(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function UL(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 NE(e,t){let i=t.transitionSupersede,r=D(e,t.change),n=await it(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&&!_m(o.event,UL(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 KL(e,t,i){if(!t.transitionSupersede)return;let r=Ue(e,t.change),n=await yE(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=D(e,t.change),o=await Oe(a),s=await NE(e,t),c=await ga(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!==L(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function YL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=D(e,t.change),a=await Oe(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 vn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Ji(await Oe(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await NE(e,t);if(o.sequence===null){let l=await Or({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 kn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ue(e,t.change),c=await yE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await wE.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function XL(e,t,i){if(!t.runRetreat)return;let r=D(e,t.change),n=await Oe(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 vn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await it(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Or({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 kn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function QL(e,t,i){let r=await Vs(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=Am.join(ne(e,t),Te),a=await ti(n);if(await KL(e,r,a===r.targetHash),await GL(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 he(n,(0,rd.stringify)(Im(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ue(e,t),s=await ti(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 ee(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await YL(e,r,i),await XL(e,r,i),await wE.rm(Bs(e,t),{force:!0}),r.nextState}async function ZL(e){let t=D(e.paths,e.state.name),i=await Oe(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=L(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:be,toSchema:Ne,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function eM(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=za(i,t.previousState),a=za(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=D(e.paths,i.name),s=await Oe(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 it(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).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(!_m(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...id(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,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=L(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 ti(Ue(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:be,toSchema:Ne,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function tM(e){let t,i,r,n;if(e.state.schema===et){if(t=xm(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==dn)throw new Error("Native v1 change has a transition from another schema generation");let s=qL(e.pendingTransition.journal);if(vE(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(vE(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=Ue(e.paths,e.name);i={sourceHash:await ti(c),targetHash:L(mE(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==ji)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 eM({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=WL(s);if(za(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(za(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=Ue(e.paths,e.name);i={sourceHash:await ti(u),targetHash:L(mE(l)),nextJournal:l}}}else t=id(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await ZL({paths:e.paths,state:e.state,migrationId:e.id}));let a=Am.join(ne(e.paths,e.name),Te),o=(0,rd.stringify)(Im(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===et?be:Ne,sourceHash:await ti(a),targetHash:L(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function bE(e){return se(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 QL(e.paths,e.name,e.hooks);if(i?.schema===Ne)return i;let r=await gi(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!==et&&n.schema!==be)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Jp(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 tM({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??LL()}),s=Bs(e.paths,e.name),c=j(e.paths,s);await I(c,s),await ee(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Gi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),nM=512*1024,xn=/^([a-f0-9]{64})\.json$/u,aM=/^\.([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,oM=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,nd=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function $m(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ri(e,t){return $m(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function RE(e,t){return $m(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ja(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return e<t?-1:e>t?1:0}function sM(e,t){let i=le.relative(e.projectRoot,t);if(i.length===0||le.isAbsolute(i)||i===".."||i.startsWith(`..${le.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(le.sep).join("/")}function CE(e,t){return le.join(D(e,t),"evidence")}function ad(e,t){return sM(e,CE(e,t))}async function od(e,t){let i=le.resolve(e),r=le.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=le.relative(i,r).split(le.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=le.join(o,s));let c=await Q.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Q.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ja(c)})}return a}async function Bt(e){for(let t of e){let i=await Q.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!$m(t,i)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function xE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:ja(e,t)}function kE(e){return e!==null&&oM.test(e)?[e]:[]}function cM(e,t,i,r){if(e==="snapshots")return{canonical:Ca(i,t),dependencies:[]};if(e==="scopes"){let a=xa(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=fu(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[ja("scopes",a.scopeHash)]}}if(e==="verifications"){let a=ys(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(kE));return{canonical:a,dependencies:[a.implementationScopeRef,gk(a.reportHash),...kE(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"||iM("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=pu(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=hu(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 Ur(e){let t=await Q.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"?nM:$r;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await Q.realpath(e.file);if(!O(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 Q.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(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Bt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Ri(Ja(t),o)||!Ri(Ja(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,S=await a.read(u,0,Math.min(u.length,g),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,S.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Bt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Ri(Ja(o),f)||!Ri(Ja(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=cM(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
267
+ `)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:Ja(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(nt)}}finally{await a.close()}}async function SE(e){try{return await Q.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function lM(e){let t=D(e.paths,e.name),i=t,r=CE(e.paths,e.name);await I(j(e.paths,r),r);let n;try{let s=await od(t,r);n=await Q.readdir(r,{withFileTypes:!0}),await Bt(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of nd){if(!n.some(f=>f.name===s))continue;let c=le.join(r,s),l=await od(t,c),u=(await Q.readdir(c,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name)),d=new Map;for(let f of u){let h=aM.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],[m])=>nt(v,m))){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 m=le.join(c,f),p=xn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=xE(s,p),g=le.join(c,v.name),S=await Ur({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),N=await SE(m),k=N?null:await Ur({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:S,action:N?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ga(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${sd(o)}`),path:ad(e.paths,e.name)}]};for(let s of a.sort((c,l)=>nt(c.ref,l.ref))){if(await Bt(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Ur({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Ur({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Ri(s.originalDocument.identity,d.identity)||!Ri(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Q.rm(s.quarantine),await Bt(s.document.directoryChain);continue}if(!await SE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Q.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Ri(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Q.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Ur({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Ur({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:xn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!RE(s.document.identity,l.identity)||!Ri(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Q.rm(s.quarantine),await Bt(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ga(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${sd(o)}`),path:ad(e.paths,e.name)}]}}async function uM(e,t){let i=D(e,t),r=i,n=le.join(i,"evidence");await I(j(e,n),n);let a;try{let l=await od(i,n);a=await Q.readdir(n,{withFileTypes:!0}),await Bt(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!nd.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(nt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${sd(o)}`);let s=[],c=0;for(let l of nd){if(!a.some(h=>h.name===l))continue;let u=le.join(n,l),d=await od(r,u),f=(await Q.readdir(u,{withFileTypes:!0})).sort((h,v)=>nt(h.name,v.name));await Bt(d);for(let h of f){if(s.length>=Gi.maxDocuments)throw new Error(`Native evidence store exceeds ${Gi.maxDocuments} documents`);let v=xn.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 m=xE(l,v[1]),p=le.join(u,h.name);await I(j(e,p),p);let b=await Ur({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>Gi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Gi.maxScannedBytes} scanned bytes`);s.push(b)}await Bt(d)}return s}function EE(e,t){let i=new Set,r=[...e].sort(nt).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(nt).reverse())i.has(o)||r.push(o)}return i}function dM(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(nt),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(nt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function fM(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=EE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Gi.minimumAgeMs&&a.add(c.ref);for(let c of nd){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,Gi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=EE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Gi.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:dM(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function sd(e){let t=e.slice(0,Gi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Ga(e){let t=Gi.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 jm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ga(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${sd(n)}`),path:r}}async function PE(e,t){try{await Q.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await Q.rename(e,t)}catch{}}async function hM(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Bt(e.directoryChain);let i=await Ur({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:xn.exec(le.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await Q.lstat(e.file),n=await Q.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Ri(e.identity,r)||!Ri(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=le.join(le.dirname(e.file),`.${le.basename(e.file)}.${rM()}.gc`);await Q.rename(e.file,a);try{let[o,s]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await Bt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!RE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await PE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Q.rm(a),await Bt(e.directoryChain)}catch(o){throw await PE(a,e.file),o}}async function pM(e){if((await ye(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await Q.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 yt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function mM(e,t){if(t)return[t];let i;try{i=await Q.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(nt)}async function vM(e,t){let i=await gi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Bi(e,t),Vs(e,t),Mr(e,t)]);return r!==null||n!==null||a!==null}async function gM(e){if(await vM(e.paths,e.name))return[];let t=await gi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await lM({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 uM(e.paths,e.name),a=fM(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=ad(e.paths,e.name);if(!e.repair)return[...i.findings,jm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await hM(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[jm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ga(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,jm(e.name,a,!0,o)]}async function AE(e){if(e.deferAll||await pM(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 mM(e.paths,e.name))try{a.push(...await gM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ga(`Native evidence retention refused to clean ${o}: ${s.message}`),path:ad(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 se(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ga(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as wM,randomUUID as g9}from"crypto";import{promises as zs}from"fs";import ae from"path";var Hm=64*1024*1024,yM=256*1024,jE=16*1024*1024;async function at(e){try{return await zs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function NM(e){let t;try{t=await zs.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 kt(e,i.name);if(r){await tu({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 Ws(e,t){let i=[];async function r(n){let a=await wt({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=ae.join(n,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await zs.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:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await re({root:e,file:c,maxBytes:Hm,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.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 bM(e,t,i,r){await hi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await wt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await zs.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await hi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await kr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Hm,label:`Native root move file ${ae.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 Ua(e,t,i,r){let n=await Ws(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await Ws(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ae.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 kM(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function SM(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function EM(e){return`${e}.removing`}function _E(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function $E(e,t,i){return ae.join(Ll(e,t).directory,`root-move-cleanup-${i}.json`)}function PM(e){return JSON.stringify(e,null,2)+`
268
+ `}function RM(e){return wM("sha256").update(e).digest("hex")}function CM(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("\\")||ae.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 xM(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(CM);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=ae.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 AM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=PM(t);if(Buffer.byteLength(i,"utf8")>jE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await he($E(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),RM(i)}async function _M(e){let t=await re({root:e.paths.runtimeDir,file:$E(e.paths,e.id,e.cleanup.kind),maxBytes:jE,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 xM(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Om(e){let t=await Ws(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 IE(e){return e.ref.split("/").length}async function IM(e){let i=[...await Om({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>IE(a)-IE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ae.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await jl({root:e.projectRoot,file:a,maxBytes:Hm,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await jh({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 Om({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await jh({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function OE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function TM(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 jM(e,t,i,r){for(let a of[e,t])try{let o=await yt(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=ae.join(i,"runtime","transactions",r,"transaction.json");try{let a=await re({root:i,file:n,maxBytes:yM,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 TE(e){let t=OE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await mr(e.projectRoot,t),t}async function qs(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=OE(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 mr(e.projectRoot,i),i}async function cd(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 at(e.target),a=await at(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 AM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ws(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await qs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await _M({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await at(e.target),a=await at(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 rN({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 qs({projectRoot:e.projectRoot,config:t,id:e.id})}return await Om({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await qs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await qs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await IM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),qs({projectRoot:e.projectRoot,config:t,id:e.id})}async function $M(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await at(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=EM(e.staging);t=await cd({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 Ws(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await bM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ua(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await TE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await at(e.destinationPaths.nativeRoot)){if(await at(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ua(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await at(e.staging))throw new Error("Native move staging tree is missing");await Ua(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await zs.rename(e.staging,e.destinationPaths.nativeRoot)}t=await TE({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 at(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=SM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await at(e.sourcePaths.nativeRoot)&&await Ua(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await cd({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 NM(e.destinationPaths);let n=await yt(e.destinationPaths,e.pending.id);await ua(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 mr(e.projectRoot,o),o}async function HE(e){let t=await ye(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await qe(e.projectRoot,i.fromArtifactRoot),n=await qe(e.projectRoot,i.toArtifactRoot),a=kM(n,i.id),o=await at(r.nativeRoot)?r:n,s=await vr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await jM(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await at(r.nativeRoot))throw v;let m=TM({id:i.id,paths:r,now:new Date});await hN(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await $M({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 at(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=_E(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await at(n.nativeRoot)&&await Ua(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await cd({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=_E(a,i.id);!t.native.pending_root_move?.cleanup&&await at(a)&&await Ua(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await cd({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 yt(r,i.id);await Ml(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 mr(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await gr(s)}}var Ka=4096,OM=4096,HM=1024;async function Kr(e,t,i){try{let r=await wt({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 ud(e,t){let i=new Map(e.map(r=>[je.resolve(r.file),{...r,file:je.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await Bo(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await bh(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 DM(e,t){let i=iE(e),r;try{await I(e.projectRoot,i);let n=await Yu(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 Gr(e,r.change)?[]:(await De(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 ld.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 LM(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await I(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 MM(e,t){let i=[],r=[];for(let n of await Kr(e,e.transactionsDir,OM)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await yt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:je.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 ea([e],`doctor archive recovery ${a.id}`,async()=>await ud([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,"archive.lock")}],i)?(await oE({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 FM(e,t,i){let r=[];for(let n of await Kr(e,e.locksDir,HM)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=je.join(e.locksDir,n.name);try{let o=await Bo(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await bh(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 BM(e,t,i=5){let r=[],n=t?await Cm(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await Cm(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:je.join(e.changesDir,a.name,Te)});continue}let o=await Rm(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:je.join(e.projectRoot,s.path)}:{}})}return r}async function VM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await wa(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 QN(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:je.join(D(e,n),"trajectory.jsonl")})}return i}async function qM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await Fo(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=sn(e,n),s=We(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 ea([e],`migrate Runtime layout for ${n}`,async()=>{let c=await ei({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await I(e.runtimeDir,s),await ld.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await ei({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await ld.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 ld.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 WM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await np(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:Na(e,n),repair:"migrate"});continue}let a=await De(e,n);await lb({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:Na(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Na(e,n)})}return i}async function zM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Bs(e,n);try{let o=await Vs(e,n),s=await gi(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:je.join(e.changesDir,n,Te)});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:je.join(e.changesDir,n,Te),repair:"migrate"});continue}await bE({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:je.join(e.changesDir,n,Te)})}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 JM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Bi(e,n)}catch(o){if(o instanceof Ps)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ue(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await ea([e],`doctor transition recovery ${n}`,async()=>await ud([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Vk(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ue(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ue(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:Ue(e,n),repair:"continue"})}}return i}async function GM(e,t){let i=[],r=t.name?[t.name]:(await Kr(e,e.changesDir,Ka)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Lr(e,n),o;try{o=await Mr(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 ea([e],`doctor checkpoint recovery ${n}`,async()=>await ud([{paths:e,file:je.join(e.locksDir,"root-move.lock")},{paths:e,file:je.join(e.locksDir,`transition-${n}.lock`)}],i)?(await eS(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 Js(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await ye(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([qe(r.projectRoot,c.fromArtifactRoot),qe(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await ud([{paths:l,file:je.join(l.locksDir,"root-move.lock")},{paths:u,file:je.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await HE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await qe(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 LM(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await MM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await qM(r,{name:e.name,repair:t})),i.push(...await zM(r,{name:e.name,repair:t})),i.push(...await WM(r,{name:e.name,repair:t})),i.push(...await VM(r,{name:e.name,repair:t})),i.push(...await JM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await GM(r,{name:e.name,repair:t})),i.push(...await AE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await FM(r,t,s.unfinished)),i.push(...await DM(r,t)),e.projectOnly||i.push(...await BM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as UM}from"node:crypto";import{promises as Fe}from"node:fs";import ht from"node:path";var Dm=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 DE(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function LE(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=ht.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function dd(e){try{return await Fe.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ME(e,t){let i=ht.normalize(ht.resolve(e)),r=ht.normalize(ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function KM(e,t){let i;try{i=await Fe.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=ht.join(e.archiveDir,n.name);try{let o=await Ze(ht.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 YM(e,t){let i=await aa(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function An(e,t){await Fe.mkdir(e.transactionsDir,{recursive:!0}),await ee(yr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function XM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Gt(e.paths.projectRoot);i.some(a=>ME(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await ye(a);if(!o)continue;let s=await qe(a,o.native.artifact_root);r.some(c=>ME(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 Fe.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 Ze(ht.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 ou(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 QM(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 ZM(e){let t=ht.join(e.paths.specsDir,e.change.capability),i=ht.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Fe.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 Fe.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([Fe.realpath(e.paths.specsDir),Fe.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Fe.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Fe.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Fe.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=ht.join(Mt(e.paths,e.state.name),e.change.source);await he(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Fe.mkdir(t,{recursive:!0}),await he(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function FE(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 eF(e,t){let i=Mt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Z({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function tF(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(FE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Lm(e){return se(e.paths,`archive portable change ${e.name}`,async()=>{let t=QM(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await YM(e.paths,e.name),r=Mt(e.paths,e.name),n=await dd(r),a=n?null:await KM(e.paths,e.name),o;if(n)o=await zi(e.paths,e.name);else if(i)o=await Ze(ht.join(LE(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}`);let s=await Dt(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await QS({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await eE({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let d=await ZS({paths:e.paths,name:e.name});if(o=d.state,d.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");d.action==="recorded-final-verification"&&(s=await Dt(e.paths,e.name))}let c=LE(e.paths,i?.archive_ref??DE(o)),l=await dd(c);if(i&&tF(i,o),n&&l)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 Ls(e.paths,o.name),await Fe.rm(We(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)FE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await XM({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Dm(d);i={schema:_l,id:UM(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:DE(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await eF(e.paths,o),created_at:new Date().toISOString()},await An(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await An(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await Ts({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await ZM({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await An(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await An(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await Ts({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await un({file:Pt(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await An(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await dd(r)?r:c;if(await Uu({file:ht.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Gu({file:ht.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await An(e.paths,i),s&&!u&&(await Ts({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await Ts({paths:e.paths,state:s}),await Fe.mkdir(e.paths.archiveDir,{recursive:!0}),await dd(c))throw new Error(`Native Archive target already exists: ${c}`);await Fe.rename(r,c),i={...i,status:"moved"},await An(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await Ls(e.paths,o.name),await Fe.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Fe.rm(yr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function Ui(e,t,i){return e.language==="zh-CN"?i:t}function iF(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Ui(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Ui(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ui(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(Ui(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(Ui(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(Ui(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function rF(e){let t=e.workspace.change_branch??"<change-branch>",i=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${i}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${i}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function nF(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:r,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",r],requiredInputs:[],inputOptions:[],description:Ui(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Ui(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function VE(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ya(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function aF(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function BE(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function oF(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function sF(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Yr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:VE({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ya("summary","--summary"),aF(e.name,e.flag)]}}function Mm(e){return[Yr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Yr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function fd(e,t,i={}){let r=oF(t)&&e.coordination_mode===void 0,n=iF(e,r),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Ya("summary","--summary")],commandAlternatives:[Yr({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ya("summary","--summary")],commandAlternatives:[Yr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Mm({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ya("summary","--summary")],commandAlternatives:[Yr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Yr({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ya("summary","--summary")],commandAlternatives:[Yr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Mm({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ya("summary","--summary")],commandAlternatives:Mm({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?VE({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:r?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:sF({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[BE("coordination-mode","--coordination-mode",Wy)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,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:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"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:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.some(({status:l})=>l==="blocked"||l==="needs-reverify"),c=t.children.some(({status:l})=>l==="ready"||l==="active");return{...a,disposition:s&&!c?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:s&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:o("none")}}return{...a,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:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Ui(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{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:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=i.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?i.archiveBlockers&&i.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[BE("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...nF(e)],userCommunication:rF(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Yr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{randomUUID as cF}from"node:crypto";import{promises as Xa}from"node:fs";import KE from"node:path";var Fm=["evidence.md","repair.md","archive.md","checkpoint.md"],lF="verification.md";async function uF(e){try{return await Xa.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Bm(e,t){let i=ne(e,t),r=[yr(e,{kind:"migration",change:t}),sn(e,t),...Fm.map(n=>KE.join(i,n))];return(await Promise.all(r.map(uF))).some(Boolean)}async function dF(e,t){let i=await aa(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function qE(e,t){await Xa.mkdir(e.transactionsDir,{recursive:!0}),await ee(yr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function WE(e,t,i={}){let r=i.removeVerificationReport===!1?Fm:[...Fm,lF];await Promise.all([Xa.rm(We(e,t),{recursive:!0,force:!0}),Xa.rm(sn(e,t),{recursive:!0,force:!0}),...r.map(n=>Xa.rm(KE.join(ne(e,t),n),{force:!0}))])}async function zE(e,t){await qi(Jr(e,t.name),qr({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function JE(e,t){try{let i=await kt(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 GE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=fe(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 fF(e){let t=ne(e.paths,e.state.name),i=await Z({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 Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Sl({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function UE(e,t){let i=await ou(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Gs(e){return se(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await dF(e.paths,e.name),i=await Gr(e.paths,e.name)?await Ze(Pt(e.paths,e.name)):null;if(!t&&i)return await WE(e.paths,e.name,{removeVerificationReport:!1}),await zE(e.paths,i),i;let r=null,n=null;for(t||(r=await UE(e.paths,e.name),n=await JE(e.paths,e.name),GE(e.paths,n),t={schema:Al,id:cF(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await qE(e.paths,t));;){let a=Uy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await UE(e.paths,e.name),n??=await JE(e.paths,e.name),GE(e.paths,n),i=Gy({state:r,acceptance:await fF({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await xl(Pt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await WE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ze(Pt(e.paths,e.name)),await zE(e.paths,i)),t={...t,status:a.nextStatus},await qE(e.paths,t)}return await Xa.rm(yr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ze(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as XE}from"node:fs";import QE from"node:path";import{promises as Vm}from"node:fs";import hF from"node:path";var pF=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),mF=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),vF=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),gF=new Set(["status","summary"]);function hd(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function pd(e,t,i){let r=new Set(Object.keys(e)),n=[...t].filter(o=>!r.has(o)),a=[...r].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${i} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function wF(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((i,r)=>i===t[r])}function _n(e,t,i){return{status:"incompatible",file:e,snapshot:t,message:i}}function yF(e,t,i,r){let n=hd(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=pd(n,pF,"Native Supervisor overlay");if(a)return a;if(r.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(r.parent!==t.name)return`Native Supervisor overlay parent ${r.parent} does not match ${t.name}`;let o=hd(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=pd(o,mF,"Native Supervisor integration");if(s)return s;if(r.integration.headCommit!==r.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=hd(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=pd(c,gF,"Native Supervisor finalVerification");if(l)return l;if(r.finalVerification.status!=="pending"||r.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==i.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=hd(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let h=pd(f,vF,`Native Supervisor child ${u}`);if(h)return h;let v=i.children[u];if(f.name!==v.name||f.summary!==v.summary||!wF(f.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let m=v.depends_on.length===0?"ready":"pending";if(f.status!==m)return`Native Supervisor child ${v.name} has progressed beyond its initial ${m} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function In(e){let t=Lu(e.paths,e.state.name),i;try{let c=await Vm.lstat(t);if(!c.isFile()||c.isSymbolicLink())return _n(t,"","Native Supervisor overlay is not a regular file");i=await Vm.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:_n(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let r;try{r=JSON.parse(i)}catch(c){return _n(t,i,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=hF.join(e.paths.changesDir,e.state.name),a;try{a=await $s({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return _n(t,i,`Native children contract cannot be validated: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:i};let o;try{o=await Dt(e.paths,e.state.name)}catch(c){return _n(t,i,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return _n(t,i,"Native Supervisor overlay disappeared during inspection");let s=yF(r,e.state,a.contract,o);return s?_n(t,i,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:i}}async function YE(e){let t=await In({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Vm.rm(t.file,{force:!1})}function NF(e,t){let i=fe(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 bF(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function kF(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:ln(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Ti(t),completed_at:r});return ct({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?bF(e):e.acceptance,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 SF(e){try{let t=await Ju(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 ZE(e){return se(e.paths,`recover portable change ${e.name}`,async()=>{let t=await zi(e.paths,e.name);if(t.status==="done")return await Ku({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=NF(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=await In({paths:e.paths,state:t});if(r.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:r.message};let n=!1;r.status==="repairable-legacy-overlay"&&(await YE({paths:e.paths,state:t,expected:r}),n=!0);let a=Jr(e.paths,e.name),o=await SF(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await qi(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Ku({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=wm({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await un({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await XE.rm(QE.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let m=qr({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await qi(a,m,{containedRoot:e.paths.runtimeDir}),{state:t,local:m,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=u||d;if(f){let v=kF(t,d?"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.",d);t=await un({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let h=qr({portableState:t,projectRoot:e.paths.projectRoot,branch:fe(e.paths.projectRoot).currentBranch});return await XE.mkdir(QE.dirname(Jr(e.paths,t.name)),{recursive:!0}),await qi(a,h,{containedRoot:e.paths.runtimeDir}),await Ku({paths:e.paths,state:t}),{state:t,local:h,action:f?"reverify":"resume-stable-boundary",reason:s,message:f?"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 tP}from"node:fs";import PF from"node:path";function EF(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function eP(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:EF(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function RF(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function CF(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function xF(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:IF(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:TF(r,i)}))]:[]]}function AF(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 iP(e,t){let i=fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:PF.resolve(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}}function _F(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function md(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function IF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:md(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function TF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:md(e.summary,t)??""}}async function Tn(e){let t=await tE(e),i=eP(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Os({paths:e.paths,state:t.state}),a=await In({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Dt(e.paths,e.name),s=o?{...iP(e.paths,t.state),projectRoot:"."}:iP(e.paths,t.state),c=fd(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?_F(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:N})=>N==="pending"||N==="ready").length,m=o.children.filter(({status:N})=>N==="active"||N==="verified").length,p=o.children.filter(({status:N})=>N==="integrated"||N==="archived").length,b=o.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,g=o.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:md(N.blocker,u)})),S=o.children.flatMap(({blocker:N})=>{let k=md(N,u);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:m,integrated:p,blocked:b,active:g,agents:{working:o.children.filter(({task:N})=>N!==null).length,completed:p},risks:S,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&p===o.children.length?"parent-verification":v>0?"dispatch-ready-child":b>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,m=xF(t.state,o,u),p=CF(e.cursor,t.state.state_version,v),b=m.slice(p,p+32),g=p+b.length<m.length?RF(t.state.state_version,v,p+b.length):null;return{items:b,nextCursor:g,supervisorStateVersion:v}})():null,h=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:AF(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:i.blockers,workspace:s,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,m)=>({...v,[m.status]:(v[m.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...h?{supervisor:h}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function rP(e){let t;try{t=await tP.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 tP.readFile(`${Mt(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 Us from"path";import{realpathSync as GF}from"fs";var Ki={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function nP(e){return e?e.command?`${Ki.next} ${e.command}`:e.ask_user?`${Ki.next} ${e.ask_user}`:null:null}function aP(e,t){let i=[e.summary],r=nP(e.next);return r&&i.push(r),e.user_message&&i.push("",Ki.relay,e.user_message),t!==void 0&&i.push("",Ki.details,JSON.stringify(t,null,2)),`${i.join(`
269
269
  `)}
270
- `}function GE(e,t,i){let r=[e.summary],n=zE(e.next);return n&&r.push(n),e.user_message&&r.push("",Wi.relay,e.user_message),r.push("",`${Wi.detail} ${t}`),i!==void 0&&r.push("",Wi.details,JSON.stringify(i,null,2)),r.join(`
271
- `)}function J(e,t,i){return e==="zh-CN"?i:t}var Om={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function UE(e,t){return typeof e=="string"&&Om[e]?J(t,Om[e].en,Om[e].zh):typeof e=="string"?e:""}function Hm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function uF(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function KE(e,t){let i=[];e.failed>0&&i.push(J(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(J(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(J(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=J(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function YE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function Dm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function dF(e,t,i){return e==="done"?J(i,"complete","已完成"):e==="await-user"?J(i,"waiting for a user decision","等待用户决定"):e==="blocked"?J(i,"paused: needs attention","已暂停,需要处理"):t?J(i,"waiting for a user decision","等待用户决定"):J(i,"ready to continue","可继续推进")}function fF(e,t,i){let r=Dm(e),n=[];i&&n.push(i);let a=J(r,`Change ${e.change}`,`需求 ${e.change}`),o=UE(e.phase,r),s=dF(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(KE(t,r));let c=e.userCommunication,l=XE(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function XE(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:J(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:J(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:J(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function hF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function pF(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=UE(e.phase,t),n=e.status==="await-user"?J(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?J(t,"paused","已暂停"):e.status==="done"?J(t,"complete","已完成"):J(t,"in progress","进行中"),a=Hm(e.acceptance)?`${J(t,", ",",")}${KE(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function mF(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function vF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function gF(e){if(e.healthy){let r=e.repaired?J("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):J("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=wF(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:J("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:J("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function wF(e){return YE(e)?XE(e,Dm(e)):void 0}function QE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(vF(t))return gF(t);if(hF(t)){let r=mF(t.items);return{summary:[t.total===t.items.length?J(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):J(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>pF(a,r))].join(`
272
- `)}}let i=t.continuation;if(YE(i))return fF(i,yF(t),NF(t,Dm(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:J(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function yF(e){if(Hm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Hm(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return uF(i.acceptance)}return null}function NF(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return J(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?J(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function ZE(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:J("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:J("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:J("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:J("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:J("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:J("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:J("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:J("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:J("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var eP=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Mm=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.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:eP,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",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, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary 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] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
273
- comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, 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.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--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 or Archive 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.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--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, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," 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."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". 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]
274
- 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 Lm(e,t){return`${e}:
270
+ `}function oP(e,t,i){let r=[e.summary],n=nP(e.next);return n&&r.push(n),e.user_message&&r.push("",Ki.relay,e.user_message),r.push("",`${Ki.detail} ${t}`),i!==void 0&&r.push("",Ki.details,JSON.stringify(i,null,2)),r.join(`
271
+ `)}function J(e,t,i){return e==="zh-CN"?i:t}var qm={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function sP(e,t){return typeof e=="string"&&qm[e]?J(t,qm[e].en,qm[e].zh):typeof e=="string"?e:""}function Wm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function jF(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function cP(e,t){let i=[];e.failed>0&&i.push(J(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(J(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(J(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=J(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function lP(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function zm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function $F(e,t,i){return e==="done"?J(i,"complete","已完成"):e==="await-user"?J(i,"waiting for a user decision","等待用户决定"):e==="blocked"?J(i,"paused: needs attention","已暂停,需要处理"):t?J(i,"waiting for a user decision","等待用户决定"):J(i,"ready to continue","可继续推进")}function OF(e,t,i){let r=zm(e),n=[];i&&n.push(i);let a=J(r,`Change ${e.change}`,`需求 ${e.change}`),o=sP(e.phase,r),s=$F(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(cP(t,r));let c=e.userCommunication,l=uP(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function uP(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:J(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:J(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:J(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function HF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function DF(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=sP(e.phase,t),n=e.status==="await-user"?J(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?J(t,"paused","已暂停"):e.status==="done"?J(t,"complete","已完成"):J(t,"in progress","进行中"),a=Wm(e.acceptance)?`${J(t,", ",",")}${cP(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function LF(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function MF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function FF(e){if(e.healthy){let r=e.repaired?J("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):J("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=BF(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:J("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:J("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function BF(e){return lP(e)?uP(e,zm(e)):void 0}function dP(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(MF(t))return FF(t);if(HF(t)){let r=LF(t.items);return{summary:[t.total===t.items.length?J(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):J(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>DF(a,r))].join(`
272
+ `)}}let i=t.continuation;if(lP(i))return OF(i,VF(t),qF(t,zm(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:J(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function VF(e){if(Wm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Wm(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return jF(i.acceptance)}return null}function qF(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return J(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?J(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function fP(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:J("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:J("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:J("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:J("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:J("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:J("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:J("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:J("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:J("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var hP=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Gm=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.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:hP,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",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, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary 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> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
273
+ comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
274
+ comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, 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 the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--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 or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--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, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," 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."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". 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 --expected-state-version <n> --expected-action confirm-shape','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]
275
+ 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 Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--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, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; 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 Jm(e,t){return`${e}:
275
276
  ${t.map(i=>` ${i}`).join(`
276
- `)}`}function bF(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Mm[i]||t.length>1&&Mm[t[0]]?.subcommands?i:t[0]}function kF(e=[]){let t=bF(e),i=Mm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Lm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...eP];return n&&n.length>0&&r.push("",Lm("Options",n)),r.push("",`Output:
277
- ${i.output}`),i.examples&&r.push("",Lm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
277
+ `)}`}function WF(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Gm[i]||t.length>1&&Gm[t[0]]?.subcommands?i:t[0]}function zF(e=[]){let t=WF(e),i=Gm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Jm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...hP];return n&&n.length>0&&r.push("",Jm("Options",n)),r.push("",`Output:
278
+ ${i.output}`),i.examples&&r.push("",Jm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
278
279
  `)}
279
- `}}var SF=kF().usage;var F8=10*1024*1024,Bt=class extends Error{};function qs(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Bt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function nd(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Bt(`${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 Bt(`${t} requires a value`);return e.splice(r,2),n}function iP(e){if(e.length>0)throw new Bt(`Unexpected argument: ${e[0]}`)}function Fm(e,t){let i=Vs.normalize(tP(e)),r=Vs.normalize(tP(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function tP(e){let t=Vs.resolve(e);try{return EF.native(t)}catch{return t}}function PF(e){let t=Vs.resolve(e),i=fe(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=fe(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Fm(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Fm(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Fm(process.cwd(),i.currentWorktreeRoot)?Vs.resolve(process.cwd()):i.currentWorktreeRoot}async function rP(e){return e?PF(e):ch(process.cwd())}async function nP(e){let t=await ye(e);return qe(e,t?.native.artifact_root??"docs")}function aP(e){return JSON.stringify(e,null,2)+`
280
- `}function zi(e,t,i){return{command:e,exitCode:0,data:t,text:i??aP(t)}}function RF(e,t){if(t instanceof Bt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Fu)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 Is)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof es)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 ts)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 Cu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ha)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 Hr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof bs)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 oP(e,t){let i=RF(e,t),r=i.error;if(!r)return i;let n=ZE({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function sP(e,t,i=!1){let r=e.envelope??QE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
281
- `}:e.error?{exitCode:e.exitCode,stderr:r?GE(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:JE(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==aP(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
282
- ${Wi.details}
280
+ `}}var JF=zF().usage;var E5=10*1024*1024,Vt=class extends Error{};function Ks(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Vt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function vd(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Vt(`${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 Vt(`${t} requires a value`);return e.splice(r,2),n}function mP(e){if(e.length>0)throw new Vt(`Unexpected argument: ${e[0]}`)}function Um(e,t){let i=Us.normalize(pP(e)),r=Us.normalize(pP(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function pP(e){let t=Us.resolve(e);try{return GF.native(t)}catch{return t}}function UF(e){let t=Us.resolve(e),i=fe(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=fe(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Um(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Um(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Um(process.cwd(),i.currentWorktreeRoot)?Us.resolve(process.cwd()):i.currentWorktreeRoot}async function vP(e){return e?UF(e):gh(process.cwd())}async function gP(e){let t=await ye(e);return qe(e,t?.native.artifact_root??"docs")}function wP(e){return JSON.stringify(e,null,2)+`
281
+ `}function Yi(e,t,i){return{command:e,exitCode:0,data:t,text:i??wP(t)}}function KF(e,t){if(t instanceof Vt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Xu)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 Ms)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof ss)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 cs)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 Hu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ka)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 Fr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof xs)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 yP(e,t){let i=KF(e,t),r=i.error;if(!r)return i;let n=fP({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function NP(e,t,i=!1){let r=e.envelope??dP(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
282
+ `}:e.error?{exitCode:e.exitCode,stderr:r?oP(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:aP(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==wP(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
283
+ ${Ki.details}
283
284
  ${JSON.stringify(e.data,null,2)}
284
- `}:{exitCode:e.exitCode,stdout:e.text}}async function Ws(e,t){let i=await Cs({paths:e,state:t});return id(t,i)}async function CF(e){let t;try{t=await uP.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 xF(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function cP(e,t){let i;try{i=await uP.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}-${xF(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:od.join(e.archiveDir,n.name)}:null}function AF(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 ad(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function lP(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:od.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function _F(e,t){let i=[],r=[];for(let n of await Wy(e)){let a=sn(n);if(t&&a.change!==t)continue;let o=od.join(e.transactionsDir,n);try{let s=await Mo(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 Bm(e,t){let i=qs(e,"--repair"),r=nd(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Bt("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();iP(e);let a=await nP(t),o=await _F(a,n);if(n&&o.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let d=await qr(a,n)?await qa({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 _m({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ws(a,v.state)})}let h=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Ws(a,h)})}return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await qr(a,n)){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([cP(a,n),$m(a,n)]);if(u){let h=await qa({paths:a,name:n,details:!0});return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await qa({paths:a,name:n,details:!0});return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[lP(a,n)],continuation:h.continuation})}if(i){if(d){let v=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Ws(a,v)})}let h=await FE({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:await Ws(a,h.state)})}let f=await qa({paths:a,name:n,details:!0});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ws(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 WE(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");if(i){let k=await Ms({paths:a,repair:!0,projectOnly:!0}),S=[];for(let w of c.transactions)w.kind==="archive"?await _m({paths:a,name:w.change}):await Bs({paths:a,name:w.change}),S.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await Bm([],t),N=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...N,repaired:!0,repairedPortableTransactions:S,repairFindings:k.findings}}}let u=await CF(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,m,p,b,g]=await Promise.all([Promise.all(s.map(k=>qa({paths:a,name:k}))),Promise.all(s.map(k=>cP(a,k))),Promise.all(s.map(k=>$m(a,k))),Promise.all(h.map(k=>Ms({paths:a,name:k}))),Ms({paths:a,projectOnly:!0})]),y=AF([...m.filter(k=>k!==null),...s.flatMap((k,S)=>p[S]&&!f.has(k)?[lP(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:od.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...b.flatMap(({findings:k})=>k),...g.findings]),E={healthy:y.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:h,findings:y};return E.healthy?zi("doctor",E):ad(E)}let l=await Ms({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?zi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}async function dP(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=n.includes("--verbose"),c,l;try{qs(n,"--json"),qs(n,"--verbose"),c=nd(n,"--project-root");let d=[...n,...a],f=await rP(c);l=await t(d,f)}catch(d){l=oP(e,d)}let u=sP(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
285
+ `}:{exitCode:e.exitCode,stdout:e.text}}async function Ys(e,t){let i=await Os({paths:e,state:t});return fd(t,i)}async function YF(e){let t;try{t=await SP.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 XF(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function bP(e,t){let i;try{i=await SP.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}-${XF(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:gd.join(e.archiveDir,n.name)}:null}function QF(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 Xs(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function kP(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:gd.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function ZF(e,t){return t.status==="repairable-legacy-overlay"?{severity:"error",code:"portable-supervisor-overlay-stale",message:t.message,path:t.file,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}:t.status==="incompatible"?{severity:"error",code:"portable-supervisor-overlay-incompatible",message:t.message,path:t.file}:null}async function eB(e,t){let i=[],r=[];for(let n of await Zy(e)){let a=hn(n);if(t&&a.change!==t)continue;let o=gd.join(e.transactionsDir,n);try{let s=await Jo(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 Km(e,t){let i=Ks(e,"--repair"),r=vd(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Vt("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();mP(e);let a=await gP(t),o=await eB(a,n);if(n&&o.findings.length>0){if(r)throw new Vt("--strategy is only available to the legacy transaction doctor");let d=await Gr(a,n)?await Tn({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 Lm({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ys(a,v.state)})}let h=await Gs({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Ys(a,h)})}return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await Gr(a,n)){if(r)throw new Vt("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([bP(a,n),Bm(a,n)]);if(u){let p=await Tn({paths:a,name:n,details:!0});return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[u],continuation:p.continuation})}if(d&&!i){let p=await Tn({paths:a,name:n,details:!0});return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[kP(a,n)],continuation:p.continuation})}let f=await zi(a,n),h=await In({paths:a,state:f}),v=ZF(n,h);if(v&&(h.status==="incompatible"||!i)){let p=await Tn({paths:a,name:n,details:!0});return Xs({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:p,findings:[v],continuation:p.continuation})}if(i){if(d){let b=await Gs({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:b.schema,stateVersion:b.state_version},state:b,continuation:await Ys(a,b)})}let p=await ZE({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:p,continuation:await Ys(a,p.state)})}let m=await Tn({paths:a,name:n,details:!0});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:m,continuation:m.continuation})}if(n){if(i){let u=await Gs({paths:a,name:n});return Yi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ys(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 rP(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Vt("--strategy is only available to the legacy transaction doctor");if(i){let k=await Js({paths:a,repair:!0,projectOnly:!0}),E=[];for(let w of c.transactions)w.kind==="archive"?await Lm({paths:a,name:w.change}):await Gs({paths:a,name:w.change}),E.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await Km([],t),y=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...y,repaired:!0,repairedPortableTransactions:E,repairFindings:k.findings}}}let u=await YF(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,m,p,b,g]=await Promise.all([Promise.all(s.map(k=>Tn({paths:a,name:k}))),Promise.all(s.map(k=>bP(a,k))),Promise.all(s.map(k=>Bm(a,k))),Promise.all(h.map(k=>Js({paths:a,name:k}))),Js({paths:a,projectOnly:!0})]),S=QF([...m.filter(k=>k!==null),...s.flatMap((k,E)=>p[E]&&!f.has(k)?[kP(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:gd.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...b.flatMap(({findings:k})=>k),...g.findings]),N={healthy:S.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:h,findings:S};return N.healthy?Yi("doctor",N):Xs(N)}let l=await Js({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?Yi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}async function EP(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=n.includes("--verbose"),c,l;try{Ks(n,"--json"),Ks(n,"--verbose"),c=vd(n,"--project-root");let d=[...n,...a],f=await vP(c);l=await t(d,f)}catch(d){l=yP(e,d)}let u=NP(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
285
286
  `)?"":`
286
- `)),u.exitCode}process.exitCode=await dP("doctor",Bm);
287
+ `)),u.exitCode}process.exitCode=await EP("doctor",Km);