@rpamis/comet 0.4.0-rc.1 → 0.4.0-rc.3

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 (423) hide show
  1. package/README.md +4 -651
  2. package/assets/manifest.json +1 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +80 -80
  4. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
  5. package/assets/skills/comet/scripts/comet-guard.mjs +102 -102
  6. package/assets/skills/comet/scripts/comet-handoff.mjs +82 -82
  7. package/assets/skills/comet/scripts/comet-hook-guard.mjs +69 -70
  8. package/assets/skills/comet/scripts/comet-hook-router.mjs +120 -121
  9. package/assets/skills/comet/scripts/comet-intent.mjs +6 -6
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +48 -48
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +174 -175
  12. package/assets/skills/comet/scripts/comet-state.mjs +105 -105
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +17 -17
  14. package/assets/skills/comet-native/SKILL.md +6 -5
  15. package/assets/skills/comet-native/reference/commands.md +7 -6
  16. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +124 -118
  17. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +131 -125
  18. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +97 -90
  19. package/assets/skills/comet-native/scripts/comet-native-init.mjs +121 -115
  20. package/assets/skills/comet-native/scripts/comet-native-new.mjs +113 -107
  21. package/assets/skills/comet-native/scripts/comet-native-next.mjs +134 -128
  22. package/assets/skills/comet-native/scripts/comet-native-root.mjs +101 -95
  23. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +166 -159
  24. package/assets/skills/comet-native/scripts/comet-native-select.mjs +114 -108
  25. package/assets/skills/comet-native/scripts/comet-native-show.mjs +98 -92
  26. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +107 -101
  27. package/assets/skills/comet-native/scripts/comet-native-status.mjs +111 -105
  28. package/assets/skills-zh/comet-native/SKILL.md +6 -5
  29. package/assets/skills-zh/comet-native/reference/commands.md +7 -6
  30. package/dist/app/commands/bundle.d.ts.map +1 -1
  31. package/dist/app/commands/bundle.js.map +1 -1
  32. package/dist/app/commands/dashboard.d.ts +1 -1
  33. package/dist/app/commands/dashboard.js +1 -1
  34. package/dist/app/commands/doctor.d.ts.map +1 -1
  35. package/dist/app/commands/doctor.js +1 -1
  36. package/dist/app/commands/doctor.js.map +1 -1
  37. package/dist/app/commands/init.js +2 -2
  38. package/dist/app/commands/init.js.map +1 -1
  39. package/dist/app/commands/platform-select-prompt.d.ts.map +1 -1
  40. package/dist/app/commands/platform-select-prompt.js +1 -0
  41. package/dist/app/commands/platform-select-prompt.js.map +1 -1
  42. package/dist/app/commands/status.d.ts.map +1 -1
  43. package/dist/app/commands/status.js +49 -9
  44. package/dist/app/commands/status.js.map +1 -1
  45. package/dist/app/commands/update.d.ts.map +1 -1
  46. package/dist/app/commands/update.js +13 -49
  47. package/dist/app/commands/update.js.map +1 -1
  48. package/dist/domains/agent-learning/policy-compiler.d.ts.map +1 -1
  49. package/dist/domains/agent-learning/policy-compiler.js.map +1 -1
  50. package/dist/domains/agent-learning/types.d.ts.map +1 -1
  51. package/dist/domains/agent-learning/types.js.map +1 -1
  52. package/dist/domains/bundle/authoring.d.ts.map +1 -1
  53. package/dist/domains/bundle/authoring.js.map +1 -1
  54. package/dist/domains/bundle/next-action.d.ts.map +1 -1
  55. package/dist/domains/bundle/next-action.js.map +1 -1
  56. package/dist/domains/bundle/readiness-user-summary.d.ts.map +1 -1
  57. package/dist/domains/bundle/readiness-user-summary.js.map +1 -1
  58. package/dist/domains/bundle/types.d.ts.map +1 -1
  59. package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
  60. package/dist/domains/comet-classic/classic-archive.js +15 -0
  61. package/dist/domains/comet-classic/classic-archive.js.map +1 -1
  62. package/dist/domains/comet-classic/classic-cli.d.ts +8 -0
  63. package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
  64. package/dist/domains/comet-classic/classic-cli.js +10 -0
  65. package/dist/domains/comet-classic/classic-cli.js.map +1 -1
  66. package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
  67. package/dist/domains/comet-classic/classic-guard.js +20 -0
  68. package/dist/domains/comet-classic/classic-guard.js.map +1 -1
  69. package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
  70. package/dist/domains/comet-classic/classic-handoff.js +13 -0
  71. package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
  72. package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
  73. package/dist/domains/comet-classic/classic-hook-guard.js +14 -15
  74. package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
  75. package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
  76. package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
  77. package/dist/domains/comet-classic/classic-output-language.d.ts +73 -0
  78. package/dist/domains/comet-classic/classic-output-language.d.ts.map +1 -0
  79. package/dist/domains/comet-classic/classic-output-language.js +175 -0
  80. package/dist/domains/comet-classic/classic-output-language.js.map +1 -0
  81. package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
  82. package/dist/domains/comet-classic/classic-script-entry.js +10 -0
  83. package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
  84. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  85. package/dist/domains/comet-classic/classic-state-command.js +43 -4
  86. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  87. package/dist/domains/comet-entry/current-selection.d.ts.map +1 -1
  88. package/dist/domains/comet-entry/current-selection.js.map +1 -1
  89. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  90. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  91. package/dist/domains/comet-entry/project-status.d.ts.map +1 -1
  92. package/dist/domains/comet-entry/project-status.js +15 -3
  93. package/dist/domains/comet-entry/project-status.js.map +1 -1
  94. package/dist/domains/comet-entry/types.d.ts +5 -1
  95. package/dist/domains/comet-entry/types.d.ts.map +1 -1
  96. package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
  97. package/dist/domains/comet-memory/personal-memory.js.map +1 -1
  98. package/dist/domains/comet-memory/types.d.ts.map +1 -1
  99. package/dist/domains/comet-memory/types.js.map +1 -1
  100. package/dist/domains/comet-native/native-atomic-file.d.ts +1 -0
  101. package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
  102. package/dist/domains/comet-native/native-atomic-file.js +19 -0
  103. package/dist/domains/comet-native/native-atomic-file.js.map +1 -1
  104. package/dist/domains/comet-native/native-children.d.ts +17 -0
  105. package/dist/domains/comet-native/native-children.d.ts.map +1 -1
  106. package/dist/domains/comet-native/native-children.js +86 -9
  107. package/dist/domains/comet-native/native-children.js.map +1 -1
  108. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  109. package/dist/domains/comet-native/native-cli-help.js +3 -2
  110. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  111. package/dist/domains/comet-native/native-cli-shared.d.ts +7 -1
  112. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  113. package/dist/domains/comet-native/native-cli-shared.js +51 -4
  114. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  115. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  116. package/dist/domains/comet-native/native-cli.js +4 -2
  117. package/dist/domains/comet-native/native-cli.js.map +1 -1
  118. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  119. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  120. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  121. package/dist/domains/comet-native/native-lock.js +10 -1
  122. package/dist/domains/comet-native/native-lock.js.map +1 -1
  123. package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -1
  124. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  125. package/dist/domains/comet-native/native-loop-runtime.js +39 -6
  126. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  127. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  128. package/dist/domains/comet-native/native-next-command.js +36 -2
  129. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  130. package/dist/domains/comet-native/native-output-language.d.ts +69 -0
  131. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -0
  132. package/dist/domains/comet-native/native-output-language.js +369 -0
  133. package/dist/domains/comet-native/native-output-language.js.map +1 -0
  134. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
  135. package/dist/domains/comet-native/native-portable-archive.js +17 -1
  136. package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
  137. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  138. package/dist/domains/comet-native/native-portable-continuation.js +70 -27
  139. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  140. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -1
  141. package/dist/domains/comet-native/native-portable-migration.js.map +1 -1
  142. package/dist/domains/comet-native/native-portable-recovery.d.ts +1 -0
  143. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
  144. package/dist/domains/comet-native/native-portable-recovery.js +2 -2
  145. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
  146. package/dist/domains/comet-native/native-portable-runtime.d.ts +22 -0
  147. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  148. package/dist/domains/comet-native/native-portable-runtime.js +114 -4
  149. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  150. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  151. package/dist/domains/comet-native/native-portable-state.js +5 -0
  152. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  153. package/dist/domains/comet-native/native-portable-types.d.ts +3 -0
  154. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  155. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  156. package/dist/domains/comet-native/native-runner-input.d.ts +30 -28
  157. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  158. package/dist/domains/comet-native/native-runner-input.js +19 -27
  159. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  160. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  161. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  162. package/dist/domains/comet-native/native-script-entry.d.ts +5 -4
  163. package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
  164. package/dist/domains/comet-native/native-script-entry.js +8 -16
  165. package/dist/domains/comet-native/native-script-entry.js.map +1 -1
  166. package/dist/domains/comet-native/native-status-discovery.d.ts +31 -1
  167. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -1
  168. package/dist/domains/comet-native/native-status-discovery.js +46 -8
  169. package/dist/domains/comet-native/native-status-discovery.js.map +1 -1
  170. package/dist/domains/comet-native/native-supervisor.d.ts +11 -1
  171. package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
  172. package/dist/domains/comet-native/native-supervisor.js +61 -0
  173. package/dist/domains/comet-native/native-supervisor.js.map +1 -1
  174. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  175. package/dist/domains/comet-native/native-verification-receipt.d.ts.map +1 -1
  176. package/dist/domains/comet-native/native-verification-receipt.js.map +1 -1
  177. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  178. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  179. package/dist/domains/comet-plugin/integration.d.ts +2 -0
  180. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  181. package/dist/domains/comet-plugin/integration.js +10 -6
  182. package/dist/domains/comet-plugin/integration.js.map +1 -1
  183. package/dist/domains/dashboard/collector.js +1 -1
  184. package/dist/domains/dashboard/default-plugin-host.d.ts +3 -0
  185. package/dist/domains/dashboard/default-plugin-host.d.ts.map +1 -1
  186. package/dist/domains/dashboard/default-plugin-host.js +38 -4
  187. package/dist/domains/dashboard/default-plugin-host.js.map +1 -1
  188. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  189. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  190. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  191. package/dist/domains/dashboard/native-collector.js +2 -0
  192. package/dist/domains/dashboard/native-collector.js.map +1 -1
  193. package/dist/domains/dashboard/web/assets/abnfDiagram-VCTEODGH-UcCx24DV.js +1 -0
  194. package/dist/domains/dashboard/web/assets/arc-n8qsRq7W.js +1 -0
  195. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-B5p4GzJf.js +1 -0
  196. package/dist/domains/dashboard/web/assets/architectureDiagram-5GKGNRK7-D4pJ8CU0.js +36 -0
  197. package/dist/domains/dashboard/web/assets/array-BifhSqXX.js +1 -0
  198. package/dist/domains/dashboard/web/assets/blockDiagram-I7D4REHJ-C7n-qrSQ.js +129 -0
  199. package/dist/domains/dashboard/web/assets/browser-CgwPGwaV.js +107 -0
  200. package/dist/domains/dashboard/web/assets/c4Diagram-7LVT6UL2-cMVrWYOm.js +38 -0
  201. package/dist/domains/dashboard/web/assets/channel-BZeSeXVb.js +1 -0
  202. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  203. package/dist/domains/dashboard/web/assets/chunk-4HAMMTFA-CE5QrCQd.js +62 -0
  204. package/dist/domains/dashboard/web/assets/{chunk-5VM5RSS4-CopXcnFA.js → chunk-5VM5RSS4-ZNzvKenW.js} +2 -2
  205. package/dist/domains/dashboard/web/assets/chunk-75Z2AOVW-BtZqN-pM.js +2 -0
  206. package/dist/domains/dashboard/web/assets/chunk-DU6HZSFF-CChv0huc.js +125 -0
  207. package/dist/domains/dashboard/web/assets/chunk-F27PBJKO-CDT1ttJ8.js +1 -0
  208. package/dist/domains/dashboard/web/assets/chunk-FOHPRMQF-DHwB1DNv.js +161 -0
  209. package/dist/domains/dashboard/web/assets/chunk-GMAD6QVW-y5m6LMR7.js +72 -0
  210. package/dist/domains/dashboard/web/assets/chunk-GVQU2GXP-DkhKkaHd.js +1 -0
  211. package/dist/domains/dashboard/web/assets/chunk-IMKFNOWR-BaDSh7Jp.js +231 -0
  212. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  213. package/dist/domains/dashboard/web/assets/chunk-L3NEJ4N5-B4ztH2fV.js +1 -0
  214. package/dist/domains/dashboard/web/assets/chunk-OSK3NFVY-BhX6NVzA.js +10 -0
  215. package/dist/domains/dashboard/web/assets/chunk-P2QGCYS3-BCNdGJkX.js +1 -0
  216. package/dist/domains/dashboard/web/assets/chunk-POPQ4Y6H-DwYVuiXw.js +1 -0
  217. package/dist/domains/dashboard/web/assets/chunk-PWAF6VOD-Cyg0IO0R.js +1 -0
  218. package/dist/domains/dashboard/web/assets/chunk-SHT3W25Y-BZ6skx8I.js +168 -0
  219. package/dist/domains/dashboard/web/assets/chunk-SVP7TREG-CLIGmSO0.js +88 -0
  220. package/dist/domains/dashboard/web/assets/chunk-TICWLB2K-BAQBbsn9.js +206 -0
  221. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-D07UbEpV.js +1 -0
  222. package/dist/domains/dashboard/web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  223. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-2fcinal6.js +1 -0
  224. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-2fcinal6.js +1 -0
  225. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-wIi0mUih.js +1 -0
  226. package/dist/domains/dashboard/web/assets/cynefin-OW5HDTMX-DBdxyuTN.js +1 -0
  227. package/dist/domains/dashboard/web/assets/cynefinDiagram-5FMLGOSQ-DzO3jXxV.js +62 -0
  228. package/dist/domains/dashboard/web/assets/cytoscape.esm-CGd-uY3x.js +321 -0
  229. package/dist/domains/dashboard/web/assets/dagre-GXQ25YYZ-CE7H_hZS.js +4 -0
  230. package/dist/domains/dashboard/web/assets/dagre-PrKaheQc.js +1 -0
  231. package/dist/domains/dashboard/web/assets/defaultLocale-BFoDCU3G.js +1 -0
  232. package/dist/domains/dashboard/web/assets/demo-DrJ2uuUL.js +456 -0
  233. package/dist/domains/dashboard/web/assets/diagram-S7CK7UJ4-jUGQk5n-.js +30 -0
  234. package/dist/domains/dashboard/web/assets/diagram-UQ7AKVKN-DaH_zW8T.js +41 -0
  235. package/dist/domains/dashboard/web/assets/diagram-VSXAHHWV-DmG80db0.js +3 -0
  236. package/dist/domains/dashboard/web/assets/diagram-VX7I27RA-ltQ6niKn.js +24 -0
  237. package/dist/domains/dashboard/web/assets/diagram-Z3DM3KII-x92ex4lK.js +24 -0
  238. package/dist/domains/dashboard/web/assets/dist-Cf0h0n6i.js +1 -0
  239. package/dist/domains/dashboard/web/assets/ebnfDiagram-PWID7BFC-CI2u976k.js +1 -0
  240. package/dist/domains/dashboard/web/assets/erDiagram-RLTQ6QDP-DKs90SRd.js +99 -0
  241. package/dist/domains/dashboard/web/assets/es-D7xGlyQk.js +10 -0
  242. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-uARcGZPD.js +1 -0
  243. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-DXL1E4Bl.js +1 -0
  244. package/dist/domains/dashboard/web/assets/ganttDiagram-EL5Y4UJY-D3z6G60S.js +292 -0
  245. package/dist/domains/dashboard/web/assets/gitGraph-4MIJSDKK-vT1UnORT.js +1 -0
  246. package/dist/domains/dashboard/web/assets/gitGraphDiagram-WWUBYQGX-BJmJ96jv.js +106 -0
  247. package/dist/domains/dashboard/web/assets/graphlib-DS17s2tU.js +1 -0
  248. package/dist/domains/dashboard/web/assets/index-BG3MF8re.js +261 -0
  249. package/dist/domains/dashboard/web/assets/index-C2Hlo7VZ.css +1 -0
  250. package/dist/domains/dashboard/web/assets/info-A6RAGUB7-DFeLqqen.js +1 -0
  251. package/dist/domains/dashboard/web/assets/infoDiagram-27XIBGKW-DxuY43XD.js +2 -0
  252. package/dist/domains/dashboard/web/assets/init-C-OQMol4.js +1 -0
  253. package/dist/domains/dashboard/web/assets/ishikawaDiagram-5VMMS53U-DxillfWQ.js +70 -0
  254. package/dist/domains/dashboard/web/assets/journeyDiagram-3NMN7TZE-BPngQ3ag.js +139 -0
  255. package/dist/domains/dashboard/web/assets/kanban-definition-UXKFOSKX-DHMLEGD4.js +89 -0
  256. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +257 -0
  257. package/dist/domains/dashboard/web/assets/line-D31peBjo.js +1 -0
  258. package/dist/domains/dashboard/web/assets/linear-B7X50T2m.js +1 -0
  259. package/dist/domains/dashboard/web/assets/marked.esm-BtJme7Pf.js +65 -0
  260. package/dist/domains/dashboard/web/assets/mermaid-parser.core-CX3Pzygh.js +7 -0
  261. package/dist/domains/dashboard/web/assets/mermaid.core-DlMjBFb6.js +44 -0
  262. package/dist/domains/dashboard/web/assets/mindmap-definition-YA3MSWOX-BKuSGF75.js +96 -0
  263. package/dist/domains/dashboard/web/assets/ordinal-BDEzSJ7C.js +1 -0
  264. package/dist/domains/dashboard/web/assets/packet-AYTQ26CC-B1T8Bds9.js +1 -0
  265. package/dist/domains/dashboard/web/assets/path-fybaL0A-.js +1 -0
  266. package/dist/domains/dashboard/web/assets/pegDiagram-XKGWAZYB-BYgTNxLw.js +1 -0
  267. package/dist/domains/dashboard/web/assets/pie-WAS4IAKB-fqAjmoQw.js +1 -0
  268. package/dist/domains/dashboard/web/assets/pieDiagram-E7YTZNPT-BAO0Ufky.js +39 -0
  269. package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +3 -0
  270. package/dist/domains/dashboard/web/assets/quadrantDiagram-AXDQQJYC-SA_1-7DT.js +7 -0
  271. package/dist/domains/dashboard/web/assets/radar-RG4KPBEZ-Bl_UfUle.js +1 -0
  272. package/dist/domains/dashboard/web/assets/railroad-74A4TZTK-yj6dkiSy.js +1 -0
  273. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CvouMciM.js +1 -0
  274. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CkYQEX72.js +1 -0
  275. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-B0uYr48F.js +1 -0
  276. package/dist/domains/dashboard/web/assets/railroadDiagram-O6MQD6OU-DqV18Y46.js +1 -0
  277. package/dist/domains/dashboard/web/assets/requirementDiagram-BXWQKSXE-Ca2K5LuT.js +84 -0
  278. package/dist/domains/dashboard/web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  279. package/dist/domains/dashboard/web/assets/sankeyDiagram-P5KCCOFB-D9MKl-Nr.js +40 -0
  280. package/dist/domains/dashboard/web/assets/sequenceDiagram-WJ2MYXX4-CXfvIzRx.js +162 -0
  281. package/dist/domains/dashboard/web/assets/sizeCapture-INFHLROL-B0uUizjq.js +1 -0
  282. package/dist/domains/dashboard/web/assets/src-CquUPIQx.js +1 -0
  283. package/dist/domains/dashboard/web/assets/stateDiagram-D77RDMKH-B7iaZHW7.js +1 -0
  284. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-B6KoHQVe.js +1 -0
  285. package/dist/domains/dashboard/web/assets/swimlanes-42K2YHIH-OK-62yZl.js +1 -0
  286. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CjdOls9K.js +8 -0
  287. package/dist/domains/dashboard/web/assets/timeline-definition-24CTP7MA-D0l01B1h.js +120 -0
  288. package/dist/domains/dashboard/web/assets/treeView-Q6P3EWNA-Bg5u_o3A.js +1 -0
  289. package/dist/domains/dashboard/web/assets/treemap-WGGIJYW6-x89ccozk.js +1 -0
  290. package/dist/domains/dashboard/web/assets/vennDiagram-4TSXK5OY-DV19Cqhv.js +34 -0
  291. package/dist/domains/dashboard/web/assets/wardley-WFR3VGLG-BWoeoVk5.js +1 -0
  292. package/dist/domains/dashboard/web/assets/wardleyDiagram-VM6X3IG4-D4fCpoIP.js +78 -0
  293. package/dist/domains/dashboard/web/assets/xychartDiagram-S5SC5T6Z-DALnOMLb.js +7 -0
  294. package/dist/domains/dashboard/web/index.html +2 -2
  295. package/dist/domains/factory/artifacts.d.ts.map +1 -1
  296. package/dist/domains/factory/artifacts.js.map +1 -1
  297. package/dist/domains/factory/types.d.ts.map +1 -1
  298. package/dist/domains/integrations/codegraph.d.ts.map +1 -1
  299. package/dist/domains/integrations/codegraph.js.map +1 -1
  300. package/dist/domains/project-knowledge/local-store.d.ts +21 -0
  301. package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
  302. package/dist/domains/project-knowledge/local-store.js +97 -0
  303. package/dist/domains/project-knowledge/local-store.js.map +1 -1
  304. package/dist/domains/project-knowledge/types.d.ts.map +1 -1
  305. package/dist/domains/skill/platform-inspect.d.ts +1 -1
  306. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  307. package/dist/domains/skill/platform-inspect.js +50 -10
  308. package/dist/domains/skill/platform-inspect.js.map +1 -1
  309. package/dist/domains/skill/platform-install.d.ts +10 -5
  310. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  311. package/dist/domains/skill/platform-install.js +107 -17
  312. package/dist/domains/skill/platform-install.js.map +1 -1
  313. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  314. package/dist/domains/skill/uninstall.js +38 -61
  315. package/dist/domains/skill/uninstall.js.map +1 -1
  316. package/dist/domains/workflow-contract/contained-atomic-write.d.ts +1 -0
  317. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  318. package/dist/domains/workflow-contract/contained-atomic-write.js +19 -0
  319. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  320. package/dist/domains/workflow-contract/global-config.d.ts +8 -0
  321. package/dist/domains/workflow-contract/global-config.d.ts.map +1 -1
  322. package/dist/domains/workflow-contract/global-config.js +25 -0
  323. package/dist/domains/workflow-contract/global-config.js.map +1 -1
  324. package/dist/domains/workflow-contract/index.d.ts +1 -1
  325. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  326. package/dist/domains/workflow-contract/index.js +1 -1
  327. package/dist/domains/workflow-contract/index.js.map +1 -1
  328. package/dist/domains/workflow-contract/output-envelope.d.ts +59 -0
  329. package/dist/domains/workflow-contract/output-envelope.d.ts.map +1 -0
  330. package/dist/domains/workflow-contract/output-envelope.js +108 -0
  331. package/dist/domains/workflow-contract/output-envelope.js.map +1 -0
  332. package/dist/domains/workflow-contract/project-config.d.ts +1 -1
  333. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  334. package/dist/domains/workflow-contract/project-config.js +1 -0
  335. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  336. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  337. package/dist/platform/install/platforms.d.ts +4 -0
  338. package/dist/platform/install/platforms.d.ts.map +1 -1
  339. package/dist/platform/install/platforms.js +15 -3
  340. package/dist/platform/install/platforms.js.map +1 -1
  341. package/dist/platform/paths/project-knowledge-storage.d.ts +1 -1
  342. package/dist/platform/paths/project-knowledge-storage.d.ts.map +1 -1
  343. package/dist/platform/paths/project-knowledge-storage.js +9 -4
  344. package/dist/platform/paths/project-knowledge-storage.js.map +1 -1
  345. package/dist/platform/version/version.d.ts +8 -0
  346. package/dist/platform/version/version.d.ts.map +1 -1
  347. package/dist/platform/version/version.js +58 -8
  348. package/dist/platform/version/version.js.map +1 -1
  349. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +13 -13
  350. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +2 -0
  351. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +1 -0
  352. package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +37 -0
  353. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +13 -13
  354. package/package.json +24 -24
  355. package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BkUJc7LK.js +0 -1
  356. package/dist/domains/dashboard/web/assets/arc-DY4Y9tSO.js +0 -1
  357. package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-7wC9YZS-.js +0 -36
  358. package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-Biqe-SaL.js +0 -132
  359. package/dist/domains/dashboard/web/assets/c4Diagram-5PPSVZJV-CccUFD1S.js +0 -10
  360. package/dist/domains/dashboard/web/assets/channel-DnRvSkOm.js +0 -1
  361. package/dist/domains/dashboard/web/assets/chunk-2GRJ4B5K-BUL4dDxo.js +0 -1
  362. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-BnKtDH9O.js +0 -1
  363. package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-C9pHQ1n3.js +0 -231
  364. package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-CxrbngCi.js +0 -88
  365. package/dist/domains/dashboard/web/assets/chunk-GF5L2VYU-01mzgCUh.js +0 -206
  366. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-wTiZVDvw.js +0 -1
  367. package/dist/domains/dashboard/web/assets/chunk-KBJHAD2P-Bxdv5bl-.js +0 -1
  368. package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-B5vF9l9A.js +0 -1
  369. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-Dra3NnDp.js +0 -1
  370. package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-D3E-rgaQ.js +0 -1
  371. package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-D3E-rgaQ.js +0 -1
  372. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DC96ge-n.js +0 -1
  373. package/dist/domains/dashboard/web/assets/cynefin-VYW2F7L2-Tt_NiopT.js +0 -166
  374. package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-BQ5__1hv.js +0 -62
  375. package/dist/domains/dashboard/web/assets/cytoscape.esm-D3_iZ_3b.js +0 -321
  376. package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-Cr2zq3ro.js +0 -4
  377. package/dist/domains/dashboard/web/assets/defaultLocale-DX6XiGOO.js +0 -1
  378. package/dist/domains/dashboard/web/assets/demo-lxXhgJ9-.js +0 -456
  379. package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-BRpYDwPl.js +0 -30
  380. package/dist/domains/dashboard/web/assets/diagram-B4RE2ZJO-D7u-VBxW.js +0 -3
  381. package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-CHYuv2JD.js +0 -24
  382. package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-CV3ZE8Q3.js +0 -24
  383. package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-co_OsTiQ.js +0 -41
  384. package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-CETcWswS.js +0 -1
  385. package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-edkItb7Z.js +0 -85
  386. package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-D_oFJtSf.js +0 -156
  387. package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-CFjLVoA1.js +0 -292
  388. package/dist/domains/dashboard/web/assets/gitGraphDiagram-DS77QQ5N-BfD0tiKH.js +0 -106
  389. package/dist/domains/dashboard/web/assets/graph-DOmOIIwC.js +0 -1
  390. package/dist/domains/dashboard/web/assets/index-BzyqCfMb.css +0 -1
  391. package/dist/domains/dashboard/web/assets/index-CCKHH_A9.js +0 -10
  392. package/dist/domains/dashboard/web/assets/index-D8dxsTJY.js +0 -271
  393. package/dist/domains/dashboard/web/assets/index-DlSYK56b.js +0 -139
  394. package/dist/domains/dashboard/web/assets/infoDiagram-6WML65LV-Cx6xa9DS.js +0 -2
  395. package/dist/domains/dashboard/web/assets/init-Gi6I4Gst.js +0 -1
  396. package/dist/domains/dashboard/web/assets/ishikawaDiagram-WSZJBQD7-BjNLyyv_.js +0 -70
  397. package/dist/domains/dashboard/web/assets/journeyDiagram-NVQOT4AX-D2n9vrhx.js +0 -139
  398. package/dist/domains/dashboard/web/assets/kanban-definition-27J2QSJJ-kJL7v018.js +0 -89
  399. package/dist/domains/dashboard/web/assets/katex-HP8lGamR.js +0 -257
  400. package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +0 -1
  401. package/dist/domains/dashboard/web/assets/linear-CeHtd5-l.js +0 -1
  402. package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +0 -1
  403. package/dist/domains/dashboard/web/assets/marked.esm-DECB3bxB.js +0 -64
  404. package/dist/domains/dashboard/web/assets/mermaid.core-B0EPSHs2.js +0 -306
  405. package/dist/domains/dashboard/web/assets/mindmap-definition-FAOFIHXS-bQQWINF4.js +0 -96
  406. package/dist/domains/dashboard/web/assets/ordinal-Cboi1Yqb.js +0 -1
  407. package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-LxLY1W7W.js +0 -1
  408. package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-BMDQqvuT.js +0 -39
  409. package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +0 -3
  410. package/dist/domains/dashboard/web/assets/quadrantDiagram-CIZ2JOQS-XWYjcuZN.js +0 -7
  411. package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-p-OlQTa7.js +0 -1
  412. package/dist/domains/dashboard/web/assets/requirementDiagram-LRYGKXZP-BL4N8Vsl.js +0 -84
  413. package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-Btu-o6LN.js +0 -40
  414. package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-9HpdQQ47.js +0 -162
  415. package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-5AnBiBHD.js +0 -1
  416. package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-Dv8IDsai.js +0 -1
  417. package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-DxOMyFOm.js +0 -1
  418. package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-BfJcN7dK.js +0 -2
  419. package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-BnHRSbDk.js +0 -8
  420. package/dist/domains/dashboard/web/assets/timeline-definition-Z64GVDOM-DEOuEHi5.js +0 -120
  421. package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BqsGpwgo.js +0 -34
  422. package/dist/domains/dashboard/web/assets/wardleyDiagram-T6FBY63Y-CXlOp9so.js +0 -78
  423. 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 Ny=Object.create;var jd=Object.defineProperty;var by=Object.getOwnPropertyDescriptor;var ky=Object.getOwnPropertyNames;var Sy=Object.getPrototypeOf,Ey=Object.prototype.hasOwnProperty;var ea=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var Cy=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ky(t))!Ey.call(e,n)&&n!==i&&jd(e,n,{get:()=>t[n],enumerable:!(r=by(t,n))||r.enumerable});return e};var Rr=(e,t,i)=>(i=e!=null?Ny(Sy(e)):{},Cy(t||!e||!e.__esModule?jd(i,"default",{value:e,enumerable:!0}):i,e));var V=x(ue=>{"use strict";var js=Symbol.for("yaml.alias"),Hd=Symbol.for("yaml.document"),ra=Symbol.for("yaml.map"),Dd=Symbol.for("yaml.pair"),$s=Symbol.for("yaml.scalar"),na=Symbol.for("yaml.seq"),Nt=Symbol.for("yaml.node.type"),Ay=e=>!!e&&typeof e=="object"&&e[Nt]===js,_y=e=>!!e&&typeof e=="object"&&e[Nt]===Hd,Iy=e=>!!e&&typeof e=="object"&&e[Nt]===ra,Ty=e=>!!e&&typeof e=="object"&&e[Nt]===Dd,Bd=e=>!!e&&typeof e=="object"&&e[Nt]===$s,jy=e=>!!e&&typeof e=="object"&&e[Nt]===na;function Ld(e){if(e&&typeof e=="object")switch(e[Nt]){case ra:case na:return!0}return!1}function $y(e){if(e&&typeof e=="object")switch(e[Nt]){case js:case ra:case $s:case na:return!0}return!1}var Oy=e=>(Bd(e)||Ld(e))&&!!e.anchor;ue.ALIAS=js;ue.DOC=Hd;ue.MAP=ra;ue.NODE_TYPE=Nt;ue.PAIR=Dd;ue.SCALAR=$s;ue.SEQ=na;ue.hasAnchor=Oy;ue.isAlias=Ay;ue.isCollection=Ld;ue.isDocument=_y;ue.isMap=Iy;ue.isNode=$y;ue.isPair=Ty;ue.isScalar=Bd;ue.isSeq=jy});var Ar=x(Os=>{"use strict";var oe=V(),be=Symbol("break visit"),Vd=Symbol("skip children"),lt=Symbol("remove node");function aa(e,t){let i=Fd(t);oe.isDocument(e)?Oi(null,e.contents,i,Object.freeze([e]))===lt&&(e.contents=null):Oi(null,e,i,Object.freeze([]))}aa.BREAK=be;aa.SKIP=Vd;aa.REMOVE=lt;function Oi(e,t,i,r){let n=Md(e,t,i,r);if(oe.isNode(n)||oe.isPair(n))return qd(e,r,n),Oi(e,n,i,r);if(typeof n!="symbol"){if(oe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Oi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===be)return be;o===lt&&(t.items.splice(a,1),a-=1)}}}else if(oe.isPair(t)){r=Object.freeze(r.concat(t));let a=Oi("key",t.key,i,r);if(a===be)return be;a===lt&&(t.key=null);let o=Oi("value",t.value,i,r);if(o===be)return be;o===lt&&(t.value=null)}}return n}async function oa(e,t){let i=Fd(t);oe.isDocument(e)?await Hi(null,e.contents,i,Object.freeze([e]))===lt&&(e.contents=null):await Hi(null,e,i,Object.freeze([]))}oa.BREAK=be;oa.SKIP=Vd;oa.REMOVE=lt;async function Hi(e,t,i,r){let n=await Md(e,t,i,r);if(oe.isNode(n)||oe.isPair(n))return qd(e,r,n),Hi(e,n,i,r);if(typeof n!="symbol"){if(oe.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await Hi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===be)return be;o===lt&&(t.items.splice(a,1),a-=1)}}}else if(oe.isPair(t)){r=Object.freeze(r.concat(t));let a=await Hi("key",t.key,i,r);if(a===be)return be;a===lt&&(t.key=null);let o=await Hi("value",t.value,i,r);if(o===be)return be;o===lt&&(t.value=null)}}return n}function Fd(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 Md(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(oe.isMap(t))return i.Map?.(e,t,r);if(oe.isSeq(t))return i.Seq?.(e,t,r);if(oe.isPair(t))return i.Pair?.(e,t,r);if(oe.isScalar(t))return i.Scalar?.(e,t,r);if(oe.isAlias(t))return i.Alias?.(e,t,r)}function qd(e,t,i){let r=t[t.length-1];if(oe.isCollection(r))r.items[e]=i;else if(oe.isPair(r))e==="key"?r.key=i:r.value=i;else if(oe.isDocument(r))r.contents=i;else{let n=oe.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Os.visit=aa;Os.visitAsync=oa});var Hs=x(zd=>{"use strict";var Wd=V(),Hy=Ar(),Dy={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},By=e=>e.replace(/[!,[\]{}]/g,t=>Dy[t]),_r=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+By(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&&Wd.isNode(t.contents)){let a={};Hy.visit(t.contents,(o,s)=>{Wd.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
- `)}};_r.defaultYaml={explicit:!1,version:"1.2"};_r.defaultTags={"!!":"tag:yaml.org,2002:"};zd.Directives=_r});var sa=x(Ir=>{"use strict";var Jd=V(),Ly=Ar();function Vy(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 Gd(e){let t=new Set;return Ly.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Ud(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function Fy(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Gd(e));let o=Ud(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Jd.isScalar(o.node)||Jd.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}}Ir.anchorIsValid=Vy;Ir.anchorNames=Gd;Ir.createNodeAnchors=Fy;Ir.findNewAnchor=Ud});var Ds=x(Kd=>{"use strict";function Tr(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=Tr(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=Tr(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=Tr(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=Tr(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}Kd.applyReviver=Tr});var Bt=x(Xd=>{"use strict";var My=V();function Yd(e,t,i){if(Array.isArray(e))return e.map((r,n)=>Yd(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!My.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}Xd.toJS=Yd});var ca=x(Zd=>{"use strict";var qy=Ds(),Qd=V(),Wy=Bt(),Bs=class{constructor(t){Object.defineProperty(this,Qd.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(!Qd.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=Wy.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?qy.applyReviver(a,{"":s},"",s):s}};Zd.NodeBase=Bs});var jr=x(ef=>{"use strict";var zy=sa(),Jy=Ar(),Di=V(),Gy=ca(),Uy=Bt(),Ls=class extends Gy.NodeBase{constructor(t){super(Di.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],Jy.visit(t,{Node:(a,o)=>{(Di.isAlias(o)||Di.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||(Uy.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=la(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(zy.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 la(e,t,i){if(Di.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Di.isCollection(t)){let r=0;for(let n of t.items){let a=la(e,n,i);a>r&&(r=a)}return r}else if(Di.isPair(t)){let r=la(e,t.key,i),n=la(e,t.value,i);return Math.max(r,n)}return 1}ef.Alias=Ls});var re=x(Vs=>{"use strict";var Ky=V(),Yy=ca(),Xy=Bt(),Qy=e=>!e||typeof e!="function"&&typeof e!="object",Lt=class extends Yy.NodeBase{constructor(t){super(Ky.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:Xy.toJS(this.value,t,i)}toString(){return String(this.value)}};Lt.BLOCK_FOLDED="BLOCK_FOLDED";Lt.BLOCK_LITERAL="BLOCK_LITERAL";Lt.PLAIN="PLAIN";Lt.QUOTE_DOUBLE="QUOTE_DOUBLE";Lt.QUOTE_SINGLE="QUOTE_SINGLE";Vs.Scalar=Lt;Vs.isScalarValue=Qy});var $r=x(rf=>{"use strict";var Zy=jr(),hi=V(),tf=re(),eN="tag:yaml.org,2002:";function tN(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 iN(e,t,i){if(hi.isDocument(e)&&(e=e.contents),hi.isNode(e))return e;if(hi.isPair(e)){let d=i.schema[hi.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 Zy.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=eN+t.slice(2));let l=tN(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new tf.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[hi.MAP]:Symbol.iterator in Object(e)?o[hi.SEQ]:o[hi.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 tf.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}rf.createNode=iN});var da=x(ua=>{"use strict";var rN=$r(),ut=V(),nN=ca();function Fs(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 rN.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 nf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ms=class extends nN.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=>ut.isNode(r)||ut.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(nf(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(ut.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fs(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(ut.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&&ut.isScalar(a)?a.value:a:ut.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!ut.isPair(i))return!1;let r=i.value;return r==null||t&&ut.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 ut.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(ut.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Fs(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ua.Collection=Ms;ua.collectionFromPath=Fs;ua.isEmptyPath=nf});var Or=x(fa=>{"use strict";var aN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function qs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var oN=(e,t,i)=>e.endsWith(`
6
- `)?qs(i,t):i.includes(`
4
+ var Ly=Object.create;var Ld=Object.defineProperty;var By=Object.getOwnPropertyDescriptor;var Vy=Object.getOwnPropertyNames;var Fy=Object.getPrototypeOf,My=Object.prototype.hasOwnProperty;var na=(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 P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var qy=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vy(t))!My.call(e,n)&&n!==i&&Ld(e,n,{get:()=>t[n],enumerable:!(r=By(t,n))||r.enumerable});return e};var Tr=(e,t,i)=>(i=e!=null?Ly(Fy(e)):{},qy(t||!e||!e.__esModule?Ld(i,"default",{value:e,enumerable:!0}):i,e));var F=P(fe=>{"use strict";var Ls=Symbol.for("yaml.alias"),Fd=Symbol.for("yaml.document"),sa=Symbol.for("yaml.map"),Md=Symbol.for("yaml.pair"),Bs=Symbol.for("yaml.scalar"),ca=Symbol.for("yaml.seq"),kt=Symbol.for("yaml.node.type"),Gy=e=>!!e&&typeof e=="object"&&e[kt]===Ls,Uy=e=>!!e&&typeof e=="object"&&e[kt]===Fd,Ky=e=>!!e&&typeof e=="object"&&e[kt]===sa,Yy=e=>!!e&&typeof e=="object"&&e[kt]===Md,qd=e=>!!e&&typeof e=="object"&&e[kt]===Bs,Xy=e=>!!e&&typeof e=="object"&&e[kt]===ca;function Wd(e){if(e&&typeof e=="object")switch(e[kt]){case sa:case ca:return!0}return!1}function Qy(e){if(e&&typeof e=="object")switch(e[kt]){case Ls:case sa:case Bs:case ca:return!0}return!1}var Zy=e=>(qd(e)||Wd(e))&&!!e.anchor;fe.ALIAS=Ls;fe.DOC=Fd;fe.MAP=sa;fe.NODE_TYPE=kt;fe.PAIR=Md;fe.SCALAR=Bs;fe.SEQ=ca;fe.hasAnchor=Zy;fe.isAlias=Gy;fe.isCollection=Wd;fe.isDocument=Uy;fe.isMap=Ky;fe.isNode=Qy;fe.isPair=Yy;fe.isScalar=qd;fe.isSeq=Xy});var jr=P(Vs=>{"use strict";var ce=F(),ke=Symbol("break visit"),zd=Symbol("skip children"),ut=Symbol("remove node");function la(e,t){let i=Jd(t);ce.isDocument(e)?Li(null,e.contents,i,Object.freeze([e]))===ut&&(e.contents=null):Li(null,e,i,Object.freeze([]))}la.BREAK=ke;la.SKIP=zd;la.REMOVE=ut;function Li(e,t,i,r){let n=Gd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Ud(e,r,n),Li(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=Li(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ut&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Li("key",t.key,i,r);if(a===ke)return ke;a===ut&&(t.key=null);let o=Li("value",t.value,i,r);if(o===ke)return ke;o===ut&&(t.value=null)}}return n}async function ua(e,t){let i=Jd(t);ce.isDocument(e)?await Bi(null,e.contents,i,Object.freeze([e]))===ut&&(e.contents=null):await Bi(null,e,i,Object.freeze([]))}ua.BREAK=ke;ua.SKIP=zd;ua.REMOVE=ut;async function Bi(e,t,i,r){let n=await Gd(e,t,i,r);if(ce.isNode(n)||ce.isPair(n))return Ud(e,r,n),Bi(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 Bi(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ke)return ke;o===ut&&(t.items.splice(a,1),a-=1)}}}else if(ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await Bi("key",t.key,i,r);if(a===ke)return ke;a===ut&&(t.key=null);let o=await Bi("value",t.value,i,r);if(o===ke)return ke;o===ut&&(t.value=null)}}return n}function Jd(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 Gd(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 Ud(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`)}}Vs.visit=la;Vs.visitAsync=ua});var Fs=P(Yd=>{"use strict";var Kd=F(),eN=jr(),tN={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},iN=e=>e.replace(/[!,[\]{}]/g,t=>tN[t]),$r=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+iN(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&&Kd.isNode(t.contents)){let a={};eN.visit(t.contents,(o,s)=>{Kd.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
+ `)}};$r.defaultYaml={explicit:!1,version:"1.2"};$r.defaultTags={"!!":"tag:yaml.org,2002:"};Yd.Directives=$r});var da=P(Or=>{"use strict";var Xd=F(),rN=jr();function nN(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 Qd(e){let t=new Set;return rN.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function Zd(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function aN(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=Qd(e));let o=Zd(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(Xd.isScalar(o.node)||Xd.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}}Or.anchorIsValid=nN;Or.anchorNames=Qd;Or.createNodeAnchors=aN;Or.findNewAnchor=Zd});var Ms=P(ef=>{"use strict";function Hr(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=Hr(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=Hr(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=Hr(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=Hr(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}ef.applyReviver=Hr});var Vt=P(rf=>{"use strict";var oN=F();function tf(e,t,i){if(Array.isArray(e))return e.map((r,n)=>tf(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!oN.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}rf.toJS=tf});var fa=P(af=>{"use strict";var sN=Ms(),nf=F(),cN=Vt(),qs=class{constructor(t){Object.defineProperty(this,nf.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(!nf.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=cN.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?sN.applyReviver(a,{"":s},"",s):s}};af.NodeBase=qs});var Dr=P(of=>{"use strict";var lN=da(),uN=jr(),Vi=F(),dN=fa(),fN=Vt(),Ws=class extends dN.NodeBase{constructor(t){super(Vi.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=[],uN.visit(t,{Node:(a,o)=>{(Vi.isAlias(o)||Vi.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||(fN.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=pa(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(lN.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 pa(e,t,i){if(Vi.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(Vi.isCollection(t)){let r=0;for(let n of t.items){let a=pa(e,n,i);a>r&&(r=a)}return r}else if(Vi.isPair(t)){let r=pa(e,t.key,i),n=pa(e,t.value,i);return Math.max(r,n)}return 1}of.Alias=Ws});var ne=P(zs=>{"use strict";var pN=F(),hN=fa(),mN=Vt(),vN=e=>!e||typeof e!="function"&&typeof e!="object",Ft=class extends hN.NodeBase{constructor(t){super(pN.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:mN.toJS(this.value,t,i)}toString(){return String(this.value)}};Ft.BLOCK_FOLDED="BLOCK_FOLDED";Ft.BLOCK_LITERAL="BLOCK_LITERAL";Ft.PLAIN="PLAIN";Ft.QUOTE_DOUBLE="QUOTE_DOUBLE";Ft.QUOTE_SINGLE="QUOTE_SINGLE";zs.Scalar=Ft;zs.isScalarValue=vN});var Lr=P(cf=>{"use strict";var gN=Dr(),vi=F(),sf=ne(),wN="tag:yaml.org,2002:";function yN(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 NN(e,t,i){if(vi.isDocument(e)&&(e=e.contents),vi.isNode(e))return e;if(vi.isPair(e)){let d=i.schema[vi.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 gN.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=wN+t.slice(2));let l=yN(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new sf.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[vi.MAP]:Symbol.iterator in Object(e)?o[vi.SEQ]:o[vi.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 sf.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}cf.createNode=NN});var ma=P(ha=>{"use strict";var bN=Lr(),dt=F(),kN=fa();function Js(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 bN.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 lf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Gs=class extends kN.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=>dt.isNode(r)||dt.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(lf(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(dt.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,Js(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(dt.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&&dt.isScalar(a)?a.value:a:dt.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!dt.isPair(i))return!1;let r=i.value;return r==null||t&&dt.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 dt.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(dt.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,Js(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ha.Collection=Gs;ha.collectionFromPath=Js;ha.isEmptyPath=lf});var Br=P(va=>{"use strict";var SN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Us(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var EN=(e,t,i)=>e.endsWith(`
6
+ `)?Us(i,t):i.includes(`
7
7
  `)?`
8
- `+qs(i,t):(e.endsWith(" ")?"":" ")+i;fa.indentComment=qs;fa.lineComment=oN;fa.stringifyComment=aN});var of=x(Hr=>{"use strict";var sN="flow",Ws="block",pa="quoted";function cN(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,S=-1;i===Ws&&(h=af(e,h,t.length),h!==-1&&(d=h+c));for(let N;N=e[h+=1];){if(i===pa&&N==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(N===`
9
- `)i===Ws&&(h=af(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(N===" "&&p&&p!==" "&&p!==`
8
+ `+Us(i,t):(e.endsWith(" ")?"":" ")+i;va.indentComment=Us;va.lineComment=EN;va.stringifyComment=SN});var df=P(Vr=>{"use strict";var CN="flow",Ks="block",ga="quoted";function xN(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,p,v=!1,h=-1,m=-1,S=-1;i===Ks&&(h=uf(e,h,t.length),h!==-1&&(d=h+c));for(let N;N=e[h+=1];){if(i===ga&&N==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}S=h}if(N===`
9
+ `)i===Ks&&(h=uf(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(N===" "&&p&&p!==" "&&p!==`
10
10
  `&&p!==" "){let k=e[h+1];k&&k!==" "&&k!==`
11
- `&&k!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===pa){for(;p===" "||p===" ";)p=N,N=e[h+=1],v=!0;let k=h>S+1?h-2:m-1;if(u[k])return e;l.push(k),u[k]=!0,d=k+c,f=void 0}else v=!0}p=N}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let k=l[N],E=l[N+1]||e.length;k===0?y=`
12
- ${t}${e.slice(0,E)}`:(i===pa&&u[k]&&(y+=`${e[k]}\\`),y+=`
13
- ${t}${e.slice(k+1,E)}`)}return y}function af(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}Hr.FOLD_BLOCK=Ws;Hr.FOLD_FLOW=sN;Hr.FOLD_QUOTED=pa;Hr.foldFlowLines=cN});var Br=x(sf=>{"use strict";var Ge=re(),Vt=of(),ma=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),va=e=>/^(%|---|\.\.\.)/m.test(e);function lN(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 Dr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(va(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)+`
11
+ `&&k!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===ga){for(;p===" "||p===" ";)p=N,N=e[h+=1],v=!0;let k=h>S+1?h-2:m-1;if(u[k])return e;l.push(k),u[k]=!0,d=k+c,f=void 0}else v=!0}p=N}if(v&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let k=l[N],E=l[N+1]||e.length;k===0?y=`
12
+ ${t}${e.slice(0,E)}`:(i===ga&&u[k]&&(y+=`${e[k]}\\`),y+=`
13
+ ${t}${e.slice(k+1,E)}`)}return y}function uf(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}Vr.FOLD_BLOCK=Ks;Vr.FOLD_FLOW=CN;Vr.FOLD_QUOTED=ga;Vr.foldFlowLines=xN});var Mr=P(ff=>{"use strict";var Ue=ne(),Mt=df(),ya=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Na=e=>/^(%|---|\.\.\.)/m.test(e);function PN(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 Fr(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Na(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:Vt.foldFlowLines(o,a,Vt.FOLD_QUOTED,ma(t,!1))}function zs(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Dr(e,t);let i=t.indent||(va(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${i}`)+"'";return t.implicitKey?r:Vt.foldFlowLines(r,i,Vt.FOLD_FLOW,ma(t,!1))}function Bi(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Dr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=zs:a&&!n?r=Dr:r=i?zs:Dr}return r(e,t)}var Js;try{Js=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:Mt.foldFlowLines(o,a,Mt.FOLD_QUOTED,ya(t,!1))}function Ys(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Fr(e,t);let i=t.indent||(Na(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${i}`)+"'";return t.implicitKey?r:Mt.foldFlowLines(r,i,Mt.FOLD_FLOW,ya(t,!1))}function Fi(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Fr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Ys:a&&!n?r=Fr:r=i?Ys:Fr}return r(e,t)}var Xs;try{Xs=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Js=/\n+(?!\n|$)/g}function ha({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 Bi(i,r);let l=r.indent||(r.forceBlockIndent||va(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ge.Scalar.BLOCK_FOLDED?!1:t===Ge.Scalar.BLOCK_LITERAL?!0:!lN(i,c,l.length);if(!i)return u?`|
23
+ |$)`,"g")}catch{Xs=/\n+(?!\n|$)/g}function wa({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 Fi(i,r);let l=r.indent||(r.forceBlockIndent||Na(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ue.Scalar.BLOCK_FOLDED?!1:t===Ue.Scalar.BLOCK_LITERAL?!0:!PN(i,c,l.length);if(!i)return u?`|
24
24
  `:`>
25
25
  `;let d,f;for(f=i.length;f>0;--f){let E=i[f-1];if(E!==`
26
26
  `&&E!==" "&&E!==" ")break}let p=i.substring(f),v=p.indexOf(`
27
27
  `);v===-1?d="-":i===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(i=i.slice(0,-p.length),p[p.length-1]===`
28
- `&&(p=p.slice(0,-1)),p=p.replace(Js,`$&${l}`));let h=!1,m,S=-1;for(m=0;m<i.length;++m){let E=i[m];if(E===" ")h=!0;else if(E===`
28
+ `&&(p=p.slice(0,-1)),p=p.replace(Xs,`$&${l}`));let h=!1,m,S=-1;for(m=0;m<i.length;++m){let E=i[m];if(E===" ")h=!0;else if(E===`
29
29
  `)S=m;else break}let y=i.substring(0,S<m?S+1:m);y&&(i=i.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let k=(h?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=i.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,P=ma(r,!0);o!=="folded"&&t!==Ge.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{b=!0});let g=Vt.foldFlowLines(`${y}${E}${p}`,l,Vt.FOLD_BLOCK,P);if(!b)return`>${k}
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=ya(r,!0);o!=="folded"&&t!==Ue.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{b=!0});let g=Mt.foldFlowLines(`${y}${E}${p}`,l,Mt.FOLD_BLOCK,x);if(!b)return`>${k}
31
31
  ${l}${g}`}return i=i.replace(/\n+/g,`$&${l}`),`|${k}
32
- ${l}${y}${i}${p}`}function uN(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 Bi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?Bi(a,t):ha(e,t,i,r);if(!s&&!u&&n!==Ge.Scalar.PLAIN&&a.includes(`
35
- `))return ha(e,t,i,r);if(va(a)){if(c==="")return t.forceBlockIndent=!0,ha(e,t,i,r);if(s&&c===l)return Bi(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Bi(a,t)}return s?d:Vt.foldFlowLines(d,c,Vt.FOLD_FLOW,ma(t,!1))}function dN(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!==Ge.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ge.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ge.Scalar.BLOCK_FOLDED:case Ge.Scalar.BLOCK_LITERAL:return n||a?Bi(o.value,t):ha(o,t,i,r);case Ge.Scalar.QUOTE_DOUBLE:return Dr(o.value,t);case Ge.Scalar.QUOTE_SINGLE:return zs(o.value,t);case Ge.Scalar.PLAIN:return uN(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}sf.stringifyString=dN});var Lr=x(Gs=>{"use strict";var fN=sa(),Ft=V(),pN=Or(),hN=Br();function mN(e,t){let i=Object.assign({blockQuote:!0,commentString:pN.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 vN(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(Ft.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 gN(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Ft.isScalar(e)||Ft.isCollection(e))&&e.anchor;a&&fN.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 wN(e,t,i,r){if(Ft.isPair(e))return e.toString(t,i,r);if(Ft.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=Ft.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=vN(t.doc.schema.tags,a));let o=gN(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):Ft.isScalar(a)?hN.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Ft.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Gs.createStringifyContext=mN;Gs.stringify=wN});var df=x(uf=>{"use strict";var bt=V(),cf=re(),lf=Lr(),Vr=Or();function yN({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=bt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(bt.isCollection(e)||!bt.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||bt.isCollection(e)||(bt.isScalar(e)?e.type===cf.Scalar.BLOCK_FOLDED||e.type===cf.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=lf.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Vr.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Vr.lineComment(m,i.indent,l(f))),m=`? ${m}
38
- ${s}:`):(m=`${m}:`,f&&(m+=Vr.lineComment(m,i.indent,l(f))));let S,y,N;bt.isNode(t)?(S=!!t.spaceBefore,y=t.commentBefore,N=t.comment):(S=!1,y=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&bt.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&bt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,E=lf.stringify(t,i,()=>k=!0,()=>h=!0),b=" ";if(f||S||y){if(b=S?`
39
- `:"",y){let P=l(y);b+=`
40
- ${Vr.indentComment(P,i.indent)}`}E===""&&!i.inFlow?b===`
32
+ ${l}${y}${i}${p}`}function RN(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 Fi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?Fi(a,t):wa(e,t,i,r);if(!s&&!u&&n!==Ue.Scalar.PLAIN&&a.includes(`
35
+ `))return wa(e,t,i,r);if(Na(a)){if(c==="")return t.forceBlockIndent=!0,wa(e,t,i,r);if(s&&c===l)return Fi(a,t)}let d=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Fi(a,t)}return s?d:Mt.foldFlowLines(d,c,Mt.FOLD_FLOW,ya(t,!1))}function AN(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!==Ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ue.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ue.Scalar.BLOCK_FOLDED:case Ue.Scalar.BLOCK_LITERAL:return n||a?Fi(o.value,t):wa(o,t,i,r);case Ue.Scalar.QUOTE_DOUBLE:return Fr(o.value,t);case Ue.Scalar.QUOTE_SINGLE:return Ys(o.value,t);case Ue.Scalar.PLAIN:return RN(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}ff.stringifyString=AN});var qr=P(Qs=>{"use strict";var _N=da(),qt=F(),IN=Br(),TN=Mr();function jN(e,t){let i=Object.assign({blockQuote:!0,commentString:IN.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 $N(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(qt.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 ON(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(qt.isScalar(e)||qt.isCollection(e))&&e.anchor;a&&_N.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 HN(e,t,i,r){if(qt.isPair(e))return e.toString(t,i,r);if(qt.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=qt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=$N(t.doc.schema.tags,a));let o=ON(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):qt.isScalar(a)?TN.stringifyString(a,t,i,r):a.toString(t,i,r);return o?qt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Qs.createStringifyContext=jN;Qs.stringify=HN});var vf=P(mf=>{"use strict";var St=F(),pf=ne(),hf=qr(),Wr=Br();function DN({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=St.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(St.isCollection(e)||!St.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||f&&t==null&&!i.inFlow||St.isCollection(e)||(St.isScalar(e)?e.type===pf.Scalar.BLOCK_FOLDED||e.type===pf.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=hf.stringify(e,i,()=>v=!0,()=>h=!0);if(!p&&!i.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=Wr.lineComment(m,i.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Wr.lineComment(m,i.indent,l(f))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,f&&(m+=Wr.lineComment(m,i.indent,l(f))));let S,y,N;St.isNode(t)?(S=!!t.spaceBefore,y=t.commentBefore,N=t.comment):(S=!1,y=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!p&&!f&&St.isScalar(t)&&(i.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!i.inFlow&&!p&&St.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let k=!1,E=hf.stringify(t,i,()=>k=!0,()=>h=!0),b=" ";if(f||S||y){if(b=S?`
39
+ `:"",y){let x=l(y);b+=`
40
+ ${Wr.indentComment(x,i.indent)}`}E===""&&!i.inFlow?b===`
41
41
  `&&N&&(b=`
42
42
 
43
43
  `):b+=`
44
- ${i.indent}`}else if(!p&&bt.isCollection(t)){let P=E[0],g=E.indexOf(`
45
- `),w=g!==-1,C=i.inFlow??t.flow??t.items.length===0;if(w||!C){let $=!1;if(w&&(P==="&"||P==="!")){let T=E.indexOf(" ");P==="&"&&T!==-1&&T<g&&E[T+1]==="!"&&(T=E.indexOf(" ",T+1)),(T===-1||g<T)&&($=!0)}$||(b=`
44
+ ${i.indent}`}else if(!p&&St.isCollection(t)){let x=E[0],g=E.indexOf(`
45
+ `),w=g!==-1,C=i.inFlow??t.flow??t.items.length===0;if(w||!C){let $=!1;if(w&&(x==="&"||x==="!")){let T=E.indexOf(" ");x==="&"&&T!==-1&&T<g&&E[T+1]==="!"&&(T=E.indexOf(" ",T+1)),(T===-1||g<T)&&($=!0)}$||(b=`
46
46
  ${i.indent}`)}}else(E===""||E[0]===`
47
- `)&&(b="");return m+=b+E,i.inFlow?k&&r&&r():N&&!k?m+=Vr.lineComment(m,i.indent,l(N)):h&&n&&n(),m}uf.stringifyPair=yN});var Ks=x(Us=>{"use strict";var ff=ea("process");function NN(e,...t){e==="debug"&&console.log(...t)}function bN(e,t){(e==="debug"||e==="warn")&&(typeof ff.emitWarning=="function"?ff.emitWarning(t):console.warn(t))}Us.debug=NN;Us.warn=bN});var ba=x(Na=>{"use strict";var ya=V(),pf=re(),ga="<<",wa={identify:e=>e===ga||typeof e=="symbol"&&e.description===ga,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new pf.Scalar(Symbol(ga)),{addToJSMap:hf}),stringify:()=>ga},kN=(e,t)=>(wa.identify(t)||ya.isScalar(t)&&(!t.type||t.type===pf.Scalar.PLAIN)&&wa.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===wa.tag&&i.default);function hf(e,t,i){let r=mf(e,i);if(ya.isSeq(r))for(let n of r.items)Ys(e,t,n);else if(Array.isArray(r))for(let n of r)Ys(e,t,n);else Ys(e,t,r)}function Ys(e,t,i){let r=mf(e,i);if(!ya.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 mf(e,t){return e&&ya.isAlias(t)?t.resolve(e.doc,e):t}Na.addMergeToJSMap=hf;Na.isMergeKey=kN;Na.merge=wa});var Qs=x(wf=>{"use strict";var SN=Ks(),vf=ba(),EN=Lr(),gf=V(),Xs=Bt();function CN(e,t,{key:i,value:r}){if(gf.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(vf.isMergeKey(e,i))vf.addMergeToJSMap(e,t,r);else{let n=Xs.toJS(i,"",e);if(t instanceof Map)t.set(n,Xs.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=PN(i,n,e),o=Xs.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 PN(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(gf.isNode(e)&&i?.doc){let r=EN.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)+'..."'),SN.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)}wf.addPairToJSMap=CN});var Mt=x(Zs=>{"use strict";var yf=$r(),xN=df(),RN=Qs(),ka=V();function AN(e,t,i){let r=yf.createNode(e,void 0,i),n=yf.createNode(t,void 0,i);return new Sa(r,n)}var Sa=class e{constructor(t,i=null){Object.defineProperty(this,ka.NODE_TYPE,{value:ka.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return ka.isNode(i)&&(i=i.clone(t)),ka.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return RN.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?xN.stringifyPair(this,t,i,r):JSON.stringify(this)}};Zs.Pair=Sa;Zs.createPair=AN});var ec=x(bf=>{"use strict";var mi=V(),Nf=Lr(),Ea=Or();function _N(e,t,i){return(t.inFlow??e.flow?TN:IN)(e,t,i)}function IN({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(mi.isNode(h))!d&&h.spaceBefore&&f.push(""),Ca(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(mi.isPair(h)){let y=mi.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Ca(i,f,y.commentBefore,d))}d=!1;let S=Nf.stringify(h,u,()=>m=null,()=>d=!0);m&&(S+=Ea.lineComment(S,a,l(m))),d&&m&&(d=!1),f.push(r+S)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
47
+ `)&&(b="");return m+=b+E,i.inFlow?k&&r&&r():N&&!k?m+=Wr.lineComment(m,i.indent,l(N)):h&&n&&n(),m}mf.stringifyPair=DN});var ec=P(Zs=>{"use strict";var gf=na("process");function LN(e,...t){e==="debug"&&console.log(...t)}function BN(e,t){(e==="debug"||e==="warn")&&(typeof gf.emitWarning=="function"?gf.emitWarning(t):console.warn(t))}Zs.debug=LN;Zs.warn=BN});var Ca=P(Ea=>{"use strict";var Sa=F(),wf=ne(),ba="<<",ka={identify:e=>e===ba||typeof e=="symbol"&&e.description===ba,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wf.Scalar(Symbol(ba)),{addToJSMap:yf}),stringify:()=>ba},VN=(e,t)=>(ka.identify(t)||Sa.isScalar(t)&&(!t.type||t.type===wf.Scalar.PLAIN)&&ka.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===ka.tag&&i.default);function yf(e,t,i){let r=Nf(e,i);if(Sa.isSeq(r))for(let n of r.items)tc(e,t,n);else if(Array.isArray(r))for(let n of r)tc(e,t,n);else tc(e,t,r)}function tc(e,t,i){let r=Nf(e,i);if(!Sa.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 Nf(e,t){return e&&Sa.isAlias(t)?t.resolve(e.doc,e):t}Ea.addMergeToJSMap=yf;Ea.isMergeKey=VN;Ea.merge=ka});var rc=P(Sf=>{"use strict";var FN=ec(),bf=Ca(),MN=qr(),kf=F(),ic=Vt();function qN(e,t,{key:i,value:r}){if(kf.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(bf.isMergeKey(e,i))bf.addMergeToJSMap(e,t,r);else{let n=ic.toJS(i,"",e);if(t instanceof Map)t.set(n,ic.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=WN(i,n,e),o=ic.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 WN(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if(kf.isNode(e)&&i?.doc){let r=MN.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)+'..."'),FN.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)}Sf.addPairToJSMap=qN});var Wt=P(nc=>{"use strict";var Ef=Lr(),zN=vf(),JN=rc(),xa=F();function GN(e,t,i){let r=Ef.createNode(e,void 0,i),n=Ef.createNode(t,void 0,i);return new Pa(r,n)}var Pa=class e{constructor(t,i=null){Object.defineProperty(this,xa.NODE_TYPE,{value:xa.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return xa.isNode(i)&&(i=i.clone(t)),xa.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return JN.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?zN.stringifyPair(this,t,i,r):JSON.stringify(this)}};nc.Pair=Pa;nc.createPair=GN});var ac=P(xf=>{"use strict";var gi=F(),Cf=qr(),Ra=Br();function UN(e,t,i){return(t.inFlow??e.flow?YN:KN)(e,t,i)}function KN({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(gi.isNode(h))!d&&h.spaceBefore&&f.push(""),Aa(i,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(gi.isPair(h)){let y=gi.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Aa(i,f,y.commentBefore,d))}d=!1;let S=Cf.stringify(h,u,()=>m=null,()=>d=!0);m&&(S+=Ra.lineComment(S,a,l(m))),d&&m&&(d=!1),f.push(r+S)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
48
48
  ${c}${h}`:`
49
49
  `}}return e?(p+=`
50
- `+Ea.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function TN({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(mi.isNode(h))h.spaceBefore&&d.push(""),Ca(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(mi.isPair(h)){let y=mi.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Ca(t,d,y.commentBefore,!1),y.comment&&(l=!0));let N=mi.isNode(h.value)?h.value:null;N?(N.comment&&(m=N.comment),N.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let S=Nf.stringify(h,c,()=>m=null);l||(l=d.length>u||S.includes(`
51
- `)),v<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,N)=>y+N.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),m&&(S+=Ea.lineComment(S,r,s(m))),d.push(S),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?`
50
+ `+Ra.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function YN({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(gi.isNode(h))h.spaceBefore&&d.push(""),Aa(t,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(gi.isPair(h)){let y=gi.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Aa(t,d,y.commentBefore,!1),y.comment&&(l=!0));let N=gi.isNode(h.value)?h.value:null;N?(N.comment&&(m=N.comment),N.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let S=Cf.stringify(h,c,()=>m=null);l||(l=d.length>u||S.includes(`
51
+ `)),v<e.length-1?S+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,N)=>y+N.length+2,2)+(S.length+2)>t.options.lineWidth)),l&&(S+=",")),m&&(S+=Ra.lineComment(S,r,s(m))),d.push(S),u=d.length}let{start:f,end:p}=i;if(d.length===0)return f+p;if(!l){let v=d.reduce((h,m)=>h+m.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let h of d)v+=h?`
52
52
  ${a}${n}${h}`:`
53
53
  `;return`${v}
54
- ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Ca({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Ea.indentComment(t(r),e);i.push(a.trimStart())}}bf.stringifyCollection=_N});var Wt=x(ic=>{"use strict";var jN=ec(),$N=Qs(),ON=da(),qt=V(),Pa=Mt(),HN=re();function Fr(e,t){let i=qt.isScalar(t)?t.value:t;for(let r of e)if(qt.isPair(r)&&(r.key===t||r.key===i||qt.isScalar(r.key)&&r.key.value===i))return r}var tc=class extends ON.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(qt.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(Pa.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;qt.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new Pa.Pair(t,t?.value):r=new Pa.Pair(t.key,t.value);let n=Fr(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);qt.isScalar(n.value)&&HN.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=Fr(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=Fr(this.items,t)?.value;return(!i&&qt.isScalar(n)?n.value:n)??void 0}has(t){return!!Fr(this.items,t)}set(t,i){this.add(new Pa.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)$N.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!qt.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})),jN.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};ic.YAMLMap=tc;ic.findPair=Fr});var Li=x(Sf=>{"use strict";var DN=V(),kf=Wt(),BN={collection:"map",default:!0,nodeClass:kf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return DN.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>kf.YAMLMap.from(e,t,i)};Sf.map=BN});var zt=x(Ef=>{"use strict";var LN=$r(),VN=ec(),FN=da(),Ra=V(),MN=re(),qN=Bt(),rc=class extends FN.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ra.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=xa(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=xa(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Ra.isScalar(n)?n.value:n}has(t){let i=xa(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=xa(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Ra.isScalar(n)&&MN.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(qN.toJS(a,String(n++),i));return r}toString(t,i,r){return t?VN.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(LN.createNode(s,void 0,r))}}return a}};function xa(e){let t=Ra.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Ef.YAMLSeq=rc});var Vi=x(Pf=>{"use strict";var WN=V(),Cf=zt(),zN={collection:"seq",default:!0,nodeClass:Cf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return WN.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Cf.YAMLSeq.from(e,t,i)};Pf.seq=zN});var Mr=x(xf=>{"use strict";var JN=Br(),GN={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),JN.stringifyString(e,t,i,r)}};xf.string=GN});var Aa=x(_f=>{"use strict";var Rf=re(),Af={identify:e=>e==null,createNode:()=>new Rf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Rf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Af.test.test(e)?e:t.options.nullStr};_f.nullTag=Af});var nc=x(Tf=>{"use strict";var UN=re(),If={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new UN.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&If.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Tf.boolTag=If});var Fi=x(jf=>{"use strict";function KN({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}jf.stringifyNumber=KN});var oc=x(_a=>{"use strict";var YN=re(),ac=Fi(),XN={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:ac.stringifyNumber},QN={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():ac.stringifyNumber(e)}},ZN={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 YN.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:ac.stringifyNumber};_a.float=ZN;_a.floatExp=QN;_a.floatNaN=XN});var cc=x(Ta=>{"use strict";var $f=Fi(),Ia=e=>typeof e=="bigint"||Number.isInteger(e),sc=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Of(e,t,i){let{value:r}=e;return Ia(r)&&r>=0?i+r.toString(t):$f.stringifyNumber(e)}var eb={identify:e=>Ia(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>sc(e,2,8,i),stringify:e=>Of(e,8,"0o")},tb={identify:Ia,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>sc(e,0,10,i),stringify:$f.stringifyNumber},ib={identify:e=>Ia(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>sc(e,2,16,i),stringify:e=>Of(e,16,"0x")};Ta.int=tb;Ta.intHex=ib;Ta.intOct=eb});var Df=x(Hf=>{"use strict";var rb=Li(),nb=Aa(),ab=Vi(),ob=Mr(),sb=nc(),lc=oc(),uc=cc(),cb=[rb.map,ab.seq,ob.string,nb.nullTag,sb.boolTag,uc.intOct,uc.int,uc.intHex,lc.floatNaN,lc.floatExp,lc.float];Hf.schema=cb});var Vf=x(Lf=>{"use strict";var lb=re(),ub=Li(),db=Vi();function Bf(e){return typeof e=="bigint"||Number.isInteger(e)}var ja=({value:e})=>JSON.stringify(e),fb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ja},{identify:e=>e==null,createNode:()=>new lb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ja},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ja},{identify:Bf,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})=>Bf(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:ja}],pb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},hb=[ub.map,db.seq].concat(fb,pb);Lf.schema=hb});var fc=x(Ff=>{"use strict";var qr=ea("buffer"),dc=re(),mb=Br(),vb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof qr.Buffer=="function")return qr.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),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 qr.Buffer=="function")s=o instanceof qr.Buffer?o.toString("base64"):qr.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=dc.Scalar.BLOCK_LITERAL),t!==dc.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===dc.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return mb.stringifyString({comment:e,type:t,value:s},r,n,a)}};Ff.binary=vb});var Ha=x(Oa=>{"use strict";var $a=V(),pc=Mt(),gb=re(),wb=zt();function Mf(e,t){if($a.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!$a.isPair(r)){if($a.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new pc.Pair(new gb.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
54
+ ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Aa({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=Ra.indentComment(t(r),e);i.push(a.trimStart())}}xf.stringifyCollection=UN});var Jt=P(sc=>{"use strict";var XN=ac(),QN=rc(),ZN=ma(),zt=F(),_a=Wt(),eb=ne();function zr(e,t){let i=zt.isScalar(t)?t.value:t;for(let r of e)if(zt.isPair(r)&&(r.key===t||r.key===i||zt.isScalar(r.key)&&r.key.value===i))return r}var oc=class extends ZN.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(zt.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(_a.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;zt.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new _a.Pair(t,t?.value):r=new _a.Pair(t.key,t.value);let n=zr(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);zt.isScalar(n.value)&&eb.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=zr(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=zr(this.items,t)?.value;return(!i&&zt.isScalar(n)?n.value:n)??void 0}has(t){return!!zr(this.items,t)}set(t,i){this.add(new _a.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)QN.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!zt.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})),XN.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};sc.YAMLMap=oc;sc.findPair=zr});var Mi=P(Rf=>{"use strict";var tb=F(),Pf=Jt(),ib={collection:"map",default:!0,nodeClass:Pf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return tb.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Pf.YAMLMap.from(e,t,i)};Rf.map=ib});var Gt=P(Af=>{"use strict";var rb=Lr(),nb=ac(),ab=ma(),Ta=F(),ob=ne(),sb=Vt(),cc=class extends ab.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ta.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=Ia(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=Ia(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Ta.isScalar(n)?n.value:n}has(t){let i=Ia(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=Ia(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Ta.isScalar(n)&&ob.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(sb.toJS(a,String(n++),i));return r}toString(t,i,r){return t?nb.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(rb.createNode(s,void 0,r))}}return a}};function Ia(e){let t=Ta.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Af.YAMLSeq=cc});var qi=P(If=>{"use strict";var cb=F(),_f=Gt(),lb={collection:"seq",default:!0,nodeClass:_f.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return cb.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>_f.YAMLSeq.from(e,t,i)};If.seq=lb});var Jr=P(Tf=>{"use strict";var ub=Mr(),db={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),ub.stringifyString(e,t,i,r)}};Tf.string=db});var ja=P(Of=>{"use strict";var jf=ne(),$f={identify:e=>e==null,createNode:()=>new jf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new jf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&$f.test.test(e)?e:t.options.nullStr};Of.nullTag=$f});var lc=P(Df=>{"use strict";var fb=ne(),Hf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new fb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Hf.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Df.boolTag=Hf});var Wi=P(Lf=>{"use strict";function pb({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}Lf.stringifyNumber=pb});var dc=P($a=>{"use strict";var hb=ne(),uc=Wi(),mb={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:uc.stringifyNumber},vb={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():uc.stringifyNumber(e)}},gb={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 hb.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:uc.stringifyNumber};$a.float=gb;$a.floatExp=vb;$a.floatNaN=mb});var pc=P(Ha=>{"use strict";var Bf=Wi(),Oa=e=>typeof e=="bigint"||Number.isInteger(e),fc=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Vf(e,t,i){let{value:r}=e;return Oa(r)&&r>=0?i+r.toString(t):Bf.stringifyNumber(e)}var wb={identify:e=>Oa(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>fc(e,2,8,i),stringify:e=>Vf(e,8,"0o")},yb={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>fc(e,0,10,i),stringify:Bf.stringifyNumber},Nb={identify:e=>Oa(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>fc(e,2,16,i),stringify:e=>Vf(e,16,"0x")};Ha.int=yb;Ha.intHex=Nb;Ha.intOct=wb});var Mf=P(Ff=>{"use strict";var bb=Mi(),kb=ja(),Sb=qi(),Eb=Jr(),Cb=lc(),hc=dc(),mc=pc(),xb=[bb.map,Sb.seq,Eb.string,kb.nullTag,Cb.boolTag,mc.intOct,mc.int,mc.intHex,hc.floatNaN,hc.floatExp,hc.float];Ff.schema=xb});var zf=P(Wf=>{"use strict";var Pb=ne(),Rb=Mi(),Ab=qi();function qf(e){return typeof e=="bigint"||Number.isInteger(e)}var Da=({value:e})=>JSON.stringify(e),_b=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Da},{identify:e=>e==null,createNode:()=>new Pb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Da},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Da},{identify:qf,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})=>qf(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:Da}],Ib={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Tb=[Rb.map,Ab.seq].concat(_b,Ib);Wf.schema=Tb});var gc=P(Jf=>{"use strict";var Gr=na("buffer"),vc=ne(),jb=Mr(),$b={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Gr.Buffer=="function")return Gr.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 Gr.Buffer=="function")s=o instanceof Gr.Buffer?o.toString("base64"):Gr.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=vc.Scalar.BLOCK_LITERAL),t!==vc.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===vc.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return jb.stringifyString({comment:e,type:t,value:s},r,n,a)}};Jf.binary=$b});var Va=P(Ba=>{"use strict";var La=F(),wc=Wt(),Ob=ne(),Hb=Gt();function Gf(e,t){if(La.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!La.isPair(r)){if(La.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new wc.Pair(new Ob.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]=$a.isPair(r)?r:new pc.Pair(r)}}else t("Expected a sequence for this tag");return e}function qf(e,t,i){let{replacer:r}=i,n=new wb.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(pc.createPair(s,c,i))}return n}var yb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Mf,createNode:qf};Oa.createPairs=qf;Oa.pairs=yb;Oa.resolvePairs=Mf});var vc=x(mc=>{"use strict";var Wf=V(),hc=Bt(),Wr=Wt(),Nb=zt(),zf=Ha(),vi=class e extends Nb.YAMLSeq{constructor(){super(),this.add=Wr.YAMLMap.prototype.add.bind(this),this.delete=Wr.YAMLMap.prototype.delete.bind(this),this.get=Wr.YAMLMap.prototype.get.bind(this),this.has=Wr.YAMLMap.prototype.has.bind(this),this.set=Wr.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(Wf.isPair(n)?(a=hc.toJS(n.key,"",i),o=hc.toJS(n.value,a,i)):a=hc.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=zf.createPairs(t,i,r),a=new this;return a.items=n.items,a}};vi.tag="tag:yaml.org,2002:omap";var bb={collection:"seq",identify:e=>e instanceof Map,nodeClass:vi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=zf.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Wf.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new vi,i)},createNode:(e,t,i)=>vi.from(e,t,i)};mc.YAMLOMap=vi;mc.omap=bb});var Yf=x(gc=>{"use strict";var Jf=re();function Gf({value:e,source:t},i){return t&&(e?Uf:Kf).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Uf={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 Jf.Scalar(!0),stringify:Gf},Kf={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 Jf.Scalar(!1),stringify:Gf};gc.falseTag=Kf;gc.trueTag=Uf});var Xf=x(Da=>{"use strict";var kb=re(),wc=Fi(),Sb={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:wc.stringifyNumber},Eb={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():wc.stringifyNumber(e)}},Cb={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 kb.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:wc.stringifyNumber};Da.float=Cb;Da.floatExp=Eb;Da.floatNaN=Sb});var Zf=x(Jr=>{"use strict";var Qf=Fi(),zr=e=>typeof e=="bigint"||Number.isInteger(e);function Ba(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 yc(e,t,i){let{value:r}=e;if(zr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return Qf.stringifyNumber(e)}var Pb={identify:zr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Ba(e,2,2,i),stringify:e=>yc(e,2,"0b")},xb={identify:zr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Ba(e,1,8,i),stringify:e=>yc(e,8,"0")},Rb={identify:zr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Ba(e,0,10,i),stringify:Qf.stringifyNumber},Ab={identify:zr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Ba(e,2,16,i),stringify:e=>yc(e,16,"0x")};Jr.int=Rb;Jr.intBin=Pb;Jr.intHex=Ab;Jr.intOct=xb});var bc=x(Nc=>{"use strict";var Fa=V(),La=Mt(),Va=Wt(),gi=class e extends Va.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Fa.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new La.Pair(t.key,null):i=new La.Pair(t,null),Va.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Va.findPair(this.items,t);return!i&&Fa.isPair(r)?Fa.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=Va.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new La.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(La.createPair(o,null,r));return a}};gi.tag="tag:yaml.org,2002:set";var _b={collection:"map",identify:e=>e instanceof Set,nodeClass:gi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>gi.from(e,t,i),resolve(e,t){if(Fa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new gi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Nc.YAMLSet=gi;Nc.set=_b});var Sc=x(Ma=>{"use strict";var Ib=Fi();function kc(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 ep(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Ib.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 Tb={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})=>kc(e,i),stringify:ep},jb={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=>kc(e,!1),stringify:ep},tp={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(tp.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=kc(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$/,"")??""};Ma.floatTime=jb;Ma.intTime=Tb;Ma.timestamp=tp});var np=x(rp=>{"use strict";var $b=Li(),Ob=Aa(),Hb=Vi(),Db=Mr(),Bb=fc(),ip=Yf(),Ec=Xf(),qa=Zf(),Lb=ba(),Vb=vc(),Fb=Ha(),Mb=bc(),Cc=Sc(),qb=[$b.map,Hb.seq,Db.string,Ob.nullTag,ip.trueTag,ip.falseTag,qa.intBin,qa.intOct,qa.int,qa.intHex,Ec.floatNaN,Ec.floatExp,Ec.float,Bb.binary,Lb.merge,Vb.omap,Fb.pairs,Mb.set,Cc.intTime,Cc.floatTime,Cc.timestamp];rp.schema=qb});var hp=x(Rc=>{"use strict";var cp=Li(),Wb=Aa(),lp=Vi(),zb=Mr(),Jb=nc(),Pc=oc(),xc=cc(),Gb=Df(),Ub=Vf(),up=fc(),Gr=ba(),dp=vc(),fp=Ha(),ap=np(),pp=bc(),Wa=Sc(),op=new Map([["core",Gb.schema],["failsafe",[cp.map,lp.seq,zb.string]],["json",Ub.schema],["yaml11",ap.schema],["yaml-1.1",ap.schema]]),sp={binary:up.binary,bool:Jb.boolTag,float:Pc.float,floatExp:Pc.floatExp,floatNaN:Pc.floatNaN,floatTime:Wa.floatTime,int:xc.int,intHex:xc.intHex,intOct:xc.intOct,intTime:Wa.intTime,map:cp.map,merge:Gr.merge,null:Wb.nullTag,omap:dp.omap,pairs:fp.pairs,seq:lp.seq,set:pp.set,timestamp:Wa.timestamp},Kb={"tag:yaml.org,2002:binary":up.binary,"tag:yaml.org,2002:merge":Gr.merge,"tag:yaml.org,2002:omap":dp.omap,"tag:yaml.org,2002:pairs":fp.pairs,"tag:yaml.org,2002:set":pp.set,"tag:yaml.org,2002:timestamp":Wa.timestamp};function Yb(e,t,i){let r=op.get(t);if(r&&!e)return i&&!r.includes(Gr.merge)?r.concat(Gr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(op.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(Gr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?sp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(sp).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},[])}Rc.coreKnownTags=Kb;Rc.getTags=Yb});var Ic=x(mp=>{"use strict";var Ac=V(),Xb=Li(),Qb=Vi(),Zb=Mr(),za=hp(),ek=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_c=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?za.getTags(t,"compat"):t?za.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?za.coreKnownTags:{},this.tags=za.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,Ac.MAP,{value:Xb.map}),Object.defineProperty(this,Ac.SCALAR,{value:Zb.string}),Object.defineProperty(this,Ac.SEQ,{value:Qb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ek:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};mp.Schema=_c});var gp=x(vp=>{"use strict";var tk=V(),Tc=Lr(),Ur=Or();function ik(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=Tc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Ur.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(tk.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Ur.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Tc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ur.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Tc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(i.push("..."),i.push(Ur.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(Ur.indentComment(a(c),"")))}return i.join(`
57
+ ${a.comment}`:r.comment}r=n}e.items[i]=La.isPair(r)?r:new wc.Pair(r)}}else t("Expected a sequence for this tag");return e}function Uf(e,t,i){let{replacer:r}=i,n=new Hb.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(wc.createPair(s,c,i))}return n}var Db={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gf,createNode:Uf};Ba.createPairs=Uf;Ba.pairs=Db;Ba.resolvePairs=Gf});var bc=P(Nc=>{"use strict";var Kf=F(),yc=Vt(),Ur=Jt(),Lb=Gt(),Yf=Va(),wi=class e extends Lb.YAMLSeq{constructor(){super(),this.add=Ur.YAMLMap.prototype.add.bind(this),this.delete=Ur.YAMLMap.prototype.delete.bind(this),this.get=Ur.YAMLMap.prototype.get.bind(this),this.has=Ur.YAMLMap.prototype.has.bind(this),this.set=Ur.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(Kf.isPair(n)?(a=yc.toJS(n.key,"",i),o=yc.toJS(n.value,a,i)):a=yc.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=Yf.createPairs(t,i,r),a=new this;return a.items=n.items,a}};wi.tag="tag:yaml.org,2002:omap";var Bb={collection:"seq",identify:e=>e instanceof Map,nodeClass:wi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=Yf.resolvePairs(e,t),r=[];for(let{key:n}of i.items)Kf.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new wi,i)},createNode:(e,t,i)=>wi.from(e,t,i)};Nc.YAMLOMap=wi;Nc.omap=Bb});var tp=P(kc=>{"use strict";var Xf=ne();function Qf({value:e,source:t},i){return t&&(e?Zf:ep).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var Zf={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 Xf.Scalar(!0),stringify:Qf},ep={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 Xf.Scalar(!1),stringify:Qf};kc.falseTag=ep;kc.trueTag=Zf});var ip=P(Fa=>{"use strict";var Vb=ne(),Sc=Wi(),Fb={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:Sc.stringifyNumber},Mb={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():Sc.stringifyNumber(e)}},qb={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 Vb.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:Sc.stringifyNumber};Fa.float=qb;Fa.floatExp=Mb;Fa.floatNaN=Fb});var np=P(Yr=>{"use strict";var rp=Wi(),Kr=e=>typeof e=="bigint"||Number.isInteger(e);function Ma(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 Ec(e,t,i){let{value:r}=e;if(Kr(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return rp.stringifyNumber(e)}var Wb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Ma(e,2,2,i),stringify:e=>Ec(e,2,"0b")},zb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Ma(e,1,8,i),stringify:e=>Ec(e,8,"0")},Jb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Ma(e,0,10,i),stringify:rp.stringifyNumber},Gb={identify:Kr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Ma(e,2,16,i),stringify:e=>Ec(e,16,"0x")};Yr.int=Jb;Yr.intBin=Wb;Yr.intHex=Gb;Yr.intOct=zb});var xc=P(Cc=>{"use strict";var za=F(),qa=Wt(),Wa=Jt(),yi=class e extends Wa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;za.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new qa.Pair(t.key,null):i=new qa.Pair(t,null),Wa.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Wa.findPair(this.items,t);return!i&&za.isPair(r)?za.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=Wa.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new qa.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(qa.createPair(o,null,r));return a}};yi.tag="tag:yaml.org,2002:set";var Ub={collection:"map",identify:e=>e instanceof Set,nodeClass:yi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>yi.from(e,t,i),resolve(e,t){if(za.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new yi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Cc.YAMLSet=yi;Cc.set=Ub});var Rc=P(Ja=>{"use strict";var Kb=Wi();function Pc(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 ap(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Kb.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 Yb={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})=>Pc(e,i),stringify:ap},Xb={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=>Pc(e,!1),stringify:ap},op={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(op.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=Pc(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$/,"")??""};Ja.floatTime=Xb;Ja.intTime=Yb;Ja.timestamp=op});var lp=P(cp=>{"use strict";var Qb=Mi(),Zb=ja(),ek=qi(),tk=Jr(),ik=gc(),sp=tp(),Ac=ip(),Ga=np(),rk=Ca(),nk=bc(),ak=Va(),ok=xc(),_c=Rc(),sk=[Qb.map,ek.seq,tk.string,Zb.nullTag,sp.trueTag,sp.falseTag,Ga.intBin,Ga.intOct,Ga.int,Ga.intHex,Ac.floatNaN,Ac.floatExp,Ac.float,ik.binary,rk.merge,nk.omap,ak.pairs,ok.set,_c.intTime,_c.floatTime,_c.timestamp];cp.schema=sk});var yp=P(jc=>{"use strict";var pp=Mi(),ck=ja(),hp=qi(),lk=Jr(),uk=lc(),Ic=dc(),Tc=pc(),dk=Mf(),fk=zf(),mp=gc(),Xr=Ca(),vp=bc(),gp=Va(),up=lp(),wp=xc(),Ua=Rc(),dp=new Map([["core",dk.schema],["failsafe",[pp.map,hp.seq,lk.string]],["json",fk.schema],["yaml11",up.schema],["yaml-1.1",up.schema]]),fp={binary:mp.binary,bool:uk.boolTag,float:Ic.float,floatExp:Ic.floatExp,floatNaN:Ic.floatNaN,floatTime:Ua.floatTime,int:Tc.int,intHex:Tc.intHex,intOct:Tc.intOct,intTime:Ua.intTime,map:pp.map,merge:Xr.merge,null:ck.nullTag,omap:vp.omap,pairs:gp.pairs,seq:hp.seq,set:wp.set,timestamp:Ua.timestamp},pk={"tag:yaml.org,2002:binary":mp.binary,"tag:yaml.org,2002:merge":Xr.merge,"tag:yaml.org,2002:omap":vp.omap,"tag:yaml.org,2002:pairs":gp.pairs,"tag:yaml.org,2002:set":wp.set,"tag:yaml.org,2002:timestamp":Ua.timestamp};function hk(e,t,i){let r=dp.get(t);if(r&&!e)return i&&!r.includes(Xr.merge)?r.concat(Xr.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(dp.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(Xr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?fp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(fp).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},[])}jc.coreKnownTags=pk;jc.getTags=hk});var Hc=P(Np=>{"use strict";var $c=F(),mk=Mi(),vk=qi(),gk=Jr(),Ka=yp(),wk=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Oc=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ka.getTags(t,"compat"):t?Ka.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ka.coreKnownTags:{},this.tags=Ka.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,$c.MAP,{value:mk.map}),Object.defineProperty(this,$c.SCALAR,{value:gk.string}),Object.defineProperty(this,$c.SEQ,{value:vk.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?wk:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Np.Schema=Oc});var kp=P(bp=>{"use strict";var yk=F(),Dc=qr(),Qr=Br();function Nk(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=Dc.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(Qr.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(yk.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(Qr.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Dc.stringify(e.contents,n,()=>s=null,c);s&&(l+=Qr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(Dc.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(i.push("..."),i.push(Qr.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(Qr.indentComment(a(c),"")))}return i.join(`
59
59
  `)+`
60
- `}vp.stringifyDocument=ik});var Kr=x(wp=>{"use strict";var rk=jr(),Mi=da(),Oe=V(),nk=Mt(),ak=Bt(),ok=Ic(),sk=gp(),jc=sa(),ck=Ds(),lk=$r(),$c=Hs(),Oc=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Oe.NODE_TYPE,{value:Oe.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 $c.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,{[Oe.NODE_TYPE]:{value:Oe.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=Oe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){qi(this.contents)&&this.contents.add(t)}addIn(t,i){qi(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=jc.anchorNames(this);t.anchor=!i||r.has(i)?jc.findNewAnchor(i||"a",r):i}return new rk.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,S=i.filter(m).map(String);S.length>0&&(i=i.concat(S)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=jc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=lk.createNode(t,u,v);return s&&Oe.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new nk.Pair(n,a)}delete(t){return qi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Mi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):qi(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Oe.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return Mi.isEmptyPath(t)?!i&&Oe.isScalar(this.contents)?this.contents.value:this.contents:Oe.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Oe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Mi.isEmptyPath(t)?this.contents!==void 0:Oe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=Mi.collectionFromPath(this.schema,[t],i):qi(this.contents)&&this.contents.set(t,i)}setIn(t,i){Mi.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=Mi.collectionFromPath(this.schema,Array.from(t),i):qi(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 $c.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 $c.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 ok.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=ak.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"?ck.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 sk.stringifyDocument(this,t)}};function qi(e){if(Oe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}wp.Document=Oc});var Qr=x(Xr=>{"use strict";var Yr=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Hc=class extends Yr{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Dc=class extends Yr{constructor(t,i,r){super("YAMLWarning",t,i,r)}},uk=(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
+ `}bp.stringifyDocument=Nk});var Zr=P(Sp=>{"use strict";var bk=Dr(),zi=ma(),He=F(),kk=Wt(),Sk=Vt(),Ek=Hc(),Ck=kp(),Lc=da(),xk=Ms(),Pk=Lr(),Bc=Fs(),Vc=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,He.NODE_TYPE,{value:He.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 Bc.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,{[He.NODE_TYPE]:{value:He.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=He.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ji(this.contents)&&this.contents.add(t)}addIn(t,i){Ji(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=Lc.anchorNames(this);t.anchor=!i||r.has(i)?Lc.findNewAnchor(i||"a",r):i}return new bk.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,S=i.filter(m).map(String);S.length>0&&(i=i.concat(S)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Lc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=Pk.createNode(t,u,v);return s&&He.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new kk.Pair(n,a)}delete(t){return Ji(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ji(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return He.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return zi.isEmptyPath(t)?!i&&He.isScalar(this.contents)?this.contents.value:this.contents:He.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return He.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zi.isEmptyPath(t)?this.contents!==void 0:He.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=zi.collectionFromPath(this.schema,[t],i):Ji(this.contents)&&this.contents.set(t,i)}setIn(t,i){zi.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=zi.collectionFromPath(this.schema,Array.from(t),i):Ji(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 Bc.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 Bc.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 Ek.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=Sk.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"?xk.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 Ck.stringifyDocument(this,t)}};function Ji(e){if(He.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Sp.Document=Vc});var rn=P(tn=>{"use strict";var en=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},Fc=class extends en{constructor(t,i,r){super("YAMLParseError",t,i,r)}},Mc=class extends en{constructor(t,i,r){super("YAMLWarning",t,i,r)}},Rk=(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
- `}};Xr.YAMLError=Yr;Xr.YAMLParseError=Hc;Xr.YAMLWarning=Dc;Xr.prettifyError=uk});var Zr=x(yp=>{"use strict";function dk(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,S=null,y=null,N=null,k=null,E=null;for(let g of e)switch(v&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),g.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&g.source.includes(" ")&&(h=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=g.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=g.source:(!k||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(m||S)&&(y=g),u=!0;break;case"anchor":m&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=g,E??(E=g.offset),l=!1,u=!1,v=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,E??(E=g.offset),l=!1,u=!1,v=!0;break}case i:(m||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),k&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),k=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let b=e[e.length-1],P=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:S,newlineAfterProp:y,end:P,start:E??P}}yp.resolveProps=dk});var Ja=x(Np=>{"use strict";function Bc(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(Bc(t.key)||Bc(t.value))return!0}return!1;default:return!0}}Np.containsNewline=Bc});var Lc=x(bp=>{"use strict";var fk=Ja();function pk(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&fk.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}bp.flowIndentCheck=pk});var Vc=x(Sp=>{"use strict";var kp=V();function hk(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||kp.isScalar(a)&&kp.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Sp.mapIncludes=hk});var Ap=x(Rp=>{"use strict";var Ep=Mt(),mk=Wt(),Cp=Zr(),vk=Ja(),Pp=Lc(),gk=Vc(),xp="All mapping items must start at the same column";function wk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??mk.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:v}=u,h=Cp.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",xp)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||vk.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",xp);i.atKey=!0;let S=h.end,y=f?e(i,f,h,n):t(i,S,d,null,h,n);i.schema.compat&&Pp.flowIndentCheck(r.indent,f,n),i.atKey=!1,gk.mapIncludes(i,s.items,y)&&n(S,"DUPLICATE_KEY","Map keys must be unique");let N=Cp.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=N.end,N.found){m&&(v?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<N.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(i,v,N,n):t(i,c,p,null,N,n);i.schema.compat&&Pp.flowIndentCheck(r.indent,v,n),c=k.range[2];let E=new Ep.Pair(y,k);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(y.comment?y.comment+=`
68
- `+N.comment:y.comment=N.comment);let k=new Ep.Pair(y);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}Rp.resolveBlockMap=wk});var Ip=x(_p=>{"use strict";var yk=zt(),Nk=Zr(),bk=Lc();function kk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??yk.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=Nk.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&bk.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}_p.resolveBlockSeq=kk});var Wi=x(Tp=>{"use strict";function Sk(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}}Tp.resolveEnd=Sk});var Hp=x(Op=>{"use strict";var Ek=V(),Ck=Mt(),jp=Wt(),Pk=zt(),xk=Wi(),$p=Zr(),Rk=Ja(),Ak=Vc(),Fc="Block collections are not allowed within flow collections",Mc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function _k({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?jp.YAMLMap:Pk.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let S=r.items[m],{start:y,key:N,sep:k,value:E}=S,b=$p.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:N??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!k&&!E){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
69
- `+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&Rk.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let P="";e:for(let g of y)switch(g.type){case"comma":case"space":break;case"comment":P=g.source.substring(1);break e;default:break e}if(P){let g=l.items[l.items.length-1];Ek.isPair(g)&&(g=g.value??g.key),g.comment?g.comment+=`
70
- `+P:g.comment=P,b.comment=b.comment.substring(P.length+1)}}if(!o&&!k&&!b.found){let P=E?e(i,E,b,n):t(i,b.end,k,null,b,n);l.items.push(P),d=P.range[2],Mc(E)&&n(P.range,"BLOCK_IN_FLOW",Fc)}else{i.atKey=!0;let P=b.end,g=N?e(i,N,b,n):t(i,P,y,null,b,n);Mc(N)&&n(g.range,"BLOCK_IN_FLOW",Fc),i.atKey=!1;let w=$p.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:E,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!b.found&&i.options.strict){if(k)for(let T of k){if(T===w.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.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 E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(i,E,w,n):w.found?t(i,w.end,k,null,w,n):null;C?Mc(E)&&n(C.range,"BLOCK_IN_FLOW",Fc):w.comment&&(g.comment?g.comment+=`
71
- `+w.comment:g.comment=w.comment);let $=new Ck.Pair(g,C);if(i.options.keepSourceTokens&&($.srcToken=S),o){let T=l;Ak.mapIncludes(i,T.items,g)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),T.items.push($)}else{let T=new jp.YAMLMap(i.schema);T.flow=!0,T.items.push($);let de=(C??g).range;T.range=[g.range[0],de[1],de[2]],l.items.push(T)}d=C?C.range[2]:w.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),S=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=xk.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
- `+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}Op.resolveFlowCollection=_k});var Bp=x(Dp=>{"use strict";var Ik=V(),Tk=re(),jk=Wt(),$k=zt(),Ok=Ap(),Hk=Ip(),Dk=Hp();function qc(e,t,i,r,n,a){let o=i.type==="block-map"?Ok.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?Hk.resolveBlockSeq(e,t,i,r,a):Dk.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 Bk(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===jk.YAMLMap.tagName&&s==="map"||o===$k.YAMLSeq.tagName&&s==="seq")return qc(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),qc(e,t,i,n,o)}let l=qc(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Ik.isNode(u)?u:new Tk.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Dp.composeCollection=Bk});var zc=x(Lp=>{"use strict";var Wc=re();function Lk(e,t,i){let r=t.offset,n=Vk(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Wc.Scalar.BLOCK_FOLDED:Wc.Scalar.BLOCK_LITERAL,o=t.source?Fk(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
65
+ `}};tn.YAMLError=en;tn.YAMLParseError=Fc;tn.YAMLWarning=Mc;tn.prettifyError=Rk});var nn=P(Ep=>{"use strict";function Ak(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,S=null,y=null,N=null,k=null,E=null;for(let g of e)switch(v&&(g.type!=="space"&&g.type!=="newline"&&g.type!=="comma"&&a(g.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&g.type!=="comment"&&g.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),g.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&g.source.includes(" ")&&(h=g),u=!0;break;case"comment":{u||a(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=g.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=g.source:(!k||i!=="seq-item-ind")&&(c=!0):f+=g.source,l=!0,p=!0,(m||S)&&(y=g),u=!0;break;case"anchor":m&&a(g,"MULTIPLE_ANCHORS","A node can have at most one anchor"),g.source.endsWith(":")&&a(g.offset+g.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=g,E??(E=g.offset),l=!1,u=!1,v=!0;break;case"tag":{S&&a(g,"MULTIPLE_TAGS","A node can have at most one tag"),S=g,E??(E=g.offset),l=!1,u=!1,v=!0;break}case i:(m||S)&&a(g,"BAD_PROP_ORDER",`Anchors and tags must be after the ${g.source} indicator`),k&&a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.source} in ${t??"collection"}`),k=g,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(g,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=g,l=!1,u=!1;break}default:a(g,"UNEXPECTED_TOKEN",`Unexpected ${g.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:k,spaceBefore:c,comment:d,hasNewline:p,anchor:m,tag:S,newlineAfterProp:y,end:x,start:E??x}}Ep.resolveProps=Ak});var Ya=P(Cp=>{"use strict";function qc(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(qc(t.key)||qc(t.value))return!0}return!1;default:return!0}}Cp.containsNewline=qc});var Wc=P(xp=>{"use strict";var _k=Ya();function Ik(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&_k.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}xp.flowIndentCheck=Ik});var zc=P(Rp=>{"use strict";var Pp=F();function Tk(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Pp.isScalar(a)&&Pp.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Rp.mapIncludes=Tk});var $p=P(jp=>{"use strict";var Ap=Wt(),jk=Jt(),_p=nn(),$k=Ya(),Ip=Wc(),Ok=zc(),Tp="All mapping items must start at the same column";function Hk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??jk.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:v}=u,h=_p.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Tp)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||$k.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&n(c,"BAD_INDENT",Tp);i.atKey=!0;let S=h.end,y=f?e(i,f,h,n):t(i,S,d,null,h,n);i.schema.compat&&Ip.flowIndentCheck(r.indent,f,n),i.atKey=!1,Ok.mapIncludes(i,s.items,y)&&n(S,"DUPLICATE_KEY","Map keys must be unique");let N=_p.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:y.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=N.end,N.found){m&&(v?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&h.start<N.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(i,v,N,n):t(i,c,p,null,N,n);i.schema.compat&&Ip.flowIndentCheck(r.indent,v,n),c=k.range[2];let E=new Ap.Pair(y,k);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(y.comment?y.comment+=`
68
+ `+N.comment:y.comment=N.comment);let k=new Ap.Pair(y);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}jp.resolveBlockMap=Hk});var Hp=P(Op=>{"use strict";var Dk=Gt(),Lk=nn(),Bk=Wc();function Vk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??Dk.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=Lk.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&Bk.flowIndentCheck(r.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[r.offset,c,l??c],s}Op.resolveBlockSeq=Vk});var Gi=P(Dp=>{"use strict";function Fk(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}}Dp.resolveEnd=Fk});var Fp=P(Vp=>{"use strict";var Mk=F(),qk=Wt(),Lp=Jt(),Wk=Gt(),zk=Gi(),Bp=nn(),Jk=Ya(),Gk=zc(),Jc="Block collections are not allowed within flow collections",Gc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Uk({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Lp.YAMLMap:Wk.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let m=0;m<r.items.length;++m){let S=r.items[m],{start:y,key:N,sep:k,value:E}=S,b=Bp.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:N??k?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!k&&!E){m===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<r.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
69
+ `+b.comment:l.comment=b.comment),d=b.end;continue}!o&&i.options.strict&&Jk.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let g of y)switch(g.type){case"comma":case"space":break;case"comment":x=g.source.substring(1);break e;default:break e}if(x){let g=l.items[l.items.length-1];Mk.isPair(g)&&(g=g.value??g.key),g.comment?g.comment+=`
70
+ `+x:g.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!k&&!b.found){let x=E?e(i,E,b,n):t(i,b.end,k,null,b,n);l.items.push(x),d=x.range[2],Gc(E)&&n(x.range,"BLOCK_IN_FLOW",Jc)}else{i.atKey=!0;let x=b.end,g=N?e(i,N,b,n):t(i,x,y,null,b,n);Gc(N)&&n(g.range,"BLOCK_IN_FLOW",Jc),i.atKey=!1;let w=Bp.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:E,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!b.found&&i.options.strict){if(k)for(let T of k){if(T===w.found)break;if(T.type==="newline"){n(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.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 E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(i,E,w,n):w.found?t(i,w.end,k,null,w,n):null;C?Gc(E)&&n(C.range,"BLOCK_IN_FLOW",Jc):w.comment&&(g.comment?g.comment+=`
71
+ `+w.comment:g.comment=w.comment);let $=new qk.Pair(g,C);if(i.options.keepSourceTokens&&($.srcToken=S),o){let T=l;Gk.mapIncludes(i,T.items,g)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),T.items.push($)}else{let T=new Lp.YAMLMap(i.schema);T.flow=!0,T.items.push($);let pe=(C??g).range;T.range=[g.range[0],pe[1],pe[2]],l.items.push(T)}d=C?C.range[2]:w.end}}let f=o?"}":"]",[p,...v]=r.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),S=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",S),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=zk.resolveEnd(v,h,i.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
+ `+m.comment:l.comment=m.comment),l.range=[r.offset,h,m.offset]}else l.range=[r.offset,h,h];return l}Vp.resolveFlowCollection=Uk});var qp=P(Mp=>{"use strict";var Kk=F(),Yk=ne(),Xk=Jt(),Qk=Gt(),Zk=$p(),eS=Hp(),tS=Fp();function Uc(e,t,i,r,n,a){let o=i.type==="block-map"?Zk.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?eS.resolveBlockSeq(e,t,i,r,a):tS.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 iS(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Xk.YAMLMap.tagName&&s==="map"||o===Qk.YAMLSeq.tagName&&s==="seq")return Uc(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),Uc(e,t,i,n,o)}let l=Uc(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Kk.isNode(u)?u:new Yk.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Mp.composeCollection=iS});var Yc=P(Wp=>{"use strict";var Kc=ne();function rS(e,t,i){let r=t.offset,n=nS(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Kc.Scalar.BLOCK_FOLDED:Kc.Scalar.BLOCK_LITERAL,o=t.source?aS(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
73
  `.repeat(Math.max(1,o.length-1)):"",m=r+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[r,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,S]=o[h];if(S===""||S==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&i(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=h,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+S.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
74
- `;for(let h=u;h<s;++h){let[m,S]=o[h];l+=m.length+S.length+1;let y=S[S.length-1]==="\r";if(y&&(S=S.slice(0,-1)),S&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(y?2:1),"BAD_INDENT",k),m=""}a===Wc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+S,f=`
74
+ `;for(let h=u;h<s;++h){let[m,S]=o[h];l+=m.length+S.length+1;let y=S[S.length-1]==="\r";if(y&&(S=S.slice(0,-1)),S&&m.length<c){let k=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-S.length-(y?2:1),"BAD_INDENT",k),m=""}a===Kc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(c)+S,f=`
75
75
  `):m.length>c||S[0]===" "?(f===" "?f=`
76
76
  `:!p&&f===`
77
77
  `&&(f=`
@@ -84,104 +84,110 @@ ${l}
84
84
  `+o[h][0].slice(c);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function Vk({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Fk(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}Lp.resolveBlockScalar=Lk});var Gc=x(Fp=>{"use strict";var Jc=re(),Mk=Wi();function qk(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=Jc.Scalar.PLAIN,c=Wk(a,l);break;case"single-quoted-scalar":s=Jc.Scalar.QUOTE_SINGLE,c=zk(a,l);break;case"double-quoted-scalar":s=Jc.Scalar.QUOTE_DOUBLE,c=Jk(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=Mk.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Wk(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}`),Vp(e)}function zk(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Vp(e.slice(1,-1)).replace(/''/g,"'")}function Vp(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 nS({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":i&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",v);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function aS(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}Wp.resolveBlockScalar=rS});var Qc=P(Jp=>{"use strict";var Xc=ne(),oS=Gi();function sS(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,p,v)=>i(r+f,p,v);switch(n){case"scalar":s=Xc.Scalar.PLAIN,c=cS(a,l);break;case"single-quoted-scalar":s=Xc.Scalar.QUOTE_SINGLE,c=lS(a,l);break;case"double-quoted-scalar":s=Xc.Scalar.QUOTE_DOUBLE,c=uS(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=oS.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function cS(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}`),zp(e)}function lS(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),zp(e.slice(1,-1)).replace(/''/g,"'")}function zp(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 Jk(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 uS(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}=Gk(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Uk[a];if(o)i+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=dS(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=fS[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+=Kk(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+=pS(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 Gk(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 dS(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 Uk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Kk(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}}Fp.resolveFlowScalar=qk});var Wp=x(qp=>{"use strict";var wi=V(),Mp=re(),Yk=zc(),Xk=Gc();function Qk(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Yk.resolveBlockScalar(e,t,r):Xk.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[wi.SCALAR]:c?l=Zk(e.schema,n,c,i,r):t.type==="scalar"?l=eS(e,n,t,r):l=e.schema[wi.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=wi.isScalar(d)?d:new Mp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Mp.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 Zk(e,t,i,r,n){if(i==="!")return e[wi.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[wi.SCALAR])}function eS({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[wi.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[wi.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}qp.composeScalar=Qk});var Jp=x(zp=>{"use strict";function tS(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}zp.emptyScalarPosition=tS});var Kp=x(Kc=>{"use strict";var iS=jr(),rS=V(),nS=Bp(),Gp=Wp(),aS=Wi(),oS=Jp(),sS={composeNode:Up,composeEmptyNode:Uc};function Up(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=cS(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=Gp.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=nS.composeCollection(sS,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=Uc(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&&(!rS.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 Uc(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:oS.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Gp.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 cS({options:e},{offset:t,source:i,end:r},n){let a=new iS.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=aS.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Kc.composeEmptyNode=Uc;Kc.composeNode=Up});var Qp=x(Xp=>{"use strict";var lS=Kr(),Yp=Kp(),uS=Wi(),dS=Zr();function fS(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new lS.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=dS.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?Yp.composeNode(l,n,u,o):Yp.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=uS.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}Xp.composeDoc=fS});var Xc=x(th=>{"use strict";var pS=ea("process"),hS=Hs(),mS=Kr(),en=Qr(),Zp=V(),vS=Qp(),gS=Wi();function tn(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 eh(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 fS={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function pS(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}}Jp.resolveFlowScalar=sS});var Kp=P(Up=>{"use strict";var Ni=F(),Gp=ne(),hS=Yc(),mS=Qc();function vS(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?hS.resolveBlockScalar(e,t,r):mS.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[Ni.SCALAR]:c?l=gS(e.schema,n,c,i,r):t.type==="scalar"?l=wS(e,n,t,r):l=e.schema[Ni.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Ni.isScalar(d)?d:new Gp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new Gp.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 gS(e,t,i,r,n){if(i==="!")return e[Ni.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[Ni.SCALAR])}function wS({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[Ni.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Ni.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}Up.composeScalar=vS});var Xp=P(Yp=>{"use strict";function yS(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}Yp.emptyScalarPosition=yS});var eh=P(el=>{"use strict";var NS=Dr(),bS=F(),kS=qp(),Qp=Kp(),SS=Gi(),ES=Xp(),CS={composeNode:Zp,composeEmptyNode:Zc};function Zp(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=xS(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=Qp.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=kS.composeCollection(CS,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=Zc(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&&(!bS.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 Zc(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:ES.emptyScalarPosition(t,i,r),indent:-1,source:""},d=Qp.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 xS({options:e},{offset:t,source:i,end:r},n){let a=new NS.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=SS.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}el.composeEmptyNode=Zc;el.composeNode=Zp});var rh=P(ih=>{"use strict";var PS=Zr(),th=eh(),RS=Gi(),AS=nn();function _S(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new PS.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=AS.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?th.composeNode(l,n,u,o):th.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=RS.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}ih.composeDoc=_S});var il=P(oh=>{"use strict";var IS=na("process"),TS=Fs(),jS=Zr(),an=rn(),nh=F(),$S=rh(),OS=Gi();function on(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 ah(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 Yc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=tn(i);a?this.warnings.push(new en.YAMLWarning(o,r,n)):this.errors.push(new en.YAMLParseError(o,r,n))},this.directives=new hS.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=eh(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(Zp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Zp.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 tl=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=on(i);a?this.warnings.push(new an.YAMLWarning(o,r,n)):this.errors.push(new an.YAMLParseError(o,r,n))},this.directives=new TS.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=ah(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(nh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];nh.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:eh(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(pS.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=tn(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=vS.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 en.YAMLParseError(tn(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 en.YAMLParseError(tn(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=gS.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 en.YAMLParseError(tn(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 mS.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}}};th.Composer=Yc});var nh=x(Ga=>{"use strict";var wS=zc(),yS=Gc(),NS=Qr(),ih=Br();function bS(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 NS.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yS.resolveFlowScalar(e,t,r);case"block-scalar":return wS.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function kS(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=ih.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:ah(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(IS.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=on(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=$S.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 an.YAMLParseError(on(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 an.YAMLParseError(on(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=OS.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 an.YAMLParseError(on(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 jS.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}}};oh.Composer=tl});var lh=P(Xa=>{"use strict";var HS=Yc(),DS=Qc(),LS=rn(),sh=Mr();function BS(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 LS.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return DS.resolveFlowScalar(e,t,r);case"block-scalar":return HS.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function VS(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=sh.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 rh(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 SS(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=ih.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">":ES(e,c);break;case'"':Qc(e,c,"double-quoted-scalar");break;case"'":Qc(e,c,"single-quoted-scalar");break;default:Qc(e,c,"scalar")}}function ES(e,t){let i=t.indexOf(`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return ch(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 FS(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=sh.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">":MS(e,c);break;case'"':rl(e,c,"double-quoted-scalar");break;case"'":rl(e,c,"single-quoted-scalar");break;default:rl(e,c,"scalar")}}function MS(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}];rh(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function rh(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function Qc(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})}}}Ga.createScalarToken=kS;Ga.resolveAsScalar=bS;Ga.setScalarValue=SS});var oh=x(ah=>{"use strict";var CS=e=>"type"in e?Ka(e):Ua(e);function Ka(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Ka(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Ua(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Ua(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Ua(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 Ua({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Ka(t)),i)for(let a of i)n+=a.source;return r&&(n+=Ka(r)),n}ah.stringify=CS});var uh=x(lh=>{"use strict";var Zc=Symbol("break visit"),PS=Symbol("skip children"),sh=Symbol("remove item");function yi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),ch(Object.freeze([]),e,t)}yi.BREAK=Zc;yi.SKIP=PS;yi.REMOVE=sh;yi.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};yi.parentCollection=(e,t)=>{let i=yi.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 ch(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=ch(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===Zc)return Zc;s===sh&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}lh.visit=yi});var Ya=x(ke=>{"use strict";var el=nh(),xS=oh(),RS=uh(),tl="\uFEFF",il="",rl="",nl="",AS=e=>!!e&&"items"in e,_S=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function IS(e){switch(e){case tl:return"<BOM>";case il:return"<DOC>";case rl:return"<FLOW_END>";case nl:return"<SCALAR>";default:return JSON.stringify(e)}}function TS(e){switch(e){case tl:return"byte-order-mark";case il:return"doc-mode";case rl:return"flow-error-end";case nl: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}];ch(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 ch(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 rl(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})}}}Xa.createScalarToken=VS;Xa.resolveAsScalar=BS;Xa.setScalarValue=FS});var dh=P(uh=>{"use strict";var qS=e=>"type"in e?Za(e):Qa(e);function Za(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Za(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Qa(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Qa(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Qa(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 Qa({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Za(t)),i)for(let a of i)n+=a.source;return r&&(n+=Za(r)),n}uh.stringify=qS});var mh=P(hh=>{"use strict";var nl=Symbol("break visit"),WS=Symbol("skip children"),fh=Symbol("remove item");function bi(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),ph(Object.freeze([]),e,t)}bi.BREAK=nl;bi.SKIP=WS;bi.REMOVE=fh;bi.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};bi.parentCollection=(e,t)=>{let i=bi.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 ph(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=ph(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===nl)return nl;s===fh&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}hh.visit=bi});var eo=P(Se=>{"use strict";var al=lh(),zS=dh(),JS=mh(),ol="\uFEFF",sl="",cl="",ll="",GS=e=>!!e&&"items"in e,US=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function KS(e){switch(e){case ol:return"<BOM>";case sl:return"<DOC>";case cl:return"<FLOW_END>";case ll:return"<SCALAR>";default:return JSON.stringify(e)}}function YS(e){switch(e){case ol:return"byte-order-mark";case sl:return"doc-mode";case cl:return"flow-error-end";case ll: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}ke.createScalarToken=el.createScalarToken;ke.resolveAsScalar=el.resolveAsScalar;ke.setScalarValue=el.setScalarValue;ke.stringify=xS.stringify;ke.visit=RS.visit;ke.BOM=tl;ke.DOCUMENT=il;ke.FLOW_END=rl;ke.SCALAR=nl;ke.isCollection=AS;ke.isScalar=_S;ke.prettyToken=IS;ke.tokenType=TS});var sl=x(fh=>{"use strict";var rn=Ya();function Ue(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var dh=new Set("0123456789ABCDEFabcdef"),jS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Xa=new Set(",[]{}"),$S=new Set(` ,[]{}
121
- \r `),al=e=>!e||$S.has(e),ol=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}Se.createScalarToken=al.createScalarToken;Se.resolveAsScalar=al.resolveAsScalar;Se.setScalarValue=al.setScalarValue;Se.stringify=zS.stringify;Se.visit=JS.visit;Se.BOM=ol;Se.DOCUMENT=sl;Se.FLOW_END=cl;Se.SCALAR=ll;Se.isCollection=GS;Se.isScalar=US;Se.prettyToken=KS;Se.tokenType=YS});var fl=P(gh=>{"use strict";var sn=eo();function Ke(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var vh=new Set("0123456789ABCDEFabcdef"),XS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),to=new Set(",[]{}"),QS=new Set(` ,[]{}
121
+ \r `),ul=e=>!e||QS.has(e),dl=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==="...")&&Ue(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]===rn.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 rn.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==="...")&&Ue(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&&!Ue(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===":")&&Ue(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(al),"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("..."))&&Ue(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield rn.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(al),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ue(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==="...")&&Ke(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]===sn.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 sn.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==="...")&&Ke(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&&!Ke(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===":")&&Ke(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(ul),"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("..."))&&Ke(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield sn.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(ul),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ke(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=>Ue(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=>Ke(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 rn.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(Ue(a)||t&&Xa.has(a))break;i=r}else if(Ue(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 sn.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(Ke(a)||t&&to.has(a))break;i=r}else if(Ke(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&&Xa.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&&Xa.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield rn.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(al),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ue(r)||i&&Xa.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(;!Ue(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(jS.has(i))i=this.buffer[++t];else if(i==="%"&&dh.has(this.buffer[t+1])&&dh.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&&to.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&&to.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield sn.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(ul),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(Ke(r)||i&&to.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(;!Ke(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(XS.has(i))i=this.buffer[++t];else if(i==="%"&&vh.has(this.buffer[t+1])&&vh.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)}};fh.Lexer=ol});var ll=x(ph=>{"use strict";var cl=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}}}};ph.LineCounter=cl});var dl=x(wh=>{"use strict";var OS=ea("process"),hh=Ya(),HS=sl();function Jt(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function mh(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 gh(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 Qa(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 zi(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 Za(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 vh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Jt(t.start,"explicit-key-ind")&&!Jt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,gh(t.value)?t.value.end?Za(t.value.end,t.sep):t.value.end=t.sep:Za(t.start,t.sep),delete t.sep)}var ul=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 HS.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,OS.env.LOG_TOKENS&&console.log("|",hh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=hh.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"&&vh(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&&mh(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":{mh(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=Qa(this.peek(2)),r=zi(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)}};gh.Lexer=dl});var hl=P(wh=>{"use strict";var pl=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}}}};wh.LineCounter=pl});var vl=P(Sh=>{"use strict";var ZS=na("process"),yh=eo(),eE=fl();function Ut(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Nh(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 kh(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 io(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 Ui(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 ro(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 bh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ut(t.start,"explicit-key-ind")&&!Ut(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,kh(t.value)?t.value.end?ro(t.value.end,t.sep):t.value.end=t.sep:ro(t.start,t.sep),delete t.sep)}var ml=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 eE.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,ZS.env.LOG_TOKENS&&console.log("|",yh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=yh.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"&&bh(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&&Nh(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":{Nh(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=io(this.peek(2)),r=Ui(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)){Za(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(Jt(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(gh(i.key)&&!Jt(i.sep,"newline")){let o=zi(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(Jt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=zi(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]}):Jt(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&&!Jt(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)){Za(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||Jt(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=Qa(r),a=zi(n);vh(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)){ro(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(Ut(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(kh(i.key)&&!Ut(i.sep,"newline")){let o=Ui(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(Ut(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ui(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]}):Ut(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&&!Ut(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)){ro(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||Ut(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=io(r),a=Ui(n);bh(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=Qa(t),r=zi(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=Qa(t),r=zi(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())}}};wh.Parser=ul});var Sh=x(an=>{"use strict";var yh=Xc(),DS=Kr(),nn=Qr(),BS=Ks(),LS=V(),VS=ll(),Nh=dl();function bh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new VS.LineCounter||null,prettyErrors:t}}function FS(e,t={}){let{lineCounter:i,prettyErrors:r}=bh(t),n=new Nh.Parser(i?.addNewLine),a=new yh.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(nn.prettifyError(e,i)),s.warnings.forEach(nn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function kh(e,t={}){let{lineCounter:i,prettyErrors:r}=bh(t),n=new Nh.Parser(i?.addNewLine),a=new yh.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 nn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(nn.prettifyError(e,i)),o.warnings.forEach(nn.prettifyError(e,i))),o}function MS(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=kh(e,i);if(!n)return null;if(n.warnings.forEach(a=>BS.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 qS(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 LS.isDocument(e)&&!r?e.toString(i):new DS.Document(e,r,i).toString(i)}an.parse=MS;an.parseAllDocuments=FS;an.parseDocument=kh;an.stringify=qS});var Ji=x(z=>{"use strict";var WS=Xc(),zS=Kr(),JS=Ic(),fl=Qr(),GS=jr(),Gt=V(),US=Mt(),KS=re(),YS=Wt(),XS=zt(),QS=Ya(),ZS=sl(),eE=ll(),tE=dl(),eo=Sh(),Eh=Ar();z.Composer=WS.Composer;z.Document=zS.Document;z.Schema=JS.Schema;z.YAMLError=fl.YAMLError;z.YAMLParseError=fl.YAMLParseError;z.YAMLWarning=fl.YAMLWarning;z.Alias=GS.Alias;z.isAlias=Gt.isAlias;z.isCollection=Gt.isCollection;z.isDocument=Gt.isDocument;z.isMap=Gt.isMap;z.isNode=Gt.isNode;z.isPair=Gt.isPair;z.isScalar=Gt.isScalar;z.isSeq=Gt.isSeq;z.Pair=US.Pair;z.Scalar=KS.Scalar;z.YAMLMap=YS.YAMLMap;z.YAMLSeq=XS.YAMLSeq;z.CST=QS;z.Lexer=ZS.Lexer;z.LineCounter=eE.LineCounter;z.Parser=tE.Parser;z.parse=eo.parse;z.parseAllDocuments=eo.parseAllDocuments;z.parseDocument=eo.parseDocument;z.stringify=eo.stringify;z.visit=Eh.visit;z.visitAsync=Eh.visitAsync});import{promises as gu}from"fs";import Av from"path";var Is={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:"验证预期"}},Py={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:"结论"}},xy={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:"结论"}},$d=new Map,Ts=new Map;for(let e of Object.keys(Is)){for(let[t,i]of Object.entries(Is[e]))$d.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Py[e]))Ts.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(xy[e]))Ts.set(i.toLocaleLowerCase("en-US"),t)}function Ry(e,t){return Is[e][t]}function ta(e){return $d.get(e.trim().toLocaleLowerCase("en-US"))??null}function Od(e){return Ts.get(e.trim().toLocaleLowerCase("en-US"))??null}function ia(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${Ry(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=io(t),r=Ui(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=io(t),r=Ui(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())}}};Sh.Parser=ml});var Rh=P(ln=>{"use strict";var Eh=il(),tE=Zr(),cn=rn(),iE=ec(),rE=F(),nE=hl(),Ch=vl();function xh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new nE.LineCounter||null,prettyErrors:t}}function aE(e,t={}){let{lineCounter:i,prettyErrors:r}=xh(t),n=new Ch.Parser(i?.addNewLine),a=new Eh.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(cn.prettifyError(e,i)),s.warnings.forEach(cn.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Ph(e,t={}){let{lineCounter:i,prettyErrors:r}=xh(t),n=new Ch.Parser(i?.addNewLine),a=new Eh.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 cn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(cn.prettifyError(e,i)),o.warnings.forEach(cn.prettifyError(e,i))),o}function oE(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Ph(e,i);if(!n)return null;if(n.warnings.forEach(a=>iE.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 sE(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 rE.isDocument(e)&&!r?e.toString(i):new tE.Document(e,r,i).toString(i)}ln.parse=oE;ln.parseAllDocuments=aE;ln.parseDocument=Ph;ln.stringify=sE});var Ki=P(J=>{"use strict";var cE=il(),lE=Zr(),uE=Hc(),gl=rn(),dE=Dr(),Kt=F(),fE=Wt(),pE=ne(),hE=Jt(),mE=Gt(),vE=eo(),gE=fl(),wE=hl(),yE=vl(),no=Rh(),Ah=jr();J.Composer=cE.Composer;J.Document=lE.Document;J.Schema=uE.Schema;J.YAMLError=gl.YAMLError;J.YAMLParseError=gl.YAMLParseError;J.YAMLWarning=gl.YAMLWarning;J.Alias=dE.Alias;J.isAlias=Kt.isAlias;J.isCollection=Kt.isCollection;J.isDocument=Kt.isDocument;J.isMap=Kt.isMap;J.isNode=Kt.isNode;J.isPair=Kt.isPair;J.isScalar=Kt.isScalar;J.isSeq=Kt.isSeq;J.Pair=fE.Pair;J.Scalar=pE.Scalar;J.YAMLMap=hE.YAMLMap;J.YAMLSeq=mE.YAMLSeq;J.CST=vE;J.Lexer=gE.Lexer;J.LineCounter=wE.LineCounter;J.Parser=yE.Parser;J.parse=no.parse;J.parseAllDocuments=no.parseAllDocuments;J.parseDocument=no.parseDocument;J.stringify=no.stringify;J.visit=Ah.visit;J.visitAsync=Ah.visitAsync});import{promises as yu}from"fs";import $v from"path";var Hs={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:"验证预期"}},Wy={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:"结论"}},zy={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:"结论"}},Bd=new Map,Ds=new Map;for(let e of Object.keys(Hs)){for(let[t,i]of Object.entries(Hs[e]))Bd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Wy[e]))Ds.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(zy[e]))Ds.set(i.toLocaleLowerCase("en-US"),t)}function Jy(e,t){return Hs[e][t]}function aa(e){return Bd.get(e.trim().toLocaleLowerCase("en-US"))??null}function Vd(e){return Ds.get(e.trim().toLocaleLowerCase("en-US"))??null}function oa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${Jy(e,i)}
143
143
  `).join(`
144
- `)}var hu=Rr(Ji(),1);import{promises as kv}from"fs";import ni from"path";import{execFileSync as iE}from"child_process";import on from"path";function Gi(e,t){return iE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function rE(e,t){let i=on.normalize(e),r=on.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Se(e){try{let t=on.resolve(Gi(e,["rev-parse","--show-toplevel"])),r=Gi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?on.resolve(r.slice(9)):t,a=null;try{a=Gi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!rE(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Ch(e){try{Gi(e,["rev-parse","--is-inside-work-tree"]);let t=Gi(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:on.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 Ui(e){return Ch(e).map(t=>t.root)}function Ni(e,t){try{let i=Gi(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 sE}from"node:crypto";import{promises as Ke}from"node:fs";import He from"node:path";import{TextDecoder as cE}from"node:util";import pl from"path";var nE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),aE=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function oE(e){return e.toLowerCase().startsWith(".env")}function dt(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>oE(r))?"environment-file":i.some(r=>aE.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>nE.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function hl(e,t){let i=dt(t);if(i)return i;let r=pl.resolve(e.projectRoot,...t.split("/")),n=pl.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===pl.resolve(e.configFile)?"native-runtime":null}function Ut(e){return e!==0&&e!==0n&&e!=="0"}function Ae(e,t){return Ut(e.dev)&&Ut(t.dev)&&Ut(e.ino)&&Ut(t.ino)}function F(e,t){let i=Ut(e.dev)&&Ut(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Ut(e.ino)&&Ut(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var sn=1024*1024;function ml(e,t){let i=He.relative(e,t);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function lE(e){let t=He.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})||He.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=dt(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 uE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function dE(e,t){return F({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function to(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ae(i,r)?F(i,r):F(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ph(e){let t=await Ke.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ke.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function fE(e,t){let i=He.resolve(e),r=He.resolve(t);if(!ml(i,r))throw new Error("Native artifact path is outside its root");let n=[await Ph(i)],a=i;for(let o of He.relative(i,r).split(He.sep).filter(Boolean)){a=He.join(a,o);let s=await Ph(a);if(!ml(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function xh(e){for(let t of e){let i=await Ke.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!dE(t,i)||await Ke.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ie(e){let t=lE(e.ref),i=e.maxBytes===null?null:uE(e.maxBytes??sn),r=He.resolve(e.root,...t.split("/")),n=await fE(e.root,He.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ke.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 Ke.realpath(r);if(!ml(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ke.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ke.lstat(r),Ke.realpath(r)]);if(await xh(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!to(a,c)||!to(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let N=i===null?p.length:i+1-f,k=await s.read(p,0,Math.min(p.length,N),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ke.lstat(r),Ke.realpath(r)]);if(await xh(n),!h.isFile()||h.isSymbolicLink()||m!==o||!to(c,v)||!to(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),y;try{y=new cE("utf-8",{fatal:!0}).decode(S)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:e.includeHash===!1?null:sE("sha256").update(S).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as pE}from"crypto";import{promises as pe}from"fs";import Ye from"path";function vl(e,t){let i=Ye.relative(e,t);return i===""||!Ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ye.sep}`)}function hE(e,t){return F({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function gl(e,t){return F({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function mE(e,t){return gl(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Rh(e){let t=await pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function cn(e){for(let t of e){let i=await pe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!hE(t,i)||await pe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function vE(e,t){let i=Ye.resolve(e),r=Ye.resolve(t);if(!vl(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Rh(i)],a=Ye.relative(i,r).split(Ye.sep).filter(Boolean),o=i;for(let s of a){await cn(n),o=Ye.join(o,s);try{await pe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Rh(o);if(!vl(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await cn(n),n}async function gE(e){let t;try{t=await pe.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 wE(e,t,i={}){let r=Ye.dirname(e),n=i.containedRoot?await vE(i.containedRoot,r):null;n||await pe.mkdir(r,{recursive:!0});let a=Ye.join(r,`.${Ye.basename(e)}.${pE()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await pe.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([pe.lstat(a),pe.realpath(a)]);if(await cn(n),!l.isFile()||l.isSymbolicLink()||!gl(s,l)||!vl(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(),!gl(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 cn(n);let l=await pe.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!mE(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await pe.link(a,e),await pe.unlink(a)):await pe.rename(a,e),await gE(r)}catch(l){if(await o?.close(),!n)await pe.rm(a,{force:!0});else try{await cn(n),await pe.rm(a,{force:!0})}catch{}throw l}}async function kt(e,t,i={}){await wE(e,t,i)}async function Xe(e,t,i={}){await kt(e,JSON.stringify(t,null,2)+`
145
- `,i)}var yl=Rr(Ji(),1);import Kt from"path";var ln=64*1024,ro=1024,no=64,Ah=1024,_h=64,Nl=5,io={learning:!0,retrieval:!0},jh={provider:"local"},yE=12e4,Ih=6e5,NE=[".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/**"],bE=["**/.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"],kE=[...NE,...bE].sort((e,t)=>e.localeCompare(t,"en"));var Ee={include:["**/*"],exclude:[...kE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function SE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Kt.posix.isAbsolute(i)||Kt.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 bi(e){let t=SE(e,"native.artifact_root");return t.length===0?".":t.join("/")}function $h(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 ao(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||Kt.posix.isAbsolute(r)||Kt.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 St(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Oh(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 oo(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>ro)throw new Error(`${t} exceeds ${ro} 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>no)throw new Error(`${t} contains more than ${no} wildcard tokens`);return e}function Th(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=>oo(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function wl(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 EE(e){if(e===void 0)return{...Ee,include:[...Ee.include],exclude:[...Ee.exclude]};let t=St(e,"native.snapshot");return{include:Th(t.include,"native.snapshot.include",Ee.include),exclude:Th(t.exclude,"native.snapshot.exclude",Ee.exclude),max_files:wl(t.max_files,Ee.max_files,"native.snapshot.max_files"),max_total_bytes:wl(t.max_total_bytes,Ee.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:wl(t.max_duration_ms,Ee.max_duration_ms,"native.snapshot.max_duration_ms")}}function CE(e){if(e===void 0)return;let t=St(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=St(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:bi(r),toArtifactRoot:bi(n),stage:a,...o?{cleanup:o}:{}}}function PE(e){if(e===void 0)return;let t=St(e,"native.finish");if(t.pull_request===void 0)return{};let i=St(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(Kt.posix.isAbsolute(r[0])||Kt.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??yE;if(!Number.isSafeInteger(n)||n<1||n>Ih)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ih}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function xE(e,t={}){let i=St(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??Nl;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=CE(i.pending_root_move),c=PE(i.finish);return{artifact_root:bi(r),language:Oh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:EE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function RE(e){let t=St(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:$h(t.artifact_layout),language:Oh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function AE(e){let i=St(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)=>ao(r,`hook.allow_paths[${n}]`)))]}}function _E(e){if(e===void 0)return{...io};let t=St(e,"memory"),i=t.learning??io.learning,r=t.retrieval??io.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 bl(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function IE(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")||Kt.posix.isAbsolute(i)||Kt.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>Ah)throw new Error(`${t} exceeds ${Ah} 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>_h)throw new Error(`${t} contains more than ${_h} wildcard tokens`);return i}function TE(e){let i=bl(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)=>IE(r,`knowledge.local.include[${n}]`)))]}}function jE(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 $E(e){let t=bl(e,"knowledge.remote"),i=jE(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 OE(e){if(e===void 0)return{...jh};let t=bl(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:TE(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:$E(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 HE(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function DE(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 un(e,t={}){let i=(0,yl.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=HE(n.ambient_resume),o=n.hook===void 0?void 0:AE(n.hook),s=_E(n.memory),c=OE(n.knowledge),l=n.native===void 0?void 0:xE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:RE(n.classic),d=DE(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 so(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...io},knowledge:{...jh},native:{artifact_root:bi(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Nl,snapshot:{...Ee,include:[...Ee.include],exclude:[...Ee.exclude]}}}}import{createHash as LE}from"crypto";import{promises as uo}from"fs";import Yt from"path";import{constants as co,promises as ki}from"fs";var Qe=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function kl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Hh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function dn(e){return{dev:e.dev,ino:e.ino,birthtime:kl(e)}}function lo(e,t){let i=dn(e),r=dn(t);return Ae(i,r)?F(i,r):F(i,r)&&kl(e)===kl(t)&&Hh(e)===Hh(t)&&e.size===t.size}async function Si(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 ki.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Qe("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Qe("too-large",`${r} exceeds ${t} bytes`);let o=await ki.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:dn(a)});let s=process.platform==="win32"?co.O_RDONLY:co.O_RDONLY|co.O_NOFOLLOW|co.O_NONBLOCK,c;try{c=await ki.open(e,s)}catch(l){throw l.code==="ELOOP"?new Qe("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),ki.lstat(e,{bigint:n}),ki.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!lo(a,l)||!lo(a,u))throw new Qe("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:dn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:N}=await c.read(v,0,Math.min(v.length,y),null);if(N===0)break;if(p+=N,p>t)throw new Qe("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),ki.lstat(e,{bigint:n}),ki.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!lo(a,h)||!lo(a,m))throw new Qe("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:dn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function BE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Sl(e,t){let i=Yt.relative(e,t);return i===""||!Yt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Yt.sep}`)}async function Dh(e,t){let i=Yt.resolve(e),r=await uo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return uo.realpath(i)}async function Bh(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Yt.join(n,i[a]);let o;try{o=await uo.lstat(n)}catch(u){if(BE(u))return{exists:!1,kind:"missing"};throw u}let s=Yt.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 uo.realpath(n);if(!Sl(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 Ki(e,t,i){let r=ao(t,i.label),n=Yt.resolve(e),a=await Dh(n,i.label),o=r.split("/"),s=Yt.resolve(n,...o);if(!Sl(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Bh(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Xt(e,t,i,r){let n=await Ki(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 Dh(n.projectRoot,r.label);return Si(n.target,i,{...r,verify:async(o,s)=>{if(!Sl(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await Bh(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var fn=".comet/config.yaml";function VE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function fo(e,t={}){return(await po(e,t)).document}async function FE(e){try{return(await Xt(e,fn,ln,{label:fn})).bytes}catch(t){if(VE(t))return null;throw t}}function ME(e){return e?{exists:!0,sha256:LE("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function po(e,t={}){let i=await FE(e);return{document:i?un(i.toString("utf8"),t):null,identity:ME(i)}}async function El(e){return(await fo(e))?.config??null}var NO=16*1024;import{existsSync as Vh,promises as Qt}from"fs";import q from"path";import GE from"os";var ho=".comet/config.yaml",UE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function xl(e){try{return await Qt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function KE(e){try{let t=await Qt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xi(e,t){let i=q.relative(e,t);return i===""||!q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${q.sep}`)}async function Yi(e){let t=[],i=e;for(;!await xl(i);){let n=q.dirname(i);if(n===i)break;t.push(q.basename(i)),i=n}let r=await Qt.realpath(i);return q.resolve(r,...t.reverse())}async function Rl(e){try{return(await Qt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mo(e){let t=q.resolve(e);try{(await Qt.stat(t)).isDirectory()||(t=q.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=q.resolve(GE.homedir());for(;;){if(!(t===r&&i!==r)){let o=q.join(t,...ho.split("/")),s=t===i||await KE(o);if(await xl(o)&&s)return t}if(await xl(q.join(t,".git")))return t;let a=q.dirname(t);if(a===t)return i;t=a}}function vo(e){return bi(e)}async function YE(e,t){let i=vo(t),r=q.resolve(e,...i.split("/")),n=await Qt.realpath(e),a=await Yi(r);if(!Xi(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Ei(e,t){let i=vo(t),r=await YE(e,i),n=q.join(r,"comet");if(await Rl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Yi(r),Yi(n)]);if(!Xi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=q.resolve(e),c=q.join(s,".comet","runtime","native");if(await Rl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Qt.realpath(s),Yi(c)]);if(!Xi(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:q.join(e,...ho.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:q.join(n,"specs"),changesDir:q.join(n,"changes"),archiveDir:q.join(n,"archive"),runtimeDir:c,changesRuntimeDir:q.join(c,"changes"),locksDir:q.join(c,"locks"),transactionsDir:q.join(c,"transactions")}}function Mh(e){if(!UE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Zt(e,t){Mh(t);let i=q.join(e.changesRuntimeDir,t);if(!L(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function qh(e,t){Mh(t);let i=q.join(e.changesDir,t,"runtime");if(!L(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function G(e,t){let i=Zt(e,t);if(Vh(i))return i;let r=qh(e,t);return Vh(r)?r:i}async function Fh(e){try{let t=await Qt.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Al(e,t){let i=Zt(e,t),r=qh(e,t),[n,a]=await Promise.all([Fh(i),Fh(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 ei(e,t){if(!t.startsWith("runtime/")||q.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=q.resolve(e,...t.slice(8).split("/"));if(!L(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function ce(e,t){let i=q.resolve(t);if(L(e.runtimeDir,i))return e.runtimeDir;if(L(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function L(e,t){return Xi(q.resolve(e),q.resolve(t))}async function W(e,t){let i=q.resolve(e),r=q.resolve(t);if(!Xi(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Rl(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Yi(i),Yi(r)]);if(!Xi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var _l=Ee;var go=oo;function QE(e="docs",t="en"){return so(e,t)}async function _e(e){let t=(await fo(e))?.config??null;return t?.native?t:null}async function wo(e){let t=await _e(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 Wh(e){let t=await mo(e.startPath),i=await _e(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${ho} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?vo(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??QE(r??"docs"),a=await Ei(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as IP}from"fs";import TP from"path";import{AsyncLocalStorage as ZE}from"async_hooks";import{randomUUID as Gh}from"crypto";import{promises as De}from"fs";import Uh from"os";import we from"path";var zh=16*1024,Kh=".coordinator",eC=5e3,Jh=new ZE,yo=new Map;function tC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function iC(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 Yh(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 Il(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ae(i,r)?F(i,r):F(i,r)&&e.size===t.size}function Tl(e,t){return Il(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Et(e){let t,i;try{let r=await Si(e,zh,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Qe?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${zh} 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:iC(JSON.parse(t.toString("utf8")),e),identity:Yh(i)}}async function rC(e){return(await Et(e))?.owner??null}function Xh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Uh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=lC(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function nC(e,t){try{await De.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await De.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function jl(e,t){let i=await Et(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Tl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await De.mkdir(t,{recursive:!0});let r=we.join(t,`${we.basename(e.file)}.${e.owner.id}.${Gh()}.removed`);try{await De.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Et(r);if(!n||n.owner.id!==e.owner.id||!Il(n.identity,e.identity))throw await nC(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await De.rm(r,{force:!0}),"removed"}function Qh(e){return{id:Gh(),pid:process.pid,hostname:Uh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Zh(e,t){let i;try{i=await De.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await rC(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)+`
146
- `,"utf8"),await i.sync(),Yh(await i.stat({bigint:!0}))}finally{await i.close()}}async function aC(e,t){let i=await W(e.runtimeDir,e.locksDir);await De.mkdir(i,{recursive:!0});let r=await W(e.runtimeDir,we.join(i,Kh));await De.mkdir(r,{recursive:!0});let n=Qh(t),a=we.join(r,`.${n.id}.tmp`),o=we.join(r,`${n.id}.claim`);try{let s=await Zh(a,n);await De.rename(a,o);let c=await Et(o);if(!c||!Il(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 De.rm(a,{force:!0})}}async function oC(e){let t=we.dirname(e.file),i=!1,r=we.basename(e.file);for(let n of await De.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=we.join(t,n.name);if(we.resolve(a)!==we.resolve(e.file))try{let o=await Et(a),s=Xh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await jl(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function em(e){let t=await Et(e.file);if(t){if(t.owner.id!==e.owner.id||!Tl(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await jl(t,we.dirname(e.file))}}async function sC(e,t){let i=Date.now()+eC;for(;;){let r=await aC(e,t);if(!await oC(r))return r;if(await em(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 cC(e){let t=yo.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return yo.set(e,n),await t,()=>{i(),yo.get(e)===n&&yo.delete(e)}}async function tm(e,t,i){let r=we.resolve(e.locksDir),n=Jh.getStore();if(n?.has(r))return i();let a=await cC(r);try{let o=await sC(e,t),s=new Map(n??[]);return s.set(r,o),await Jh.run(s,async()=>{try{return await i()}finally{await em(o)}})}finally{a()}}async function No(e,t,i){return tm(e,`acquire ${t}`,async()=>{let r=await W(e.runtimeDir,e.locksDir);await De.mkdir(r,{recursive:!0});let n=await W(e.runtimeDir,we.join(r,tC(t))),a=Qh(i),o=await Zh(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function bo(e){await Et(e.file)&&await tm({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${we.basename(e.file)}`,async()=>{let t=await Et(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Tl(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=we.join(e.locksDir,Kh);await jl(t,i)})}function lC(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function im(e){return Xh(await Et(e))}import aP from"node:path";import rm from"node:path";import{createHash as uC}from"crypto";function Ze(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function dC(e,t){t.has(e)&&Ze("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)||Ze("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Ze("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ze("symbol properties are not supported"),`[${e.map(r=>$l(r,t)).join(",")}]`}finally{t.delete(e)}}function fC(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Ze("only plain objects are supported"),t.has(e)&&Ze("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ze("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Ze("accessor properties are not supported"),`${JSON.stringify(o)}:${$l(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function $l(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Ze("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?dC(e,t):fC(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ze(`${typeof e} values are not supported`)}return Ze("unsupported value type")}function hn(e){return $l(e,new Set)}function B(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 uC("sha256").update(`${e}
147
- ${hn(t)}`).digest("hex")}var pC="comet.native.acceptance.v1",hC=/^acceptance-[a-f0-9]{64}$/u,mC=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),vC=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,gC=/^[a-f0-9]{64}$/u,wC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function yC(e,t){return e<t?-1:e>t?1:0}var Ct=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),mn=Object.freeze({maxCriteria:1024}),nm="<!-- comet-native:acceptance-evidence:start -->",am="<!-- comet-native:acceptance-evidence:end -->";function om(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 sm(e,t){let i=t.toString(36),r=B("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function NC(e){if(!gC.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=wC.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]!==B("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function bC(e,t){let i=om(e.text,Ct.maxTextBytes),r=e.context.slice(0,Ct.maxContextItems).map(n=>om(n,Ct.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 lm(e){let t=NC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(yC),n=r.slice(0,Ct.maxFailedCheckIds),a=e.criteria.slice(t,t+Ct.maxItems);for(let c of a){let l=[...i,bC(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?sm(e.acceptanceHash,u):null,limits:{...Ct}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Ct.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?sm(e.acceptanceHash,o):null,limits:{...Ct}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Ct.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Hl(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 Ol(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 cm(e){return e.includes("-->")||e.includes("--!>")}function*Qi(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
144
+ `)}var vu=Tr(Ki(),1);import{promises as Pv}from"fs";import oi from"path";import{execFileSync as NE}from"child_process";import un from"path";function Yi(e,t){return NE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function bE(e,t){let i=un.normalize(e),r=un.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Ee(e){try{let t=un.resolve(Yi(e,["rev-parse","--show-toplevel"])),r=Yi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?un.resolve(r.slice(9)):t,a=null;try{a=Yi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!bE(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function _h(e){try{Yi(e,["rev-parse","--is-inside-work-tree"]);let t=Yi(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:un.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 Xi(e){return _h(e).map(t=>t.root)}function ki(e,t){try{let i=Yi(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 CE}from"node:crypto";import{promises as Ye}from"node:fs";import De from"node:path";import{TextDecoder as xE}from"node:util";import wl from"path";var kE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),SE=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function EE(e){return e.toLowerCase().startsWith(".env")}function ft(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>EE(r))?"environment-file":i.some(r=>SE.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>kE.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function yl(e,t){let i=ft(t);if(i)return i;let r=wl.resolve(e.projectRoot,...t.split("/")),n=wl.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===wl.resolve(e.configFile)?"native-runtime":null}function Yt(e){return e!==0&&e!==0n&&e!=="0"}function _e(e,t){return Yt(e.dev)&&Yt(t.dev)&&Yt(e.ino)&&Yt(t.ino)}function M(e,t){let i=Yt(e.dev)&&Yt(t.dev);if(i&&e.dev!==t.dev)return!1;let r=Yt(e.ino)&&Yt(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var dn=1024*1024;function Nl(e,t){let i=De.relative(e,t);return i===""||!De.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${De.sep}`)}function PE(e){let t=De.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})||De.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=ft(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 RE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function AE(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ao(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ih(e){let t=await Ye.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ye.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function _E(e,t){let i=De.resolve(e),r=De.resolve(t);if(!Nl(i,r))throw new Error("Native artifact path is outside its root");let n=[await Ih(i)],a=i;for(let o of De.relative(i,r).split(De.sep).filter(Boolean)){a=De.join(a,o);let s=await Ih(a);if(!Nl(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Th(e){for(let t of e){let i=await Ye.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!AE(t,i)||await Ye.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=PE(e.ref),i=e.maxBytes===null?null:RE(e.maxBytes??dn),r=De.resolve(e.root,...t.split("/")),n=await _E(e.root,De.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Ye.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 Ye.realpath(r);if(!Nl(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ye.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ye.lstat(r),Ye.realpath(r)]);if(await Th(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!ao(a,c)||!ao(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let N=i===null?p.length:i+1-f,k=await s.read(p,0,Math.min(p.length,N),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ye.lstat(r),Ye.realpath(r)]);if(await Th(n),!h.isFile()||h.isSymbolicLink()||m!==o||!ao(c,v)||!ao(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let S=Buffer.concat(d,f),y;try{y=new xE("utf-8",{fatal:!0}).decode(S)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:e.includeHash===!1?null:CE("sha256").update(S).digest("hex"),text:y}}finally{await s.close()}}import{randomUUID as IE}from"crypto";import{promises as le}from"fs";import Xe from"path";function oo(e,t){let i=Xe.relative(e,t);return i===""||!Xe.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Xe.sep}`)}function TE(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function so(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function jE(e,t){return so(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function jh(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Qi(e){for(let t of e){let i=await le.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!TE(t,i)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function $E(e,t,i){let[r,n]=await Promise.all([le.lstat(e),le.realpath(e),i?Qi(i):Promise.resolve()]);if(!r.isFile()||r.isSymbolicLink()||!so(r,t)||i&&!oo(i[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return r}async function OE(e,t){let i=Xe.resolve(e),r=Xe.resolve(t);if(!oo(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await jh(i)],a=Xe.relative(i,r).split(Xe.sep).filter(Boolean),o=i;for(let s of a){await Qi(n),o=Xe.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await jh(o);if(!oo(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Qi(n),n}async function HE(e){let t;try{t=await le.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function DE(e,t,i={}){let r=Xe.dirname(e),n=i.containedRoot?await OE(i.containedRoot,r):null;n||await le.mkdir(r,{recursive:!0});let a=Xe.join(r,`.${Xe.basename(e)}.${IE()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Qi(n),!l.isFile()||l.isSymbolicLink()||!so(s,l)||!oo(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(),!so(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 $E(a,c,n),await i.beforeCommit?.(),n){await Qi(n);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!jE(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await le.link(a,e),await le.unlink(a)):await le.rename(a,e),await HE(r)}catch(l){if(await o?.close(),!n)await le.rm(a,{force:!0});else try{await Qi(n),await le.rm(a,{force:!0})}catch{}throw l}}async function Et(e,t,i={}){await DE(e,t,i)}async function Qe(e,t,i={}){await Et(e,JSON.stringify(t,null,2)+`
145
+ `,i)}var kl=Tr(Ki(),1);import Xt from"path";var fn=64*1024,lo=1024,uo=64,$h=1024,Oh=64,Sl=5,co={learning:!0,retrieval:!0},Lh={provider:"local"},LE=12e4,Hh=6e5,BE=[".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/**"],VE=["**/.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"],FE=[...BE,...VE].sort((e,t)=>e.localeCompare(t,"en"));var Ce={include:["**/*"],exclude:[...FE],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function ME(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||Xt.posix.isAbsolute(i)||Xt.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 Si(e){let t=ME(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Bh(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function fo(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||Xt.posix.isAbsolute(r)||Xt.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 Ct(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Vh(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 po(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>lo)throw new Error(`${t} exceeds ${lo} 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>uo)throw new Error(`${t} contains more than ${uo} wildcard tokens`);return e}function Dh(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=>po(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function bl(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 qE(e){if(e===void 0)return{...Ce,include:[...Ce.include],exclude:[...Ce.exclude]};let t=Ct(e,"native.snapshot");return{include:Dh(t.include,"native.snapshot.include",Ce.include),exclude:Dh(t.exclude,"native.snapshot.exclude",Ce.exclude),max_files:bl(t.max_files,Ce.max_files,"native.snapshot.max_files"),max_total_bytes:bl(t.max_total_bytes,Ce.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:bl(t.max_duration_ms,Ce.max_duration_ms,"native.snapshot.max_duration_ms")}}function WE(e){if(e===void 0)return;let t=Ct(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=Ct(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:Si(r),toArtifactRoot:Si(n),stage:a,...o?{cleanup:o}:{}}}function zE(e){if(e===void 0)return;let t=Ct(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ct(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(Xt.posix.isAbsolute(r[0])||Xt.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??LE;if(!Number.isSafeInteger(n)||n<1||n>Hh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Hh}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function JE(e,t={}){let i=Ct(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??Sl;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=WE(i.pending_root_move),c=zE(i.finish);return{artifact_root:Si(r),language:Vh(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:qE(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function GE(e){let t=Ct(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:Bh(t.artifact_layout),language:Vh(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function UE(e){let i=Ct(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)=>fo(r,`hook.allow_paths[${n}]`)))]}}function KE(e){if(e===void 0)return{...co};let t=Ct(e,"memory"),i=t.learning??co.learning,r=t.retrieval??co.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 El(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function YE(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")||Xt.posix.isAbsolute(i)||Xt.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>$h)throw new Error(`${t} exceeds ${$h} 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>Oh)throw new Error(`${t} contains more than ${Oh} wildcard tokens`);return i}function XE(e){let i=El(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)=>YE(r,`knowledge.local.include[${n}]`)))]}}function QE(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 ZE(e){let t=El(e,"knowledge.remote"),i=QE(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 eC(e){if(e===void 0)return{...Lh};let t=El(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:XE(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:ZE(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 tC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function iC(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 pn(e,t={}){let i=(0,kl.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=tC(n.ambient_resume),o=n.hook===void 0?void 0:UE(n.hook),s=KE(n.memory),c=eC(n.knowledge),l=n.native===void 0?void 0:JE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:GE(n.classic),d=iC(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 ho(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...co},knowledge:{...Lh},native:{artifact_root:Si(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Sl,snapshot:{...Ce,include:[...Ce.include],exclude:[...Ce.exclude]}}}}import{createHash as nC}from"crypto";import{promises as go}from"fs";import Qt from"path";import{constants as mo,promises as Ei}from"fs";var Ze=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Cl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Fh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function hn(e){return{dev:e.dev,ino:e.ino,birthtime:Cl(e)}}function vo(e,t){let i=hn(e),r=hn(t);return _e(i,r)?M(i,r):M(i,r)&&Cl(e)===Cl(t)&&Fh(e)===Fh(t)&&e.size===t.size}async function Ci(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 Ei.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ze("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ze("too-large",`${r} exceeds ${t} bytes`);let o=await Ei.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:hn(a)});let s=process.platform==="win32"?mo.O_RDONLY:mo.O_RDONLY|mo.O_NOFOLLOW|mo.O_NONBLOCK,c;try{c=await Ei.open(e,s)}catch(l){throw l.code==="ELOOP"?new Ze("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!vo(a,l)||!vo(a,u))throw new Ze("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:hn(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:N}=await c.read(v,0,Math.min(v.length,y),null);if(N===0)break;if(p+=N,p>t)throw new Ze("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([c.stat({bigint:n}),Ei.lstat(e,{bigint:n}),Ei.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||S!==o||!vo(a,h)||!vo(a,m))throw new Ze("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:S,identity:hn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:S}}finally{await c.close()}}function rC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function xl(e,t){let i=Qt.relative(e,t);return i===""||!Qt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Qt.sep}`)}async function Mh(e,t){let i=Qt.resolve(e),r=await go.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return go.realpath(i)}async function qh(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=Qt.join(n,i[a]);let o;try{o=await go.lstat(n)}catch(u){if(rC(u))return{exists:!1,kind:"missing"};throw u}let s=Qt.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 go.realpath(n);if(!xl(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 Zi(e,t,i){let r=fo(t,i.label),n=Qt.resolve(e),a=await Mh(n,i.label),o=r.split("/"),s=Qt.resolve(n,...o);if(!xl(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await qh(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function Zt(e,t,i,r){let n=await Zi(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 Mh(n.projectRoot,r.label);return Ci(n.target,i,{...r,verify:async(o,s)=>{if(!xl(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await qh(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var mn=".comet/config.yaml";function aC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function wo(e,t={}){return(await yo(e,t)).document}async function oC(e){try{return(await Zt(e,mn,fn,{label:mn})).bytes}catch(t){if(aC(t))return null;throw t}}function sC(e){return e?{exists:!0,sha256:nC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function yo(e,t={}){let i=await oC(e);return{document:i?pn(i.toString("utf8"),t):null,identity:sC(i)}}async function Pl(e){return(await wo(e))?.config??null}var YO=16*1024;import{existsSync as zh,promises as ei}from"fs";import W from"path";import fC from"os";var No=".comet/config.yaml",pC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function _l(e){try{return await ei.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hC(e){try{let t=await ei.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function tr(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}async function er(e){let t=[],i=e;for(;!await _l(i);){let n=W.dirname(i);if(n===i)break;t.push(W.basename(i)),i=n}let r=await ei.realpath(i);return W.resolve(r,...t.reverse())}async function Il(e){try{return(await ei.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bo(e){let t=W.resolve(e);try{(await ei.stat(t)).isDirectory()||(t=W.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=W.resolve(fC.homedir());for(;;){if(!(t===r&&i!==r)){let o=W.join(t,...No.split("/")),s=t===i||await hC(o);if(await _l(o)&&s)return t}if(await _l(W.join(t,".git")))return t;let a=W.dirname(t);if(a===t)return i;t=a}}function ko(e){return Si(e)}async function mC(e,t){let i=ko(t),r=W.resolve(e,...i.split("/")),n=await ei.realpath(e),a=await er(r);if(!tr(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function xi(e,t){let i=ko(t),r=await mC(e,i),n=W.join(r,"comet");if(await Il(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([er(r),er(n)]);if(!tr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=W.resolve(e),c=W.join(s,".comet","runtime","native");if(await Il(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([ei.realpath(s),er(c)]);if(!tr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:W.join(e,...No.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:W.join(n,"specs"),changesDir:W.join(n,"changes"),archiveDir:W.join(n,"archive"),runtimeDir:c,changesRuntimeDir:W.join(c,"changes"),locksDir:W.join(c,"locks"),transactionsDir:W.join(c,"transactions")}}function Gh(e){if(!pC.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ti(e,t){Gh(t);let i=W.join(e.changesRuntimeDir,t);if(!V(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Uh(e,t){Gh(t);let i=W.join(e.changesDir,t,"runtime");if(!V(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function U(e,t){let i=ti(e,t);if(zh(i))return i;let r=Uh(e,t);return zh(r)?r:i}async function Jh(e){try{let t=await ei.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Tl(e,t){let i=ti(e,t),r=Uh(e,t),[n,a]=await Promise.all([Jh(i),Jh(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 ii(e,t){if(!t.startsWith("runtime/")||W.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=W.resolve(e,...t.slice(8).split("/"));if(!V(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function ue(e,t){let i=W.resolve(t);if(V(e.runtimeDir,i))return e.runtimeDir;if(V(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function V(e,t){return tr(W.resolve(e),W.resolve(t))}async function z(e,t){let i=W.resolve(e),r=W.resolve(t);if(!tr(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await Il(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([er(i),er(r)]);if(!tr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var jl=Ce;var So=po;function gC(e="docs",t="en"){return ho(e,t)}async function Ie(e){let t=(await wo(e))?.config??null;return t?.native?t:null}async function Eo(e){let t=await Ie(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 Kh(e){let t=await bo(e.startPath),i=await Ie(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${No} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let r=e.explicitArtifactRoot?ko(e.explicitArtifactRoot):void 0;if(i&&r&&r!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${r}`);let n=i??gC(r??"docs"),a=await xi(t,n.native.artifact_root);return{config:n,paths:a,configured:i!==null}}import{promises as Yx}from"fs";import Xx from"path";import{AsyncLocalStorage as wC}from"async_hooks";import{randomUUID as Qh}from"crypto";import{promises as Le}from"fs";import Zh from"os";import ye from"path";var Yh=16*1024,em=".coordinator",yC=5e3,Xh=new wC,Co=new Map;function NC(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function bC(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 tm(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 xo(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return _e(i,r)?M(i,r):M(i,r)&&e.size===t.size}function $l(e,t){return xo(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function pt(e){let t,i;try{let r=await Ci(e,Yh,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Ze?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${Yh} 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:bC(JSON.parse(t.toString("utf8")),e),identity:tm(i)}}async function kC(e){return(await pt(e))?.owner??null}function im(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Zh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=RC(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function SC(e,t){try{await Le.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Le.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Ol(e,t){let i=await pt(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!$l(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Le.mkdir(t,{recursive:!0});let r=ye.join(t,`${ye.basename(e.file)}.${e.owner.id}.${Qh()}.removed`);try{await Le.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await pt(r);if(!n||n.owner.id!==e.owner.id||!xo(n.identity,e.identity))throw await SC(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Le.rm(r,{force:!0}),"removed"}function rm(e){return{id:Qh(),pid:process.pid,hostname:Zh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function nm(e,t){let i;try{i=await Le.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await kC(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)+`
146
+ `,"utf8"),await i.sync(),r=tm(await i.stat({bigint:!0}))}finally{await i.close()}let n=await pt(e);if(!r||!n||n.owner.id!==t.id||!xo(n.identity,r))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function EC(e,t){let i=await z(e.runtimeDir,e.locksDir);await Le.mkdir(i,{recursive:!0});let r=await z(e.runtimeDir,ye.join(i,em));await Le.mkdir(r,{recursive:!0});let n=rm(t),a=ye.join(r,`.${n.id}.tmp`),o=ye.join(r,`${n.id}.claim`);try{let s=await nm(a,n);await Le.rename(a,o);let c=await pt(o);if(!c||!xo(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 Le.rm(a,{force:!0})}}async function CC(e){let t=ye.dirname(e.file),i=!1,r=ye.basename(e.file);for(let n of await Le.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ye.join(t,n.name);if(ye.resolve(a)!==ye.resolve(e.file))try{let o=await pt(a),s=im(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ol(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function am(e){let t=await pt(e.file);if(t){if(t.owner.id!==e.owner.id||!$l(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Ol(t,ye.dirname(e.file))}}async function xC(e,t){let i=Date.now()+yC;for(;;){let r=await EC(e,t);if(!await CC(r))return r;if(await am(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 PC(e){let t=Co.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return Co.set(e,n),await t,()=>{i(),Co.get(e)===n&&Co.delete(e)}}async function om(e,t,i){let r=ye.resolve(e.locksDir),n=Xh.getStore();if(n?.has(r))return i();let a=await PC(r);try{let o=await xC(e,t),s=new Map(n??[]);return s.set(r,o),await Xh.run(s,async()=>{try{return await i()}finally{await am(o)}})}finally{a()}}async function Po(e,t,i){return om(e,`acquire ${t}`,async()=>{let r=await z(e.runtimeDir,e.locksDir);await Le.mkdir(r,{recursive:!0});let n=await z(e.runtimeDir,ye.join(r,NC(t))),a=rm(i),o=await nm(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function Ro(e){await pt(e.file)&&await om({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ye.basename(e.file)}`,async()=>{let t=await pt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!$l(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ye.join(e.locksDir,em);await Ol(t,i)})}function RC(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function sm(e){return im(await pt(e))}import Ex from"node:path";import cm from"node:path";import{createHash as AC}from"crypto";function et(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function _C(e,t){t.has(e)&&et("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)||et("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&et("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),`[${e.map(r=>Hl(r,t)).join(",")}]`}finally{t.delete(e)}}function IC(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&et("only plain objects are supported"),t.has(e)&&et("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&et("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))&&et("accessor properties are not supported"),`${JSON.stringify(o)}:${Hl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Hl(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)||et("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?_C(e,t):IC(e,t);case"bigint":case"function":case"symbol":case"undefined":return et(`${typeof e} values are not supported`)}return et("unsupported value type")}function gn(e){return Hl(e,new Set)}function L(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return AC("sha256").update(`${e}
147
+ ${gn(t)}`).digest("hex")}var TC="comet.native.acceptance.v1",jC=/^acceptance-[a-f0-9]{64}$/u,$C=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),OC=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,HC=/^[a-f0-9]{64}$/u,DC=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function LC(e,t){return e<t?-1:e>t?1:0}var xt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),wn=Object.freeze({maxCriteria:1024}),lm="<!-- comet-native:acceptance-evidence:start -->",um="<!-- comet-native:acceptance-evidence:end -->";function dm(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 fm(e,t){let i=t.toString(36),r=L("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function BC(e){if(!HC.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=DC.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==L("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function VC(e,t){let i=dm(e.text,xt.maxTextBytes),r=e.context.slice(0,xt.maxContextItems).map(n=>dm(n,xt.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 hm(e){let t=BC({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(LC),n=r.slice(0,xt.maxFailedCheckIds),a=e.criteria.slice(t,t+xt.maxItems);for(let c of a){let l=[...i,VC(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?fm(e.acceptanceHash,u):null,limits:{...xt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>xt.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?fm(e.acceptanceHash,o):null,limits:{...xt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>xt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Ll(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 Dl(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 pm(e){return e.includes("-->")||e.includes("--!>")}function*ir(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
148
148
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
149
- `,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=Ol(l,t);else if(i)cm(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Ol(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!cm(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function kC(e){return[...Qi(e)].map(({line:t,body:i})=>({line:t,body:i}))}function ko(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function SC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Dl(e,t,i,r=[],n="content-hash"){let a=ko(i),o=t.replaceAll("\\","/").trim(),s=r.map(ko);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${B(pC,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Bl(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 EC(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Qi(e)){n=s+1;let c=o?Hl(a):null;c?.level===1&&(ta(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 Ll(e,t="brief.md",i=mn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=EC(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Qi(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Qi(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(),Bl(o.map(l=>Dl("brief-example",t,l.join(`
150
- `),[],r)),"Brief",r)}function Vl(e,t="spec.md",i=mn.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(Dl("spec-scenario",t,[o.title,...o.body].join(`
151
- `),o.context,r)),o=null}};for(let{line:c,body:l}of Qi(e)){let u=l?Hl(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=ko(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Bl(n,"Specification",r)}function um(e,t="spec.md",i=mn.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(Dl("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 Qi(e)){let f=d?Hl(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Ol(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Bl(n,"Specification mandatory requirements",r)}function CC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||SC(i)||rm.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=rm.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(!vC.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function PC(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=>!mC.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function dm(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=PC(i,r),a=n.acceptance_id;if(typeof a!="string"||!hC.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 CC(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 fm(e){let t=kC(e);if(t.some(({line:l,body:u})=>!u&&(l===nm||l===am)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===nm?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===am?[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(`
152
- `).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=dm(o),c=xC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function xC(e){let t=dm([...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 Ml=Rr(Ji(),1);import{promises as AC}from"node:fs";var vn="comet.native.v4",So="comet.native.local-execution.v4";var pm=["multi-session","single-session"];var _C=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TC=/^A[1-9][0-9]*$/u,jC=/^[a-f0-9]{64}$/u,$C=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"]);function ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function le(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function Fl(e,t){return e===null?null:le(e,t)}function OC(e,t){let i=le(e,t);if(!jC.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Zi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function te(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 HC(e,t){return e===null?null:te(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 ft(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Eo(e,t){return ft(e,t,(i,r)=>le(i,`${t}[${r}]`))}function Ci(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function er(e,t){let i=le(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function ql(e,t,i=!1){let r=le(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function Be(e,t){let i=ye(e,t);return Ne(i,new Set(["text","truncated"]),t),{text:le(i.text,`${t}.text`,{empty:!0}),truncated:Zi(i.truncated,`${t}.truncated`)}}function DC(e,t){let i=`Native spec_changes[${t}]`,r=ye(e,i);Ne(r,new Set(["capability","operation","source"]),i);let n=le(r.capability,`${i}.capability`);if(!IC.test(n))throw new Error(`${i}.capability is invalid`);let a=se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:ql(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 BC(e){let t="Native workspace",i=ye(e,t);Ne(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=Fl(i.change_branch,`${t}.change_branch`),a=Fl(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 LC(e){let t="Native loop",i=ye(e,t);Ne(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=Eo(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return Ci(r,`${t}.previous_unresolved_ids`),{stage:se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:te(i.goal_cycle,`${t}.goal_cycle`,1),iteration:te(i.iteration,`${t}.iteration`),attempt:te(i.attempt,`${t}.attempt`),retry_epoch:te(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:te(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:te(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:te(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:Fl(i.next_action,`${t}.next_action`)}}function VC(e,t){let i=`Native acceptance[${t}]`,r=ye(e,i);Ne(r,new Set(["id","source","text","result","reason"]),i);let n=le(r.id,`${i}.id`);if(!TC.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:ql(r.source,`${i}.source`),text:le(r.text,`${i}.text`),result:se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Be(r.reason,`${i}.reason`)}}function FC(e,t){let i=`Native builder_handoff.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["name","result","note"]),i),{name:Be(r.name,`${i}.name`),result:se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Be(r.note,`${i}.note`)}}function MC(e){let t="Native builder_handoff",i=ye(e,t);Ne(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=Eo(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ci(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:ye(i.review,`${t}.review`);return n&&Ne(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:le(i.candidate_id,`${t}.candidate_id`),identity_provider:le(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:le(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),summary:Be(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ft(i.checks,`${t}.checks`,FC),checks_truncated:Zi(i.checks_truncated,`${t}.checks_truncated`),known_limits:ft(i.known_limits,`${t}.known_limits`,(a,o)=>Be(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Zi(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:se(n.status,["passed"],`${t}.review.status`),summary:Be(n.summary,`${t}.review.summary`),reviewer_execution_ref:le(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:er(i.submitted_at,`${t}.submitted_at`)}}function qC(e,t){let i=`Native blockers[${t}]`,r=ye(e,i);Ne(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Eo(r.acceptance_ids,`${i}.acceptance_ids`);return Ci(n,`${i}.acceptance_ids`),{owner:se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Be(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 WC(e,t){let i=`Native verification.checks[${t}]`,r=ye(e,i);return Ne(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:le(r.id,`${i}.id`),name:Be(r.name,`${i}.name`),argv_display:ft(r.argv_display,`${i}.argv_display`,(n,a)=>Be(n,`${i}.argv_display[${a}]`)),argv_truncated:Zi(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:ql(r.cwd_ref,`${i}.cwd_ref`,!0),status:se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:HC(r.exit_code,`${i}.exit_code`),duration_ms:te(r.duration_ms,`${i}.duration_ms`)}}function zC(e){let t="Native verification",i=ye(e,t);Ne(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ft(i.checks,`${t}.checks`,WC);Ci(r.map(a=>a.id),`${t}.checks IDs`);let n=le(i.identity_provider,`${t}.identity_provider`);return{candidate_id:le(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:le(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:te(i.iteration,`${t}.iteration`,1),attempt:te(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:Be(i.summary,`${t}.summary`),risks:ft(i.risks,`${t}.risks`,(a,o)=>Be(a,`${t}.risks[${o}]`)),risks_truncated:Zi(i.risks_truncated,`${t}.risks_truncated`),completed_at:er(i.completed_at,`${t}.completed_at`)}}function JC(e,t){let i=`Native history[${t}]`,r=ye(e,i);Ne(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Eo(r.unresolved_ids,`${i}.unresolved_ids`);return Ci(n,`${i}.unresolved_ids`),{goal_cycle:te(r.goal_cycle,`${i}.goal_cycle`,1),iteration:te(r.iteration,`${i}.iteration`),attempt:te(r.attempt,`${i}.attempt`),outcome:se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Be(r.summary,`${i}.summary`),completed_at:er(r.completed_at,`${i}.completed_at`)}}function GC(e){let t="Native history_overflow.outcome_counts",i=ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Ne(i,new Set(r),t),{pass:te(i.pass,`${t}.pass`),fail:te(i.fail,`${t}.fail`),blocked:te(i.blocked,`${t}.blocked`),"execution-error":te(i["execution-error"],`${t}.execution-error`),recovery:te(i.recovery,`${t}.recovery`)}}function UC(e){let t="Native history_overflow",i=ye(e,t);Ne(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=te(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:er(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:er(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=GC(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 KC(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 YC(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 gn(e){let t=ye(e,"Native portable state");if(Ne(t,$C,"Native portable state"),t.schema!==vn)throw new Error(`Native portable state schema must be ${vn}`);let i=le(t.name,"Native state name");if(!_C.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=ft(t.spec_changes,"Native spec_changes",DC);Ci(r.map(s=>s.capability),"Native spec change capabilities");let n=ft(t.acceptance,"Native acceptance",VC);Ci(n.map(s=>s.id),"Native acceptance IDs");let a=ft(t.history,"Native history",JC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:vn,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:te(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:OC(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:BC(t.workspace),loop:LC(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:MC(t.builder_handoff),blockers:ft(t.blockers,"Native blockers",qC),verification:t.verification===null?null:zC(t.verification),history:a,history_overflow:UC(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:Zi(t.archived,"Native archived"),created_at:er(t.created_at,"Native created_at")};return KC(o),YC(o),o}function XC(e,t){let i=(0,Ml.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 wn(e){let t=await AC.readFile(e,"utf8");return gn(XC(t,"Native portable state"))}var Pt="comet.native.v3",xt="comet.native.v2",Rt="comet.native.v1",tr="comet.native.transition.v3",ir="comet.native.transition.v2",yn="comet.native.transition.v1";var mm="comet.native.portable-migration.v1",QC=new Set(["schema","id","change","fromSchema","status","createdAt"]),ZC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eP=/^[a-z0-9][a-z0-9-]{7,127}$/u,tP=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),iP=new Set([Rt,xt,Pt]);function rP(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nP(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 gm(e){let t=rP(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!QC.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==mm)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!eP.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!ZC.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!iP.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!tP.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:mm,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:nP(t.createdAt,"Native portable migration transaction createdAt")}}var wm="comet.native.archive-transaction.v4",ym="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",oP=new RegExp(`^portable-archive-(${ym})\\.json$`,"u"),sP=new RegExp(`^portable-migration-(${ym})\\.json$`,"u"),cP=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,lP=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uP=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),dP=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),fP=new Set(["capability","operation","source","content"]),Nm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function bm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function km(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 pP(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=bm(e,i);if(km(r,fP,i),typeof r.capability!="string"||!Nm.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 hP(e){let t=bm(e,"Native portable Archive transaction");if(km(t,dP,"Native portable Archive transaction"),t.schema!==wm)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!cP.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Nm.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"||!lP.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"||!uP.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(pP);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:wm,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 Wl(e){let t=oP.exec(e);if(t)return{kind:"archive",change:t[1]};let i=sP.exec(e);return i?{kind:"migration",change:i[1]}:null}async function Sm(e,t){let i=Wl(t);if(!i)return null;let r=await ie({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=aP.join(e.transactionsDir,t);if(i.kind==="archive"){let s=hP(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=gm(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}function Em(e){return e.kind==="archive"||e.journal.status!=="committed"}import _t from"path";import{TextDecoder as bP}from"util";import{createHash as mP}from"node:crypto";import{constants as Co,promises as Ie}from"node:fs";import et from"node:path";import{TextDecoder as vP}from"node:util";function xo(e,t){let i=et.relative(e,t);return i===""||!et.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${et.sep}`)}function Cm(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function gP(e,t){return F({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Po(e,t){return F({...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 zl(e,t){let i=await Ie.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ie.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Pm(e,t,i){let r=et.resolve(e),n=et.resolve(t);if(!xo(r,n))throw new Error(`${i} is outside its managed root`);let a=[await zl(r,i)],o=r;for(let s of et.relative(r,n).split(et.sep).filter(Boolean)){await At(a,i),o=et.join(o,s);let c=await zl(o,i);if(!xo(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await At(a,i),a}async function At(e,t){for(let i of e){let r=await Ie.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!gP(i,r)||await Ie.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function yP(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 pt(e){let t=Cm(e.maxBytes),i=et.resolve(e.file),r=await Pm(e.root,et.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>zl(et.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await At(r,e.label);let a=await Ie.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=wP(a),s=await Ie.realpath(i);if(!xo(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>xo(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Co.O_RDONLY:Co.O_RDONLY|Co.O_NOFOLLOW|Co.O_NONBLOCK,l=await Ie.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ie.lstat(i),Ie.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Po(o,u)||!Po(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await yP(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Ie.lstat(i),Ie.realpath(i)]);if(await At(r,e.label),await At(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Po(o,v)||!Po(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:mP("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function xm(e){let t=await pt(e),i;try{i=new vP("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 Nn(e){let t=await Pm(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Ie.readdir(e.directory,{withFileTypes:!0});else{let r=Cm(e.maxEntries);i=[];let n=await Ie.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 At(t,e.label),{entries:i,verify:()=>At(t,e.label)}}var kP=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),SP=new Set(["id","type","source","target","staged","backup"]),EP=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),CP=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var _m=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var PP=256*1024,B0=1024*1024,L0=16*1024;var V0=64*1024*1024;var xP=new bP("utf-8",{fatal:!0});function Ao(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _o(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Im(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Jl(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 Ro(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Rm(e,t){if(Jl(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 RP(e,t){let i=Ao(e,`transaction operations[${t}]`);if(_o(i,SP,`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`);Jl(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Jl(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 Tm(e){let t=Ao(e,"Native Archive transaction journal");if(_o(t,EP,"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"||!_m.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(!Im(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ro(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Ao(s,`Archive transaction operations[${c}]`);if(_o(l,CP,`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`);Rm(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Rm(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ro(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(Ro(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`);Ro(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 AP(e){let t=Ao(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Tm(t);if(_o(t,kP,"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"||!_m.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(!Im(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(RP),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 _P(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 jm(e,t){let i=_P(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 Gl(e,t){let i=jm(e,t);return await Promise.all(Object.values(i).map(r=>W(e.runtimeDir,r))),i}async function Ul(e,t,i={}){let r=await Gl(e,t),n=await pt({root:e.runtimeDir,file:r.journal,maxBytes:PP,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(xP.decode(n.bytes)),o=AP(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function jP(e,t,i){let r;try{r=await IP.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 Ul(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(Wl(n.name))try{let a=await Sm(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Em(a))return!0}catch{return!0}return!1}async function $P(e,t){let i=Date.now()+5e3,r=TP.join(e.locksDir,"root-move.lock");for(;;)try{return await No(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await im(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 tt(e,t,i,r){let n=await $P(e,t);try{if(await wo(e.projectRoot),await jP(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await bo(n)}}import{createHash as Oo}from"crypto";import{spawn as qm}from"node:child_process";import{promises as Y}from"fs";import H from"path";import{createHash as $m}from"crypto";import{createReadStream as OP}from"fs";async function Kl(e){let t=$m("sha256");for await(let i of OP(e))t.update(i);return t.digest("hex")}function U(e){return $m("sha256").update(e).digest("hex")}var Io={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},tu=1e3,HP=8*1024*1024,DP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),LP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),VP=new Set(["schema","include","exclude","hash"]),FP=new Set(["provider","gitSelection","physicalSelection","projection"]),MP=new Set(["provider","selection"]),qP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),WP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),zP=new Set(["schema","status","before","after"]),JP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),GP=new Set(["path","hash","size","type","gitObjectId"]),UP=new Set(["path","size","type","reason"]),KP=new Set(["ref","hash","count"]),YP=new Set(["change-created","legacy-migration","explicit"]),XP=new Set(["file","directory","other"]),QP=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"]),Ho=/^[a-f0-9]{64}$/u,Wm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ZP=new Set(["EACCES","EPERM"]),lr=64*1024,Zl=64*1024,ex=6e4,tx=1e3,ix=2,iu={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},rx={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function zm(e){let t=e.deadlineMs??ex;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 it(e){return Math.max(0,e.deadlineAt-Date.now())}function j(e){return it(e)>=1}function Yl(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 sr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function nx(e){let t={...rx,...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 ax(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&&H.win32.isAbsolute(r)?H.win32.resolve(r):"C:\\Windows",a=H.win32.join(n,"System32","taskkill.exe");if(!H.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=qm(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),tx),u.unref()}catch{d(!1)}});for(let s=0;s<ix;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 ru(e,t,i,r){let n=it(e);if(n<1)throw Yl();let a=e.gitProcess,o=qm(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",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=ax(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Yl(v.error):Yl()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Jm(e){let t={...iu,...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 To(e,t,i,r=Zl){let{child:n,completion:a}=ru(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=lr)return;let v=lr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Xl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function kn(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}=ru(e,t,i,r.stdin!==void 0),c=[],l=Oo("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,N=k=>{let E=0;for(;E<k.byteLength;){let b=k.indexOf(0,E),P=b<0?k.byteLength:b,g=k.subarray(E,P);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){N(k);return}for(let b=0;b<k.byteLength;b+=E)N(k.subarray(b,Math.min(k.byteLength,b+E)))}),o.stderr.on("data",k=>{if(d>=lr)return;let E=lr-d,b=Buffer.from(k).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(k!==null&&b.includes(k)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function jo(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 ox(e,t,i){if(i.length===0)return new Set;let r=await kn(e,t,["check-ignore","--no-index","-z","--stdin"],{...iu,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=jo(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function sx(e,t,i){let{child:r,completion:n}=ru(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>=lr)return;let d=lr-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 cr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||H.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||H.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function cx(e,t){return e.map(i=>{let r=cr(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function lx(e){let t=H.resolve(e);for(;;){try{return await Y.lstat(H.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=H.dirname(t);if(i===t)return!1;t=i}}async function Gm(e,t,i,r={}){let n=H.resolve(t.projectRoot),a=H.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=H.relative(n,H.resolve(f)).replaceAll("\\","/"),v=cr(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await kn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await kn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await kn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Um(e){return{stageBefore:Xl(e.stagedBefore),combined:Xl(e.combined),stageAfter:Xl(e.stagedAfter)}}async function Km(e,t,i=iu,r={}){let n=H.resolve(t.projectRoot);if(!await lx(n))return null;let a;try{a=await To(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw sr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Gm(e,t,i,r)}catch(y){throw sr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let N of y){let k=jo(N),E=k.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let P=cr(k.slice(E+1));if(P===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(P),b.stage==="0"&&d.set(P,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(P)}};p(s.records),p(l.records);let v=c.records.map(jo),h=cx(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,N)=>!u.has(y)&&v[N].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:Um(o)}}function ri(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Om(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function ux(e,t){return!ri(e.stageBefore,e.stageAfter)||!ri(e.stageAfter,t.stageBefore)||!ri(e.combined,t.combined)||!ri(t.stageBefore,t.stageAfter)}async function Ym(e,t,i,r,n){let a;try{a=await Gm(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw sr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=Um(a),c=Om(o)||Om(s),l=ux(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:U(`comet.native.git-selection-overflow.v2
153
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var dx=(1n<<256n)-1n;function fx(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Hm(e){let t=H.resolve(e.paths.projectRoot),i=H.resolve(e.paths.nativeRoot),r=H.resolve(e.paths.runtimeDir),n=H.resolve(e.paths.configFile),a=H.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>it(e.execution)>=1?!0:(p=!0,h=!0,!1),S=k=>{let E=Buffer.from(`${k.type}\0${k.path}`,"utf8"),b=Oo("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let P=0;P<c.length;P+=1)c[P]^=b[P];if(l=l+BigInt(`0x${b.toString("hex")}`)&dx,d+=1,f+=E.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(k)},y=async k=>{if(h||!m())return;let E;try{E=await Y.opendir(k)}catch(C){if(!m())return;if(!ae(C)&&!ne(C)||k===t&&ae(C))throw C;v||=ne(C),p||=ae(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let b=!1,P;try{for(;!h&&m();){let C;try{C=await E.read()}catch(J){if(!m())break;if(!ae(J)&&!ne(J)||k===t&&ae(J))throw J;v||=ne(J),p||=ae(J),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let $=H.join(k,C.name),T=hx(t,$);if($===n||$===a||rt(i,$)||rt(r,$)||e.denylist.some(J=>rt(J,$))||dt(T)!==null)continue;if(!m())break;let de;try{de=await Y.lstat($)}catch(J){if(!m())break;if(!ae(J)&&!ne(J))throw J;if(v=!0,S({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:ae(J)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;let X=fx(de);if(X==="directory"){if(wx(e.policy,T))continue;if(!m())break;let J;try{J=await Y.realpath($)}catch(ct){if(!m())break;if(!ae(ct)&&!ne(ct))throw ct;if(v=!0,S({path:T,type:X}),s.push({path:T,size:null,type:"directory",reason:ae(ct)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;if(!L(e.physicalProjectRoot,J)||rt(e.physicalNativeRoot,J))continue;if(S({path:T,type:X}),await e.hooks?.afterNode?.(T),!m()||(await y($),h))break;continue}if(S({path:T,type:X}),await e.hooks?.afterNode?.(T),!m()||h)break}}catch(C){b=!0,P=C}let g;try{await E.close()}catch(C){g=C}let w=m();if(b)throw P;if(w&&g!==void 0&&g.code!=="ERR_DIR_CLOSED")throw g};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((k,E)=>k.path.localeCompare(E.path,"en")),s.sort((k,E)=>k.path.localeCompare(E.path,"en")));let N=p?U(`comet.native.physical-selection-incomplete.v1
154
- ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):U(`comet.native.physical-selection.v1
155
- ${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:N,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function Xm(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 px(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!Xm(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 Qm(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Dm(e,t){let r=(await To(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Wm.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return U(`gitlink:${r}`)}async function Bm(e,t){let i=await Dm(e,t),r=await sx(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Dm(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function bn(e,t){if(dt(t)!==null)return!1;let i=H.resolve(e.projectRoot,...t.split("/"));return!rt(H.resolve(e.nativeRoot),i)&&!rt(H.resolve(e.runtimeDir),i)}function hx(e,t){return H.relative(e,t).split(H.sep).join("/")}function mx(e,t){return t.map(i=>H.resolve(e,...i.split(/[\\/]/u)))}function rt(e,t){let i=H.resolve(e),r=H.resolve(t);return r===i||L(i,r)}function ae(e){return ZP.has(e.code??"")}function ne(e){return e.code==="ENOENT"}function nu(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
156
- `)}function vx(e,t){return U(`comet.native.snapshot-policy.v1
157
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Ql(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 gx(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Lm(e){let t=go(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?gx(n):void 0;if(a&&!a())return!1;let o=Ql(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=Ql(i,c,a),o===null||o.size===0)return!1}return Ql(i,o,a)?.has(i.length)??!1}}function Zm(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>go(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>go(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=vx(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(Lm),excludeMatchers:i.map(Lm),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 wx(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Vm(e,t,i){if(!e)return!0;let r=()=>j(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 Sn(e,t,i){let r=JSON.stringify(i);return U(`${e}
149
+ `,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=Dl(l,t);else if(i)pm(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=Dl(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!pm(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(r=p[1])}}}if(c===-1)break;o=c+1}}function FC(e){return[...ir(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Ao(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function MC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Bl(e,t,i,r=[],n="content-hash"){let a=Ao(i),o=t.replaceAll("\\","/").trim(),s=r.map(Ao);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${L(TC,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Vl(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 qC(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of ir(e)){n=s+1;let c=o?Ll(a):null;c?.level===1&&(aa(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 Fl(e,t="brief.md",i=wn.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=qC(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ir(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of ir(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(),Vl(o.map(l=>Bl("brief-example",t,l.join(`
150
+ `),[],r)),"Brief",r)}function Ml(e,t="spec.md",i=wn.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(Bl("spec-scenario",t,[o.title,...o.body].join(`
151
+ `),o.context,r)),o=null}};for(let{line:c,body:l}of ir(e)){let u=l?Ll(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=Ao(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Vl(n,"Specification",r)}function mm(e,t="spec.md",i=wn.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(Bl("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 ir(e)){let f=d?Ll(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Dl(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Vl(n,"Specification mandatory requirements",r)}function WC(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||MC(i)||cm.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=cm.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(!OC.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function zC(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=>!$C.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function vm(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=zC(i,r),a=n.acceptance_id;if(typeof a!="string"||!jC.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 WC(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 gm(e){let t=FC(e);if(t.some(({line:l,body:u})=>!u&&(l===lm||l===um)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===lm?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===um?[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(`
152
+ `).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=vm(o),c=JC(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function JC(e){let t=vm([...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 Wl=Tr(Ki(),1);import{promises as UC}from"node:fs";var yn="comet.native.v4",_o="comet.native.local-execution.v4";var wm=["multi-session","single-session"];var KC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XC=/^A[1-9][0-9]*$/u,QC=/^[a-f0-9]{64}$/u,ZC=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"]);function Ne(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function be(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 de(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 ql(e,t){return e===null?null:de(e,t)}function ex(e,t){let i=de(e,t);if(!QC.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function rr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ie(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 tx(e,t){return e===null?null:ie(e,t,Number.MIN_SAFE_INTEGER)}function ae(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ht(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function Io(e,t){return ht(e,t,(i,r)=>de(i,`${t}[${r}]`))}function Pi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function nr(e,t){let i=de(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function zl(e,t,i=!1){let r=de(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 Be(e,t){let i=Ne(e,t);return be(i,new Set(["text","truncated"]),t),{text:de(i.text,`${t}.text`,{empty:!0}),truncated:rr(i.truncated,`${t}.truncated`)}}function ix(e,t){let i=`Native spec_changes[${t}]`,r=Ne(e,i);be(r,new Set(["capability","operation","source"]),i);let n=de(r.capability,`${i}.capability`);if(!YC.test(n))throw new Error(`${i}.capability is invalid`);let a=ae(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:zl(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 rx(e){let t="Native workspace",i=Ne(e,t);be(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=ae(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=ql(i.change_branch,`${t}.change_branch`),a=ql(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:ae(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 nx(e){let t="Native loop",i=Ne(e,t);be(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=Io(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Pi(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:ae(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ae(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ie(i.goal_cycle,`${t}.goal_cycle`,1),iteration:ie(i.iteration,`${t}.iteration`),attempt:ie(i.attempt,`${t}.attempt`),retry_epoch:ie(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ie(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ie(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ie(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:ql(i.next_action,`${t}.next_action`)}}function ax(e,t){let i=`Native acceptance[${t}]`,r=Ne(e,i);be(r,new Set(["id","source","text","result","reason"]),i);let n=de(r.id,`${i}.id`);if(!XC.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:zl(r.source,`${i}.source`),text:de(r.text,`${i}.text`),result:ae(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:Be(r.reason,`${i}.reason`)}}function ox(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["name","result","note"]),i),{name:Be(r.name,`${i}.name`),result:ae(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:Be(r.note,`${i}.note`)}}function sx(e){let t="Native builder_handoff",i=Ne(e,t);be(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=Io(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Pi(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Ne(i.review,`${t}.review`);return n&&be(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:de(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:de(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),summary:Be(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ht(i.checks,`${t}.checks`,ox),checks_truncated:rr(i.checks_truncated,`${t}.checks_truncated`),known_limits:ht(i.known_limits,`${t}.known_limits`,(a,o)=>Be(a,`${t}.known_limits[${o}]`)),known_limits_truncated:rr(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ae(n.status,["passed"],`${t}.review.status`),summary:Be(n.summary,`${t}.review.summary`),reviewer_execution_ref:de(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:nr(i.submitted_at,`${t}.submitted_at`)}}function cx(e,t){let i=`Native blockers[${t}]`,r=Ne(e,i);be(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=Io(r.acceptance_ids,`${i}.acceptance_ids`);return Pi(n,`${i}.acceptance_ids`),{owner:ae(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:Be(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:ae(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function lx(e,t){let i=`Native verification.checks[${t}]`,r=Ne(e,i);return be(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:de(r.id,`${i}.id`),name:Be(r.name,`${i}.name`),argv_display:ht(r.argv_display,`${i}.argv_display`,(n,a)=>Be(n,`${i}.argv_display[${a}]`)),argv_truncated:rr(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:zl(r.cwd_ref,`${i}.cwd_ref`,!0),status:ae(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:tx(r.exit_code,`${i}.exit_code`),duration_ms:ie(r.duration_ms,`${i}.duration_ms`)}}function ux(e){let t="Native verification",i=Ne(e,t);be(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ht(i.checks,`${t}.checks`,lx);Pi(r.map(a=>a.id),`${t}.checks IDs`);let n=de(i.identity_provider,`${t}.identity_provider`);return{candidate_id:de(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:de(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ie(i.iteration,`${t}.iteration`,1),attempt:ie(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ae(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ae(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:Be(i.summary,`${t}.summary`),risks:ht(i.risks,`${t}.risks`,(a,o)=>Be(a,`${t}.risks[${o}]`)),risks_truncated:rr(i.risks_truncated,`${t}.risks_truncated`),completed_at:nr(i.completed_at,`${t}.completed_at`)}}function dx(e,t){let i=`Native history[${t}]`,r=Ne(e,i);be(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=Io(r.unresolved_ids,`${i}.unresolved_ids`);return Pi(n,`${i}.unresolved_ids`),{goal_cycle:ie(r.goal_cycle,`${i}.goal_cycle`,1),iteration:ie(r.iteration,`${i}.iteration`),attempt:ie(r.attempt,`${i}.attempt`),outcome:ae(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:Be(r.summary,`${i}.summary`),completed_at:nr(r.completed_at,`${i}.completed_at`)}}function fx(e){let t="Native history_overflow.outcome_counts",i=Ne(e,t),r=["pass","fail","blocked","execution-error","recovery"];return be(i,new Set(r),t),{pass:ie(i.pass,`${t}.pass`),fail:ie(i.fail,`${t}.fail`),blocked:ie(i.blocked,`${t}.blocked`),"execution-error":ie(i["execution-error"],`${t}.execution-error`),recovery:ie(i.recovery,`${t}.recovery`)}}function px(e){let t="Native history_overflow",i=Ne(e,t);be(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=ie(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:nr(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:nr(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=fx(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 hx(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 mx(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 Nn(e){let t=Ne(e,"Native portable state");if(be(t,ZC,"Native portable state"),t.schema!==yn)throw new Error(`Native portable state schema must be ${yn}`);let i=de(t.name,"Native state name");if(!KC.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=ht(t.spec_changes,"Native spec_changes",ix);Pi(r.map(s=>s.capability),"Native spec change capabilities");let n=ht(t.acceptance,"Native acceptance",ax);Pi(n.map(s=>s.id),"Native acceptance IDs");let a=ht(t.history,"Native history",dx);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:yn,name:i,language:ae(t.language,["en","zh-CN"],"Native state language"),phase:ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ie(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:ex(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:rx(t.workspace),loop:nx(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:sx(t.builder_handoff),blockers:ht(t.blockers,"Native blockers",cx),verification:t.verification===null?null:ux(t.verification),history:a,history_overflow:px(t.history_overflow),verification_result:ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ae(t.verification_report,["verification.md"],"Native verification_report"),archived:rr(t.archived,"Native archived"),created_at:nr(t.created_at,"Native created_at")};return hx(o),mx(o),o}function vx(e,t){let i=(0,Wl.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 bn(e){let t=await UC.readFile(e,"utf8");return Nn(vx(t,"Native portable state"))}var Pt="comet.native.v3",Rt="comet.native.v2",At="comet.native.v1",ar="comet.native.transition.v3",or="comet.native.transition.v2",kn="comet.native.transition.v1";var Nm="comet.native.portable-migration.v1",gx=new Set(["schema","id","change","fromSchema","status","createdAt"]),wx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yx=/^[a-z0-9][a-z0-9-]{7,127}$/u,Nx=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),bx=new Set([At,Rt,Pt]);function kx(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sx(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 km(e){let t=kx(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!gx.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==Nm)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!yx.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!wx.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!bx.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Nx.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Nm,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Sx(t.createdAt,"Native portable migration transaction createdAt")}}var Sm="comet.native.archive-transaction.v4",Em="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Cx=new RegExp(`^portable-archive-(${Em})\\.json$`,"u"),xx=new RegExp(`^portable-migration-(${Em})\\.json$`,"u"),Px=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Rx=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ax=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),_x=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Ix=new Set(["capability","operation","source","content"]),Cm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function xm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Pm(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 Tx(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=xm(e,i);if(Pm(r,Ix,i),typeof r.capability!="string"||!Cm.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 jx(e){let t=xm(e,"Native portable Archive transaction");if(Pm(t,_x,"Native portable Archive transaction"),t.schema!==Sm)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!Px.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Cm.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"||!Rx.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"||!Ax.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(Tx);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:Sm,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 Jl(e){let t=Cx.exec(e);if(t)return{kind:"archive",change:t[1]};let i=xx.exec(e);return i?{kind:"migration",change:i[1]}:null}async function Rm(e,t){let i=Jl(t);if(!i)return null;let r=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Ex.join(e.transactionsDir,t);if(i.kind==="archive"){let s=jx(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=km(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}function Am(e){return e.kind==="archive"||e.journal.status!=="committed"}import It from"path";import{TextDecoder as Vx}from"util";import{createHash as $x}from"node:crypto";import{constants as To,promises as Te}from"node:fs";import tt from"node:path";import{TextDecoder as Ox}from"node:util";function $o(e,t){let i=tt.relative(e,t);return i===""||!tt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${tt.sep}`)}function _m(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Hx(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Dx(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function jo(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Gl(e,t){let i=await Te.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Im(e,t,i){let r=tt.resolve(e),n=tt.resolve(t);if(!$o(r,n))throw new Error(`${i} is outside its managed root`);let a=[await Gl(r,i)],o=r;for(let s of tt.relative(r,n).split(tt.sep).filter(Boolean)){await _t(a,i),o=tt.join(o,s);let c=await Gl(o,i);if(!$o(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await _t(a,i),a}async function _t(e,t){for(let i of e){let r=await Te.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Hx(i,r)||await Te.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Lx(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 mt(e){let t=_m(e.maxBytes),i=tt.resolve(e.file),r=await Im(e.root,tt.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Gl(tt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await _t(r,e.label);let a=await Te.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=Dx(a),s=await Te.realpath(i);if(!$o(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>$o(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?To.O_RDONLY:To.O_RDONLY|To.O_NOFOLLOW|To.O_NONBLOCK,l=await Te.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Te.lstat(i),Te.realpath(i)]);if(await _t(r,e.label),await _t(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!jo(o,u)||!jo(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Lx(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),Te.lstat(i),Te.realpath(i)]);if(await _t(r,e.label),await _t(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!jo(o,v)||!jo(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:$x("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Tm(e){let t=await mt(e),i;try{i=new Ox("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 Sn(e){let t=await Im(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await Te.readdir(e.directory,{withFileTypes:!0});else{let r=_m(e.maxEntries);i=[];let n=await Te.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 _t(t,e.label),{entries:i,verify:()=>_t(t,e.label)}}var Fx=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Mx=new Set(["id","type","source","target","staged","backup"]),qx=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Wx=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Om=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var zx=256*1024,hH=1024*1024,mH=16*1024;var vH=64*1024*1024;var Jx=new Vx("utf-8",{fatal:!0});function Ho(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Do(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 Hm(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ul(e,t){if(typeof e!="string"||e.length===0||It.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Oo(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function jm(e,t){if(Ul(e,t),e.includes("\\")||e!==It.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 Gx(e,t){let i=Ho(e,`transaction operations[${t}]`);if(Do(i,Mx,`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`);Ul(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ul(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 Dm(e){let t=Ho(e,"Native Archive transaction journal");if(Do(t,qx,"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"||!Om.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(!Hm(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Oo(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=Ho(s,`Archive transaction operations[${c}]`);if(Do(l,Wx,`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`);jm(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&jm(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Oo(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(Oo(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`);Oo(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 Ux(e){let t=Ho(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Dm(t);if(Do(t,Fx,"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"||!Om.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!It.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!It.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(!Hm(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(Gx),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 Kx(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return It.join(e.transactionsDir,t)}function Lm(e,t){let i=Kx(e,t);return{directory:i,journal:It.join(i,"transaction.json"),events:It.join(i,"events.jsonl"),staged:It.join(i,"staged"),backups:It.join(i,"backups")}}async function Kl(e,t){let i=Lm(e,t);return await Promise.all(Object.values(i).map(r=>z(e.runtimeDir,r))),i}async function Yl(e,t,i={}){let r=await Kl(e,t),n=await mt({root:e.runtimeDir,file:r.journal,maxBytes:zx,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Jx.decode(n.bytes)),o=Ux(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Qx(e,t,i){let r;try{r=await Yx.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 Yl(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(Jl(n.name))try{let a=await Rm(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Am(a))return!0}catch{return!0}return!1}async function Zx(e,t){let i=Date.now()+5e3,r=Xx.join(e.locksDir,"root-move.lock");for(;;)try{return await Po(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await sm(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 it(e,t,i,r){let n=await Zx(e,t);try{if(await Eo(e.projectRoot),await Qx(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Ro(n)}}import{createHash as Mo}from"crypto";import{spawn as Um}from"node:child_process";import{promises as X}from"fs";import H from"path";import{createHash as Bm}from"crypto";import{createReadStream as eP}from"fs";async function Xl(e){let t=Bm("sha256");for await(let i of eP(e))t.update(i);return t.digest("hex")}function K(e){return Bm("sha256").update(e).digest("hex")}var Lo={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},ru=1e3,tP=8*1024*1024,iP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),nP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),aP=new Set(["schema","include","exclude","hash"]),oP=new Set(["provider","gitSelection","physicalSelection","projection"]),sP=new Set(["provider","selection"]),cP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),lP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),uP=new Set(["schema","status","before","after"]),dP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),fP=new Set(["path","hash","size","type","gitObjectId"]),pP=new Set(["path","size","type","reason"]),hP=new Set(["ref","hash","count"]),mP=new Set(["change-created","legacy-migration","explicit"]),vP=new Set(["file","directory","other"]),gP=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"]),qo=/^[a-f0-9]{64}$/u,Km=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,wP=new Set(["EACCES","EPERM"]),pr=64*1024,tu=64*1024,yP=6e4,NP=1e3,bP=2,nu={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},kP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Ym(e){let t=e.deadlineMs??yP;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 rt(e){return Math.max(0,e.deadlineAt-Date.now())}function j(e){return rt(e)>=1}function Ql(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 dr(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function SP(e){let t={...kP,...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 EP(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&&H.win32.isAbsolute(r)?H.win32.resolve(r):"C:\\Windows",a=H.win32.join(n,"System32","taskkill.exe");if(!H.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=Um(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),NP),u.unref()}catch{d(!1)}});for(let s=0;s<bP;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 au(e,t,i,r){let n=rt(e);if(n<1)throw Ql();let a=e.gitProcess,o=Um(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",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=EP(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Ql(v.error):Ql()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Xm(e){let t={...nu,...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 Bo(e,t,i,r=tu){let{child:n,completion:a}=au(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>r&&(u=!0)}),n.stderr.on("data",p=>{if(c>=pr)return;let v=pr-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Zl(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Cn(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}=au(e,t,i,r.stdin!==void 0),c=[],l=Mo("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,S=!1,y=!1,N=k=>{let E=0;for(;E<k.byteLength;){let b=k.indexOf(0,E),x=b<0?k.byteLength:b,g=k.subarray(E,x);if(!m&&g.byteLength>0&&(h.byteLength+g.byteLength>r.maxRecordBytes?(h=Buffer.alloc(0),m=!0,S=!0):h=Buffer.concat([h,g])),b<0)break;v+=1,h.byteLength===0&&!m&&(y=!0);let w=h.byteLength+1;!m&&v<=r.maxRecords&&p+w<=r.maxBytes?(c.push(h),p+=w):S=!0,h=Buffer.alloc(0),m=!1,E=b+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>r.maxBytes&&(S=!0);let E=r.outputChunkBytes;if(E===void 0){N(k);return}for(let b=0;b<k.byteLength;b+=E)N(k.subarray(b,Math.min(k.byteLength,b+E)))}),o.stderr.on("data",k=>{if(d>=pr)return;let E=pr-d,b=Buffer.from(k).subarray(0,E);u.push(b),d+=b.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:E})=>{let b=r.acceptedExitCodes??[0];if(k!==null&&b.includes(k)&&E===null&&!y&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:S,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${E?`: ${E.message}`:y||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Vo(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 CP(e,t,i){if(i.length===0)return new Set;let r=await Cn(e,t,["check-ignore","--no-index","-z","--stdin"],{...nu,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=Vo(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function xP(e,t,i){let{child:r,completion:n}=au(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>=pr)return;let d=pr-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 fr(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||H.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||H.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function PP(e,t){return e.map(i=>{let r=fr(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function RP(e){let t=H.resolve(e);for(;;){try{return await X.lstat(H.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=H.dirname(t);if(i===t)return!1;t=i}}async function Qm(e,t,i,r={}){let n=H.resolve(t.projectRoot),a=H.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=H.relative(n,H.resolve(f)).replaceAll("\\","/"),v=fr(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Cn(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Cn(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Cn(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Zm(e){return{stageBefore:Zl(e.stagedBefore),combined:Zl(e.combined),stageAfter:Zl(e.stagedAfter)}}async function ev(e,t,i=nu,r={}){let n=H.resolve(t.projectRoot);if(!await RP(n))return null;let a;try{a=await Bo(e,n,["rev-parse","--is-inside-work-tree"])}catch(y){throw dr(y)?y:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:y})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Qm(e,t,i,r)}catch(y){throw dr(y)?y:new Error("Native Git snapshot provider failed after repository detection",{cause:y})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=y=>{for(let N of y){let k=Vo(N),E=k.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let b=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,E))?.groups;if(!b)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=fr(k.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),b.stage==="0"&&d.set(x,b.objectId),b.mode==="160000"&&b.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(Vo),h=PP(v,"combined"),m=new Set(h.filter(y=>!u.has(y))),S=new Set(h.filter((y,N)=>!u.has(y)&&v[N].endsWith("/")));for(let y of f)S.delete(y);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:S,omissions:[],overflow:null,evidence:null,initialFence:Zm(o)}}function ai(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Vm(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function AP(e,t){return!ai(e.stageBefore,e.stageAfter)||!ai(e.stageAfter,t.stageBefore)||!ai(e.combined,t.combined)||!ai(t.stageBefore,t.stageAfter)}async function tv(e,t,i,r,n){let a;try{a=await Qm(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw dr(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=Zm(a),c=Vm(o)||Vm(s),l=AP(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:K(`comet.native.git-selection-overflow.v2
153
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var _P=(1n<<256n)-1n;function IP(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Fm(e){let t=H.resolve(e.paths.projectRoot),i=H.resolve(e.paths.nativeRoot),r=H.resolve(e.paths.runtimeDir),n=H.resolve(e.paths.configFile),a=H.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>rt(e.execution)>=1?!0:(p=!0,h=!0,!1),S=k=>{let E=Buffer.from(`${k.type}\0${k.path}`,"utf8"),b=Mo("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=b[x];if(l=l+BigInt(`0x${b.toString("hex")}`)&_P,d+=1,f+=E.byteLength,Buffer.byteLength(k.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(k)},y=async k=>{if(h||!m())return;let E;try{E=await X.opendir(k)}catch(C){if(!m())return;if(!se(C)&&!oe(C)||k===t&&se(C))throw C;v||=oe(C),p||=se(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let b=!1,x;try{for(;!h&&m();){let C;try{C=await E.read()}catch(G){if(!m())break;if(!se(G)&&!oe(G)||k===t&&se(G))throw G;v||=oe(G),p||=se(G),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let $=H.join(k,C.name),T=jP(t,$);if($===n||$===a||nt(i,$)||nt(r,$)||e.denylist.some(G=>nt(G,$))||ft(T)!==null)continue;if(!m())break;let pe;try{pe=await X.lstat($)}catch(G){if(!m())break;if(!se(G)&&!oe(G))throw G;if(v=!0,S({path:T,type:"other"}),s.push({path:T,size:null,type:"file",reason:se(G)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;let Q=IP(pe);if(Q==="directory"){if(DP(e.policy,T))continue;if(!m())break;let G;try{G=await X.realpath($)}catch(lt){if(!m())break;if(!se(lt)&&!oe(lt))throw lt;if(v=!0,S({path:T,type:Q}),s.push({path:T,size:null,type:"directory",reason:se(lt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(T),h||!m())break;continue}if(!m())break;if(!V(e.physicalProjectRoot,G)||nt(e.physicalNativeRoot,G))continue;if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||(await y($),h))break;continue}if(S({path:T,type:Q}),await e.hooks?.afterNode?.(T),!m()||h)break}}catch(C){b=!0,x=C}let g;try{await E.close()}catch(C){g=C}let w=m();if(b)throw x;if(w&&g!==void 0&&g.code!=="ERR_DIR_CLOSED")throw g};await y(t),m(),p?(o.length=0,d=0,f=0):(o.sort((k,E)=>k.path.localeCompare(E.path,"en")),s.sort((k,E)=>k.path.localeCompare(E.path,"en")));let N=p?K(`comet.native.physical-selection-incomplete.v1
154
+ ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):K(`comet.native.physical-selection.v1
155
+ ${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:N,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function iv(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 TP(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!iv(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 rv(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Mm(e,t){let r=(await Bo(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Km.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return K(`gitlink:${r}`)}async function qm(e,t){let i=await Mm(e,t),r=await xP(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Mm(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function En(e,t){if(ft(t)!==null)return!1;let i=H.resolve(e.projectRoot,...t.split("/"));return!nt(H.resolve(e.nativeRoot),i)&&!nt(H.resolve(e.runtimeDir),i)}function jP(e,t){return H.relative(e,t).split(H.sep).join("/")}function $P(e,t){return t.map(i=>H.resolve(e,...i.split(/[\\/]/u)))}function nt(e,t){let i=H.resolve(e),r=H.resolve(t);return r===i||V(i,r)}function se(e){return wP.has(e.code??"")}function oe(e){return e.code==="ENOENT"}function ou(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
156
+ `)}function OP(e,t){return K(`comet.native.snapshot-policy.v1
157
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function eu(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 HP(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Wm(e){let t=So(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?HP(n):void 0;if(a&&!a())return!1;let o=eu(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=eu(i,c,a),o===null||o.size===0)return!1}return eu(i,o,a)?.has(i.length)??!1}}function nv(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>So(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>So(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=OP(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(Wm),excludeMatchers:i.map(Wm),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 DP(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function zm(e,t,i){if(!e)return!0;let r=()=>j(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 xn(e,t,i){let r=JSON.stringify(i);return K(`${e}
158
158
  ${Buffer.byteLength(t)}:${t}
159
- ${Buffer.byteLength(r)}:${r}`)}function eu(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function $o(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!eu(i))return e.splice(t,1),i}return null}function ii(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ae(i,r)?F(i,r):F(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function yx(e,t,i,r){if(!j(r))return{status:"budget-exhausted"};let n;try{n=await Y.open(e,"r")}catch(c){if(!j(r))return{status:"budget-exhausted"};throw c}if(!j(r))return await n.close(),{status:"budget-exhausted"};let a=Oo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!j(r))return{status:"budget-exhausted"};let c=await n.stat();if(!j(r))return{status:"budget-exhausted"};if(!c.isFile()||!ii(i,c))return{status:"changed"};for(;;){if(!j(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(!j(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!j(r))return{status:"budget-exhausted"};let d=await n.stat();return j(r)?!d.isFile()||!ii(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 Le(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ve(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function or(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ht(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ev(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=H.posix.normalize(e);if(i!==e||H.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function Nx(e,t){let i=Le(e,`Native snapshot entry ${t}`);Ve(i,GP,`Native snapshot entry ${t}`);let r=ev(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Ho.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:ht(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Wm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function bx(e,t){let i=Le(e,`Native snapshot omission ${t}`);if(Ve(i,UP,`Native snapshot omission ${t}`),!XP.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!QP.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:ev(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:ht(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function kx(e){let t=Le(e,"Native snapshot omission overflow");if(Ve(t,KP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ho.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:or(t.count,"Native snapshot omission overflow count")}}function ar(e,t){let i=Le(e,t);if(Ve(i,WP,t),typeof i.hash!="string"||!Ho.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=ht(i.recordCount,`${t} recordCount`),n=ht(i.storedRecordCount,`${t} storedRecordCount`),a=ht(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 Fm(e){let t=Le(e,"Native Git selection evidence");if(Ve(t,qP,"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=ar(t.stageBefore,"Native Git selection stageBefore"),r=ar(t.combined,"Native Git selection combined"),n=ar(t.stageAfter,"Native Git selection stageAfter"),a=ar(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ar(t.finalCombined,"Native Git selection finalCombined"),s=ar(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!ri(i,n)||!ri(n,a)||!ri(r,o)||!ri(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 Mm(e,t){let i=Le(e,t);if(Ve(i,JP,t),typeof i.hash!="string"||!Ho.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=ht(i.visitedNodeCount,`${t} visitedNodeCount`),n=ht(i.recordCount,`${t} recordCount`),a=ht(i.storedRecordCount,`${t} storedRecordCount`),o=ht(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 Sx(e){let t=Le(e,"Native physical selection evidence");if(Ve(t,zP,"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=Mm(t.before,"Native physical selection before"),r=Mm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!Xm(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Pi(e){let t=Le(e,"Native content snapshot manifest");if(Ve(t,BP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!YP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=Le(t.capture,"Native content snapshot capture");if(Ve(b,FP,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=b.gitSelection===void 0?void 0:Fm(b.gitSelection),g=b.physicalSelection===void 0?void 0:Sx(b.physicalSelection),w=null;if(b.projection!==void 0){let C=Le(b.projection,"Native content snapshot projection");if(Ve(C,MP,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:Fm(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Le(t.limits,"Native content snapshot limits");Ve(r,LP,"Native content snapshot limits");let n={maxFiles:or(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:or(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:or(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:or(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:or(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Le(t.policy,"Native snapshot policy");if(Ve(b,VP,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Zm({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(Nx),s=t.omitted.map(bx),c=ht(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:kx(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,P)=>b+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>tu||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,N=y?.status==="overflow"||y?.status==="overflow-and-changed",k=y?.status==="changed"||y?.status==="overflow-and-changed";if(N!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={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(nu(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function tv(e,t,i={}){let r=Pi(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=H.resolve(e.projectRoot),a=zm(i),o=Jm(i.gitSelectionLimits),s=await Km(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(Qm(s).filter(g=>bn(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>bn(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await ox(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&bn(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await Ym(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!bn(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let N=r.omissionOverflow?.count??0,k=r.omissionOverflow?.hash??U("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,k=Sn(k,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{N+=1,k=Sn(k,"omission",g)};for(;y.length>tu;){let g=$o(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+N===0,entries:m,omitted:y,omittedCount:y.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:N}}:{}}),P=b();for(;nu(P)>r.limits.maxManifestBytes;){let g=$o(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),P=b()}return Pi(P)}function Ex(e,t){if(!DP.test(t))throw new Error(`Invalid Native change name: ${t}`);return H.join(G(e,t),"baseline-manifest.json")}async function iv(e,t={}){let i={maxFiles:t.limits?.maxFiles??Io.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Io.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Io.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Io.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=Zm(t.policy),n=zm({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Jm(t.gitSelectionLimits),o=nx(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=H.resolve(e.projectRoot),c=await Y.realpath(s),l=H.resolve(e.nativeRoot),u=await Y.realpath(l),d=H.resolve(e.runtimeDir),f=H.resolve(e.configFile),p=H.join(s,".comet","current-change.json"),v=mx(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,N=0,k=0,E=U("comet.native.snapshot-omission-overflow.v1"),b=0,P=!1,g=null,w=_=>{k+=1,E=Sn(E,"omission",_)},C=_=>{if(N+=1,m.length<tu){m.push(_);return}if(eu(_)){let A=$o(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},$=_=>{N+=_.count,k+=_.count,E=Sn(E,"git-selection",{source:"git-selection",..._})},T=_=>{k+=1,E=Sn(E,"manifest-entry",{reason:"manifest-size",entry:_})},de=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),P||(P=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},X=(_,A)=>{let I=h.findIndex(K=>K.path===_);if(I<0)return;let[D]=h.splice(I,1);b-=D.size,S.delete(_),C(A)},J=async(_,A,I,D)=>{if(!I.isFile()||I.isSymbolicLink()||!j(n))return;let K;try{K=await Y.realpath(_)}catch(R){if(!j(n))return;if(!ae(R)&&!ne(R))throw R;C({path:A,size:I.size,type:"file",reason:ne(R)?"changed-during-read":"unreadable"});return}if(!j(n)||!L(c,K)||rt(u,K))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let M,O,Z;try{if(M=await yx(K,I.size,I,n),M.status==="budget-exhausted"||!j(n))return;if(M.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!j(n)||(Z=await Y.realpath(_),!j(n)))return;O=await Y.lstat(_)}catch(R){if(!j(n))return;if(!ae(R)&&!ne(R))throw R;C({path:A,size:I.size,type:"file",reason:ne(R)?"changed-during-read":"unreadable"});return}if(j(n)){if(M.bytes!==I.size||Z!==K||!ii(I,M.finalStat)||!ii(M.finalStat,O)||!O.isFile()||O.isSymbolicLink()||O.size!==I.size||O.mtimeMs!==I.mtimeMs||O.ctimeMs!==I.ctimeMs){C({path:A,size:O.isFile()?O.size:null,type:O.isFile()?"file":"other",reason:"changed-during-read"});return}j(n)&&await de({path:A,hash:M.hash,size:O.size,type:"file",...D===void 0?{}:{gitObjectId:D}},{kind:"file",target:_,realTarget:K,stat:O})}},ct=async(_,A,I)=>{if(!j(n))return;let D,K,M;try{if(D=await Y.readlink(_,{encoding:"buffer"}),!j(n)||(M=await Y.lstat(_),!j(n)))return;K=await Y.readlink(_,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!ae(R)&&!ne(R))throw R;C({path:A,size:null,type:"other",reason:ne(R)?"changed-during-read":"unreadable"});return}if(!j(n))return;if(!M.isSymbolicLink()||!ii(I,M)||M.mtimeMs!==I.mtimeMs||M.ctimeMs!==I.ctimeMs||!D.equals(K)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let O=D.byteLength;if(h.length>=i.maxFiles){C({path:A,size:O,type:"other",reason:"file-count"});return}if(O>i.maxFileBytes){C({path:A,size:O,type:"other",reason:"file-size"});return}if(b+O>i.maxTotalBytes){C({path:A,size:O,type:"other",reason:"total-size"});return}let Z=Oo("sha256").update("symlink\0").update(D).digest("hex");j(n)&&await de({path:A,hash:Z,size:O,type:"file"},{kind:"symlink",target:_,rawTarget:D,stat:M})},Je=async()=>{for(let[_,A]of[...S]){if(!j(n))return;if(A.kind==="file"){let O,Z;try{if(O=await Y.realpath(A.target),!j(n))return;Z=await Y.lstat(A.target)}catch(R){if(!j(n))return;if(!ae(R)&&!ne(R))throw R;X(_,{path:_,size:null,type:"file",reason:ae(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(O!==A.realTarget||!Z.isFile()||Z.isSymbolicLink()||!ii(A.stat,Z)||Z.size!==A.stat.size||Z.mtimeMs!==A.stat.mtimeMs||Z.ctimeMs!==A.stat.ctimeMs)&&X(_,{path:_,size:Z.isFile()?Z.size:null,type:Z.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let O,Z;try{if(O=await Y.lstat(A.target),!j(n))return;Z=await Y.readlink(A.target,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!ae(R)&&!ne(R))throw R;X(_,{path:_,size:null,type:"other",reason:ae(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(!O.isSymbolicLink()||!ii(A.stat,O)||O.mtimeMs!==A.stat.mtimeMs||O.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(Z))&&X(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,D;try{if(I=await Y.realpath(A.target),!j(n))return;D=await Y.lstat(A.target)}catch{if(!j(n))return;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;if(!(I===A.realTarget&&D.isDirectory()&&!D.isSymbolicLink()&&ii(A.stat,D)&&L(c,I)&&!rt(u,I))){X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!j(n))return;M=await Bm(n,I)}catch(O){if(sr(O))throw O;X(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;M.dirty?X(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==A.hash&&X(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!j(n))return;try{let I=await Y.lstat(A);if(!j(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!j(n))return;if(ne(I))continue;if(!ae(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},xe=await Km(n,e,a,t.gitSelectionHooks);if(xe===null){let _=await Hm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let D of _.records){if(D.type!=="file"&&D.type!=="symlink"||S.has(D.path))continue;if(it(n)<1)break;if(!Vm(r,D.path,n))continue;if(it(n)<1)break;let K=H.resolve(s,...D.path.split("/")),M;try{M=await Y.lstat(K)}catch(O){if(!j(n))break;if(!ae(O)&&!ne(O))throw O;C({path:D.path,size:null,type:"file",reason:ne(O)?"changed-during-read":"unreadable"});continue}if(it(n)<1)break;if(D.type==="symlink"&&M.isSymbolicLink()){if(await ct(K,D.path,M),it(n)<1)break;continue}if(D.type!=="file"||!M.isFile()||M.isSymbolicLink()){C({path:D.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(K,D.path,M),it(n)<1)break}it(n)>=1&&await Je();let A=await Hm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=px(_.evidence,A.evidence);g=I.evidence;for(let D of[..._.omissions,...A.omissions,...I.omissions])m.some(K=>K.path===D.path&&K.reason===D.reason)||C(D)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=Pi(_);for(let Q of R.entries)Q.gitObjectId!==void 0&&A.set(Q.path,Q);I=A.size>0}let D=new Set,K=!0;try{let R=await kn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,K=!1,A.clear();else for(let Q of R.records){let ee=jo(Q),ge=ee.indexOf(" "),fe=ge<0?null:cr(ee.slice(ge+1));if(ge!==1||fe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ee[0]!=="H"&&D.add(fe)}}catch(R){if(sr(R))throw R;I=!1,K=!1,A.clear()}let M=new Set;try{let R=await To(n,s,["ls-files","--modified","-z"],Zl);for(let Q of R.toString("utf8").split("\0")){let ee=cr(Q);ee!==null&&M.add(ee)}}catch{I=!1,K=!1,A.clear()}let O=new Set,Z=new Set;for(let R of Qm(xe)){if(S.has(R)||!bn(e,R))continue;if(it(n)<1)break;if(!Vm(r,R,n))continue;if(it(n)<1)break;let Q=H.resolve(s,...R.split("/"));if(Q===f||Q===p||rt(d,Q)||v.some(Re=>rt(Re,Q)))continue;if(xe.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Re,Zn;try{[Re,Zn]=await Promise.all([Y.realpath(Q),Y.lstat(Q)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Zn.isSymbolicLink()||!Zn.isDirectory()||!L(c,Re)||rt(u,Re)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let $i=await Bm(n,Re);if($i.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await de({path:R,hash:$i.hash,size:0,type:"file"},{kind:"gitlink",target:Q,realTarget:Re,stat:Zn,hash:$i.hash})}catch($i){if(sr($i))throw $i;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ee;try{ee=await Y.lstat(Q)}catch(Re){if(ne(Re)&&xe.tracked.has(R)){y.set(R,Q);continue}if(!ae(Re)&&!ne(Re))throw Re;C({path:R,size:null,type:"file",reason:ne(Re)?"changed-during-read":"unreadable"});continue}if(ee.isSymbolicLink()){await ct(Q,R,ee);continue}if(!ee.isFile()){xe.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let ge=xe.trackedObjectIds.get(R),fe=ge?A.get(R):void 0;if(I&&fe?.gitObjectId!==void 0&&fe.gitObjectId===ge&&!D.has(R)&&!M.has(R)){if(h.length>=i.maxFiles){C({path:R,size:fe.size,type:"file",reason:"file-count"});continue}if(fe.size>i.maxFileBytes){C({path:R,size:fe.size,type:"file",reason:"file-size"});continue}if(b+fe.size>i.maxTotalBytes){C({path:R,size:fe.size,type:"file",reason:"total-size"});continue}h.push({...fe}),b+=fe.size,O.add(R);continue}let Td=K&&!D.has(R)&&!M.has(R)?ge:void 0;await J(Q,R,ee,Td),Td!==void 0&&Z.add(R)}if(await Je(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Ym(n,e,a,xe,t.gitSelectionHooks?.outputChunkBytes),O.size>0||I&&Z.size>0){let R=await To(n,s,["ls-files","--modified","-z"],Zl),Q=new Set;for(let ee of R.toString("utf8").split("\0")){let ge=cr(ee);ge!==null&&Q.add(ge)}for(let ee of O){if(!Q.has(ee))continue;let ge=h.find(fe=>fe.path===ee);X(ee,{path:ee,size:ge?.size??null,type:"file",reason:"changed-during-read"})}for(let ee of Z){if(!Q.has(ee))continue;let ge=h.find(fe=>fe.path===ee);ge&&delete ge.gitObjectId}}for(let R of xe.omissions)C(R);xe.overflow&&$(xe.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let yy=xe===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...xe.evidence?{gitSelection:xe.evidence}:{}},Id=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:yy,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:k}}:{}}),_s=Id();for(;nu(_s)>i.maxManifestBytes;){if(m.filter(A=>!eu(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let D=$o(m);if(D===null)break;w(D)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))N+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");_s=Id()}return _s}async function au(e,t,i={}){let n=(await _e(e.projectRoot))?.native.snapshot??_l;return iv(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 Do(e,t){let i=Ex(e,t),r=ce(e,i);await W(r,i);try{let n=await xm({root:r,file:i,maxBytes:HP,label:"Native baseline snapshot manifest"});return Pi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as qx}from"crypto";import Wx from"path";var Fe=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as Bo,promises as nt}from"node:fs";import at from"node:path";import{TextDecoder as Bx}from"node:util";import $x from"path";var _x=Rr(Ji(),1);var CH=4*1024*1024;var Ix=null;function Tx(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function rv(e,t){return(...i)=>{let r=Ix;if(r===null)return t(...i);let n=Tx(`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 _H=rv("hookWritePolicy",async e=>(await El(e))?.hook??{allow_paths:[]});var nv=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Cn(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 En(e,t){let i=Cn(e,t);if($x.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 Ox(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 av(e){if(!e.run_id)return null;let t=Cn(e,"run_id"),i=Cn(e,"skill"),r=Cn(e,"skill_version"),n=Cn(e,"skill_hash"),a=En(e,"pending_ref"),o=En(e,"trajectory_ref"),s=En(e,"context_ref"),c=En(e,"artifacts_ref"),l=En(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:nv(e,"current_step"),iteration:u,pending:nv(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Ox(e)}}var PD=256*1024;var Hx=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Dx(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=av(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ou(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=>!Hx.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 Dx(t)}var ur={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 Vo(e,t){let i=at.relative(e,t);return i===""||!at.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${at.sep}`)}function Lx(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lo(e,t){return F({...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 Vx(e,t){return F({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fo(e,t,i){let r=Fe[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=at.resolve(e),a=at.resolve(n,...r.slice(8).split("/"));if(!Vo(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function ov(e){let t=await nt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await nt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Fx(e,t){let i=at.resolve(e),r=at.resolve(t);if(!Vo(i,r))throw new Error("Native Run path is outside its change");let n=[await ov(i)],a=i;for(let o of at.relative(i,r).split(at.sep).filter(Boolean)){a=at.join(a,o);let s;try{s=await ov(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Vo(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function sv(e){for(let t of e){let i=await nt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Vx(t,i)||await nt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Mx(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 Mo(e,t,i,r,n){let a=await Fx(e,at.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await nt.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=Lx(o),c=await nt.realpath(t);if(!Vo(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Bo.O_RDONLY:Bo.O_RDONLY|Bo.O_NOFOLLOW|Bo.O_NONBLOCK,u;try{u=await nt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),nt.lstat(t),nt.realpath(t)]);if(await sv(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Lo(s,d)||!Lo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await Mx(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),nt.lstat(t),nt.realpath(t)]);if(await sv(a),!m.isFile()||m.isSymbolicLink()||S!==c||!Lo(s,h)||!Lo(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new Bx("utf-8",{fatal:!0}).decode(v)}catch(N){throw new Error(`${r} is not valid UTF-8`,{cause:N})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function cv(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function su(e){return ou(e)}async function dr(e,t){let i=Fo(e,"stateRef"),r=await Mo(e,i,ur.runStateBytes,"Native Run state",t);return r?ou(cv(r.text,"Native Run state")):null}async function xi(e,t,i){let r=Fo(e,"trajectoryRef",t),n=await Mo(e,r,ur.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>ur.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${ur.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 lv(e,t,i){return(await Mo(e,Fo(e,"trajectoryRef",t),ur.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function qo(e,t,i){let r=await Mo(e,Fo(e,"checkpointRef",t),ur.checkpointBytes,"Native Run checkpoint",i);return r?cv(r.text,"Native Run checkpoint"):null}var zx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function cu(e){return qx("sha256").update(e).digest("hex")}function Jx(e,t){if(!zx.test(t))throw new Error(`Invalid Native change name: ${t}`);return Wx.join(G(e,t),"trajectory.jsonl")}function Gx(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 Ux(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 Kx(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=Gx(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(`
160
- `)])}catch(d){if(!Ux(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:cu(t),targetHash:cu(l),tailHash:cu(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Yx(e,t){let i=Jx(e,t);await W(ce(e,i),i);let r=G(e,t),n=await lv(r,Fe.trajectoryRef);return n===null?{status:"clean",file:i}:Kx(i,Buffer.from(n))}async function uv(e,t){let i=await Yx(e,t);return"inspection"in i?i.inspection:i}import{createHash as Xx}from"node:crypto";import{promises as Wo}from"node:fs";import It from"node:path";var Pn=/^[a-f0-9]{64}$/u,dv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Qx=16*1024,uu=process.platform,Zx=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function fr(e){return Zx.has(e)}function mv(e,t){let i=It.relative(e,t);return It.isAbsolute(i)||i===".."||i.startsWith(`..${It.sep}`)?null:i.replaceAll("\\","/")||"."}function vv(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function gv(e,t){if(e.length===0||vv(e)||e.includes("\\")||It.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=It.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function du(e,t){return Xx("sha256").update(`${e}
161
- ${t}`).digest("hex")}async function fv(e,t){let i=await Wo.realpath(t),r=await Wo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=uu==="win32"?It.normalize(i).toLowerCase():i;return du(e,`${n}
159
+ ${Buffer.byteLength(r)}:${r}`)}function iu(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Fo(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!iu(i))return e.splice(t,1),i}return null}function ni(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function LP(e,t,i,r){if(!j(r))return{status:"budget-exhausted"};let n;try{n=await X.open(e,"r")}catch(c){if(!j(r))return{status:"budget-exhausted"};throw c}if(!j(r))return await n.close(),{status:"budget-exhausted"};let a=Mo("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!j(r))return{status:"budget-exhausted"};let c=await n.stat();if(!j(r))return{status:"budget-exhausted"};if(!c.isFile()||!ni(i,c))return{status:"changed"};for(;;){if(!j(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(!j(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!j(r))return{status:"budget-exhausted"};let d=await n.stat();return j(r)?!d.isFile()||!ni(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 Ve(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fe(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function ur(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function vt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function av(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=H.posix.normalize(e);if(i!==e||H.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function BP(e,t){let i=Ve(e,`Native snapshot entry ${t}`);Fe(i,fP,`Native snapshot entry ${t}`);let r=av(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!qo.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:vt(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Km.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function VP(e,t){let i=Ve(e,`Native snapshot omission ${t}`);if(Fe(i,pP,`Native snapshot omission ${t}`),!vP.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!gP.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:av(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:vt(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function FP(e){let t=Ve(e,"Native snapshot omission overflow");if(Fe(t,hP,"Native snapshot omission overflow"),typeof t.hash!="string"||!qo.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:ur(t.count,"Native snapshot omission overflow count")}}function lr(e,t){let i=Ve(e,t);if(Fe(i,lP,t),typeof i.hash!="string"||!qo.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=vt(i.recordCount,`${t} recordCount`),n=vt(i.storedRecordCount,`${t} storedRecordCount`),a=vt(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 Jm(e){let t=Ve(e,"Native Git selection evidence");if(Fe(t,cP,"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=lr(t.stageBefore,"Native Git selection stageBefore"),r=lr(t.combined,"Native Git selection combined"),n=lr(t.stageAfter,"Native Git selection stageAfter"),a=lr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=lr(t.finalCombined,"Native Git selection finalCombined"),s=lr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!ai(i,n)||!ai(n,a)||!ai(r,o)||!ai(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 Gm(e,t){let i=Ve(e,t);if(Fe(i,dP,t),typeof i.hash!="string"||!qo.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=vt(i.visitedNodeCount,`${t} visitedNodeCount`),n=vt(i.recordCount,`${t} recordCount`),a=vt(i.storedRecordCount,`${t} storedRecordCount`),o=vt(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 MP(e){let t=Ve(e,"Native physical selection evidence");if(Fe(t,uP,"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=Gm(t.before,"Native physical selection before"),r=Gm(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!iv(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 Ri(e){let t=Ve(e,"Native content snapshot manifest");if(Fe(t,rP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!mP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let b=Ve(t.capture,"Native content snapshot capture");if(Fe(b,oP,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:Jm(b.gitSelection),g=b.physicalSelection===void 0?void 0:MP(b.physicalSelection),w=null;if(b.projection!==void 0){let C=Ve(b.projection,"Native content snapshot projection");if(Fe(C,sP,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...C.selection===void 0?{}:{selection:Jm(C.selection)}}}if(b.provider==="git"){if(g||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Ve(t.limits,"Native content snapshot limits");Fe(r,nP,"Native content snapshot limits");let n={maxFiles:ur(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ur(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ur(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ur(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:ur(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Ve(t.policy,"Native snapshot policy");if(Fe(b,aP,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=nv({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(BP),s=t.omitted.map(VP),c=vt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:FP(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>ru||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(b=>b.reason==="git-enumeration-limit"),f=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...d,...f])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(b=>b.reason==="physical-enumeration-limit"),S=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...m,...S])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||S.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=i?.physicalSelection,N=y?.status==="overflow"||y?.status==="overflow-and-changed",k=y?.status==="changed"||y?.status==="overflow-and-changed";if(N!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(S.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={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(ou(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function ov(e,t,i={}){let r=Ri(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=H.resolve(e.projectRoot),a=Ym(i),o=Xm(i.gitSelectionLimits),s=await ev(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(rv(s).filter(g=>En(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>En(e,g)),d=(g,w)=>w.some(C=>g===C||g.startsWith(`${C}/`)),f=g=>d(g,l),p=g=>d(g,u),v=[...r.entries.map(g=>g.path),...r.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await CP(a,n,v),m=r.entries.filter(g=>!f(g.path)&&!p(g.path)&&En(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await tv(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let S=[...s.omissions];for(let g of l)S.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((g,w)=>g.path.localeCompare(w.path,"en"));let y=r.omitted.filter(g=>f(g.path)||p(g.path)||!En(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(w=>w.startsWith(`${g.path}/`)):!0);for(let g of S)y.some(w=>w.path===g.path&&w.reason===g.reason)||y.push(g);y.sort((g,w)=>g.path.localeCompare(w.path,"en"));let N=r.omissionOverflow?.count??0,k=r.omissionOverflow?.hash??K("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,k=xn(k,"git-selection",{source:"git-selection",...s.overflow}));let E=g=>{N+=1,k=xn(k,"omission",g)};for(;y.length>ru;){let g=Fo(y);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(g)}let b=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:y.length+N===0,entries:m,omitted:y,omittedCount:y.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:N}}:{}}),x=b();for(;ou(x)>r.limits.maxManifestBytes;){let g=Fo(y);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(g),x=b()}return Ri(x)}function qP(e,t){if(!iP.test(t))throw new Error(`Invalid Native change name: ${t}`);return H.join(U(e,t),"baseline-manifest.json")}async function sv(e,t={}){let i={maxFiles:t.limits?.maxFiles??Lo.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Lo.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Lo.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Lo.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=nv(t.policy),n=Ym({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Xm(t.gitSelectionLimits),o=SP(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=H.resolve(e.projectRoot),c=await X.realpath(s),l=H.resolve(e.nativeRoot),u=await X.realpath(l),d=H.resolve(e.runtimeDir),f=H.resolve(e.configFile),p=H.join(s,".comet","current-change.json"),v=$P(s,t.denylist??[]),h=[],m=[],S=new Map,y=new Map,N=0,k=0,E=K("comet.native.snapshot-omission-overflow.v1"),b=0,x=!1,g=null,w=_=>{k+=1,E=xn(E,"omission",_)},C=_=>{if(N+=1,m.length<ru){m.push(_);return}if(iu(_)){let A=Fo(m);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),m.push(_);return}w(_)},$=_=>{N+=_.count,k+=_.count,E=xn(E,"git-selection",{source:"git-selection",..._})},T=_=>{k+=1,E=xn(E,"manifest-entry",{reason:"manifest-size",entry:_})},pe=async(_,A)=>{h.push(_),b+=_.size,S.set(_.path,A),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},Q=(_,A)=>{let I=h.findIndex(Y=>Y.path===_);if(I<0)return;let[D]=h.splice(I,1);b-=D.size,S.delete(_),C(A)},G=async(_,A,I,D)=>{if(!I.isFile()||I.isSymbolicLink()||!j(n))return;let Y;try{Y=await X.realpath(_)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!j(n)||!V(c,Y)||nt(u,Y))return;if(h.length>=i.maxFiles){C({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){C({path:A,size:I.size,type:"file",reason:"file-size"});return}if(b+I.size>i.maxTotalBytes){C({path:A,size:I.size,type:"file",reason:"total-size"});return}let q,O,ee;try{if(q=await LP(Y,I.size,I,n),q.status==="budget-exhausted"||!j(n))return;if(q.status==="changed"){C({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!j(n)||(ee=await X.realpath(_),!j(n)))return;O=await X.lstat(_)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:I.size,type:"file",reason:oe(R)?"changed-during-read":"unreadable"});return}if(j(n)){if(q.bytes!==I.size||ee!==Y||!ni(I,q.finalStat)||!ni(q.finalStat,O)||!O.isFile()||O.isSymbolicLink()||O.size!==I.size||O.mtimeMs!==I.mtimeMs||O.ctimeMs!==I.ctimeMs){C({path:A,size:O.isFile()?O.size:null,type:O.isFile()?"file":"other",reason:"changed-during-read"});return}j(n)&&await pe({path:A,hash:q.hash,size:O.size,type:"file",...D===void 0?{}:{gitObjectId:D}},{kind:"file",target:_,realTarget:Y,stat:O})}},lt=async(_,A,I)=>{if(!j(n))return;let D,Y,q;try{if(D=await X.readlink(_,{encoding:"buffer"}),!j(n)||(q=await X.lstat(_),!j(n)))return;Y=await X.readlink(_,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;C({path:A,size:null,type:"other",reason:oe(R)?"changed-during-read":"unreadable"});return}if(!j(n))return;if(!q.isSymbolicLink()||!ni(I,q)||q.mtimeMs!==I.mtimeMs||q.ctimeMs!==I.ctimeMs||!D.equals(Y)){C({path:A,size:null,type:"other",reason:"changed-during-read"});return}let O=D.byteLength;if(h.length>=i.maxFiles){C({path:A,size:O,type:"other",reason:"file-count"});return}if(O>i.maxFileBytes){C({path:A,size:O,type:"other",reason:"file-size"});return}if(b+O>i.maxTotalBytes){C({path:A,size:O,type:"other",reason:"total-size"});return}let ee=Mo("sha256").update("symlink\0").update(D).digest("hex");j(n)&&await pe({path:A,hash:ee,size:O,type:"file"},{kind:"symlink",target:_,rawTarget:D,stat:q})},Ge=async()=>{for(let[_,A]of[...S]){if(!j(n))return;if(A.kind==="file"){let O,ee;try{if(O=await X.realpath(A.target),!j(n))return;ee=await X.lstat(A.target)}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"file",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(O!==A.realTarget||!ee.isFile()||ee.isSymbolicLink()||!ni(A.stat,ee)||ee.size!==A.stat.size||ee.mtimeMs!==A.stat.mtimeMs||ee.ctimeMs!==A.stat.ctimeMs)&&Q(_,{path:_,size:ee.isFile()?ee.size:null,type:ee.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let O,ee;try{if(O=await X.lstat(A.target),!j(n))return;ee=await X.readlink(A.target,{encoding:"buffer"})}catch(R){if(!j(n))return;if(!se(R)&&!oe(R))throw R;Q(_,{path:_,size:null,type:"other",reason:se(R)?"unreadable":"changed-during-read"});continue}if(!j(n))return;(!O.isSymbolicLink()||!ni(A.stat,O)||O.mtimeMs!==A.stat.mtimeMs||O.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ee))&&Q(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,D;try{if(I=await X.realpath(A.target),!j(n))return;D=await X.lstat(A.target)}catch{if(!j(n))return;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;if(!(I===A.realTarget&&D.isDirectory()&&!D.isSymbolicLink()&&ni(A.stat,D)&&V(c,I)&&!nt(u,I))){Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let q;try{if(!j(n))return;q=await qm(n,I)}catch(O){if(dr(O))throw O;Q(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!j(n))return;q.dirty?Q(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):q.hash!==A.hash&&Q(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of y){if(!j(n))return;try{let I=await X.lstat(A);if(!j(n))return;C({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!j(n))return;if(oe(I))continue;if(!se(I))throw I;C({path:_,size:null,type:"file",reason:"unreadable"})}}},Re=await ev(n,e,a,t.gitSelectionHooks);if(Re===null){let _=await Fm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let D of _.records){if(D.type!=="file"&&D.type!=="symlink"||S.has(D.path))continue;if(rt(n)<1)break;if(!zm(r,D.path,n))continue;if(rt(n)<1)break;let Y=H.resolve(s,...D.path.split("/")),q;try{q=await X.lstat(Y)}catch(O){if(!j(n))break;if(!se(O)&&!oe(O))throw O;C({path:D.path,size:null,type:"file",reason:oe(O)?"changed-during-read":"unreadable"});continue}if(rt(n)<1)break;if(D.type==="symlink"&&q.isSymbolicLink()){if(await lt(Y,D.path,q),rt(n)<1)break;continue}if(D.type!=="file"||!q.isFile()||q.isSymbolicLink()){C({path:D.path,size:q.isFile()?q.size:null,type:q.isDirectory()?"directory":q.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await G(Y,D.path,q),rt(n)<1)break}rt(n)>=1&&await Ge();let A=await Fm({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=TP(_.evidence,A.evidence);g=I.evidence;for(let D of[..._.omissions,...A.omissions,...I.omissions])m.some(Y=>Y.path===D.path&&Y.reason===D.reason)||C(D)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let R=Ri(_);for(let Z of R.entries)Z.gitObjectId!==void 0&&A.set(Z.path,Z);I=A.size>0}let D=new Set,Y=!0;try{let R=await Cn(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)I=!1,Y=!1,A.clear();else for(let Z of R.records){let te=Vo(Z),we=te.indexOf(" "),he=we<0?null:fr(te.slice(we+1));if(we!==1||he===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");te[0]!=="H"&&D.add(he)}}catch(R){if(dr(R))throw R;I=!1,Y=!1,A.clear()}let q=new Set;try{let R=await Bo(n,s,["ls-files","--modified","-z"],tu);for(let Z of R.toString("utf8").split("\0")){let te=fr(Z);te!==null&&q.add(te)}}catch{I=!1,Y=!1,A.clear()}let O=new Set,ee=new Set;for(let R of rv(Re)){if(S.has(R)||!En(e,R))continue;if(rt(n)<1)break;if(!zm(r,R,n))continue;if(rt(n)<1)break;let Z=H.resolve(s,...R.split("/"));if(Z===f||Z===p||nt(d,Z)||v.some(Ae=>nt(Ae,Z)))continue;if(Re.gitlinks.has(R)){if(h.length>=i.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Ae,ra;try{[Ae,ra]=await Promise.all([X.realpath(Z),X.lstat(Z)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(ra.isSymbolicLink()||!ra.isDirectory()||!V(c,Ae)||nt(u,Ae)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Di=await qm(n,Ae);if(Di.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await pe({path:R,hash:Di.hash,size:0,type:"file"},{kind:"gitlink",target:Z,realTarget:Ae,stat:ra,hash:Di.hash})}catch(Di){if(dr(Di))throw Di;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let te;try{te=await X.lstat(Z)}catch(Ae){if(oe(Ae)&&Re.tracked.has(R)){y.set(R,Z);continue}if(!se(Ae)&&!oe(Ae))throw Ae;C({path:R,size:null,type:"file",reason:oe(Ae)?"changed-during-read":"unreadable"});continue}if(te.isSymbolicLink()){await lt(Z,R,te);continue}if(!te.isFile()){Re.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let we=Re.trackedObjectIds.get(R),he=we?A.get(R):void 0;if(I&&he?.gitObjectId!==void 0&&he.gitObjectId===we&&!D.has(R)&&!q.has(R)){if(h.length>=i.maxFiles){C({path:R,size:he.size,type:"file",reason:"file-count"});continue}if(he.size>i.maxFileBytes){C({path:R,size:he.size,type:"file",reason:"file-size"});continue}if(b+he.size>i.maxTotalBytes){C({path:R,size:he.size,type:"file",reason:"total-size"});continue}h.push({...he}),b+=he.size,O.add(R);continue}let Dd=Y&&!D.has(R)&&!q.has(R)?we:void 0;await G(Z,R,te,Dd),Dd!==void 0&&ee.add(R)}if(await Ge(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await tv(n,e,a,Re,t.gitSelectionHooks?.outputChunkBytes),O.size>0||I&&ee.size>0){let R=await Bo(n,s,["ls-files","--modified","-z"],tu),Z=new Set;for(let te of R.toString("utf8").split("\0")){let we=fr(te);we!==null&&Z.add(we)}for(let te of O){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);Q(te,{path:te,size:we?.size??null,type:"file",reason:"changed-during-read"})}for(let te of ee){if(!Z.has(te))continue;let we=h.find(he=>he.path===te);we&&delete we.gitObjectId}}for(let R of Re.omissions)C(R);Re.overflow&&$(Re.overflow)}h.sort((_,A)=>_.path.localeCompare(A.path,"en")),m.sort((_,A)=>_.path.localeCompare(A.path,"en"));let Dy=Re===null?{provider:"physical-tree",...g?{physicalSelection:g}:{}}:{provider:"git",...Re.evidence?{gitSelection:Re.evidence}:{}},Hd=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Dy,createdAt:(t.now??new Date).toISOString(),complete:N===0,limits:i,...r?{policy:r.manifest}:{},entries:h,omitted:m,omittedCount:N,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:k}}:{}}),Os=Hd();for(;ou(Os)>i.maxManifestBytes;){if(m.filter(A=>!iu(A)).length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I=0;I<A;I+=1){let D=Fo(m);if(D===null)break;w(D)}}else if(h.length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let I of h.splice(-A))N+=1,T(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Os=Hd()}return Os}async function su(e,t,i={}){let n=(await Ie(e.projectRoot))?.native.snapshot??jl;return sv(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 Wo(e,t){let i=qP(e,t),r=ue(e,i);await z(r,i);try{let n=await Tm({root:r,file:i,maxBytes:tP,label:"Native baseline snapshot manifest"});return Ri(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as cR}from"crypto";import lR from"path";var Me=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{constants as zo,promises as at}from"node:fs";import ot from"node:path";import{TextDecoder as rR}from"node:util";import ZP from"path";var KP=Tr(Ki(),1);var tD=4*1024*1024;var YP=null;function XP(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function cv(e,t){return(...i)=>{let r=YP;if(r===null)return t(...i);let n=XP(`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 oD=cv("hookWritePolicy",async e=>(await Pl(e))?.hook??{allow_paths:[]});var lv=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Rn(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 Pn(e,t){let i=Rn(e,t);if(ZP.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 eR(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 uv(e){if(!e.run_id)return null;let t=Rn(e,"run_id"),i=Rn(e,"skill"),r=Rn(e,"skill_version"),n=Rn(e,"skill_hash"),a=Pn(e,"pending_ref"),o=Pn(e,"trajectory_ref"),s=Pn(e,"context_ref"),c=Pn(e,"artifacts_ref"),l=Pn(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:lv(e,"current_step"),iteration:u,pending:lv(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:eR(e)}}var nL=256*1024;var tR=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function iR(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=uv(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function cu(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=>!tR.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 iR(t)}var hr={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 Go(e,t){let i=ot.relative(e,t);return i===""||!ot.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ot.sep}`)}function nR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Jo(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function aR(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Uo(e,t,i){let r=Me[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=ot.resolve(e),a=ot.resolve(n,...r.slice(8).split("/"));if(!Go(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function dv(e){let t=await at.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await at.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function oR(e,t){let i=ot.resolve(e),r=ot.resolve(t);if(!Go(i,r))throw new Error("Native Run path is outside its change");let n=[await dv(i)],a=i;for(let o of ot.relative(i,r).split(ot.sep).filter(Boolean)){a=ot.join(a,o);let s;try{s=await dv(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Go(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function fv(e){for(let t of e){let i=await at.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!aR(t,i)||await at.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function sR(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 Ko(e,t,i,r,n){let a=await oR(e,ot.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await at.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=nR(o),c=await at.realpath(t);if(!Go(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?zo.O_RDONLY:zo.O_RDONLY|zo.O_NOFOLLOW|zo.O_NONBLOCK,u;try{u=await at.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),at.lstat(t),at.realpath(t)]);if(await fv(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Jo(s,d)||!Jo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await sR(u,i,r);await n?.beforeFinalCheck?.();let[h,m,S]=await Promise.all([u.stat(),at.lstat(t),at.realpath(t)]);if(await fv(a),!m.isFile()||m.isSymbolicLink()||S!==c||!Jo(s,h)||!Jo(s,m))throw new Error(`${r} changed while reading`);let y;try{y=new rR("utf-8",{fatal:!0}).decode(v)}catch(N){throw new Error(`${r} is not valid UTF-8`,{cause:N})}return{text:y,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function pv(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function lu(e){return cu(e)}async function mr(e,t){let i=Uo(e,"stateRef"),r=await Ko(e,i,hr.runStateBytes,"Native Run state",t);return r?cu(pv(r.text,"Native Run state")):null}async function Ai(e,t,i){let r=Uo(e,"trajectoryRef",t),n=await Ko(e,r,hr.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>hr.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${hr.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 hv(e,t,i){return(await Ko(e,Uo(e,"trajectoryRef",t),hr.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Yo(e,t,i){let r=await Ko(e,Uo(e,"checkpointRef",t),hr.checkpointBytes,"Native Run checkpoint",i);return r?pv(r.text,"Native Run checkpoint"):null}var uR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function uu(e){return cR("sha256").update(e).digest("hex")}function dR(e,t){if(!uR.test(t))throw new Error(`Invalid Native change name: ${t}`);return lR.join(U(e,t),"trajectory.jsonl")}function fR(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 pR(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 hR(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=fR(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(`
160
+ `)])}catch(d){if(!pR(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:uu(t),targetHash:uu(l),tailHash:uu(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function mR(e,t){let i=dR(e,t);await z(ue(e,i),i);let r=U(e,t),n=await hv(r,Me.trajectoryRef);return n===null?{status:"clean",file:i}:hR(i,Buffer.from(n))}async function mv(e,t){let i=await mR(e,t);return"inspection"in i?i.inspection:i}import{createHash as vR}from"node:crypto";import{promises as Xo}from"node:fs";import Tt from"node:path";var An=/^[a-f0-9]{64}$/u,vv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,gR=16*1024,fu=process.platform,wR=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function vr(e){return wR.has(e)}function Nv(e,t){let i=Tt.relative(e,t);return Tt.isAbsolute(i)||i===".."||i.startsWith(`..${Tt.sep}`)?null:i.replaceAll("\\","/")||"."}function bv(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function kv(e,t){if(e.length===0||bv(e)||e.includes("\\")||Tt.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=Tt.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function pu(e,t){return vR("sha256").update(`${e}
161
+ ${t}`).digest("hex")}async function gv(e,t){let i=await Xo.realpath(t),r=await Xo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=fu==="win32"?Tt.normalize(i).toLowerCase():i;return pu(e,`${n}
162
162
  ${r.dev}
163
163
  ${r.ino}
164
- ${r.birthtimeMs}`)}async function pv(e,t){let i=await Wo.realpath(t),r=await Wo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=uu==="win32"?It.normalize(i).toLowerCase():i;return du(e,n)}function eR(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 lu(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||vv(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function wv(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(lu(e.changeBranch,"Native workspace change branch"),lu(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 tR(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"||!dv.test(t.baseCommit)||typeof t.targetCommit!="string"||!dv.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");lu(t.targetBranch,"Native workspace Git target branch")}function zo(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"||!Pn.test(String(t.projectRootId))||!Pn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");eR(t.capturedAt),gv(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&&!Pn.test(String(t.projectRootPathId))||a&&!Pn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Pn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&tR(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(wv(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 iR(e,t){return It.join(G(e,t),"workspace.json")}function rR(e,t){let i=iR(e,t),r=ce(e,i),n=mv(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:gv(n,"Native workspace file ref")}}async function nR(e,t){try{let i=rR(e,t),r=await ie({root:i.root,ref:i.ref,maxBytes:Qx});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function yv(e,t){let i=Se(e.projectRoot),r={projectRoot:It.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await Tt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await xn({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function aR(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=mv(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Se(e.paths.projectRoot),r=i.isGitWorktree?Ni(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:Ni(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([fv("comet.native.workspace-project-root.v2",e.paths.projectRoot),fv("comet.native.workspace-native-root.v2",e.paths.nativeRoot),pv("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),pv("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&&wv(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:du("comet.native.workspace-session.v2",`${s}
164
+ ${r.birthtimeMs}`)}async function wv(e,t){let i=await Xo.realpath(t),r=await Xo.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=fu==="win32"?Tt.normalize(i).toLowerCase():i;return pu(e,n)}function yR(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 du(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||bv(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Sv(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(du(e.changeBranch,"Native workspace change branch"),du(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 NR(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"||!vv.test(t.baseCommit)||typeof t.targetCommit!="string"||!vv.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");du(t.targetBranch,"Native workspace Git target branch")}function Qo(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"||!An.test(String(t.projectRootId))||!An.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");yR(t.capturedAt),kv(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&&!An.test(String(t.projectRootPathId))||a&&!An.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!An.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&NR(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(Sv(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 bR(e,t){return Tt.join(U(e,t),"workspace.json")}function kR(e,t){let i=bR(e,t),r=ue(e,i),n=Nv(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:kv(n,"Native workspace file ref")}}async function SR(e,t){try{let i=kR(e,t),r=await re({root:i.root,ref:i.ref,maxBytes:gR});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ev(e,t){let i=Ee(e.projectRoot),r={projectRoot:Tt.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await jt(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 _n({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 ER(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Nv(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=Ee(e.paths.projectRoot),r=i.isGitWorktree?ki(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:ki(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([gv("comet.native.workspace-project-root.v2",e.paths.projectRoot),gv("comet.native.workspace-native-root.v2",e.paths.nativeRoot),wv("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),wv("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&&Sv(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:pu("comet.native.workspace-session.v2",`${s}
165
165
  ${c}
166
- ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return zo(p),p}async function Tt(e,t){let i=await nR(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(zo(i),i)}async function Jo(e){zo(e.identity);let t=await aR({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")),uu==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function xn(e){if(zo(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 Jo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Se(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 Nv(e,t){let i=await Tt(e,t);if(i===null)return null;let r=await xn({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Sv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],sR=new Set(Sv),Ev=new Set([...Sv,"minimum_runtime_version","revision"]),cR=new Set([...Ev,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),lR=new Set(["capability","operation","source","base_hash"]),uR=new Set(["shape","build","verify","archive"]),dR=new Set(["implicit","confirmed"]),fR=new Set(["pending","pass","fail"]),Ai="comet-state.yaml",pu=/^[a-f0-9]{64}$/u,Cv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Go=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"},Ri=class extends Error{constructor(i,r){super(i!==Pt||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"},Uo=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"},Rn=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"},Ko=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"},EB=ia("en");function _n(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Pv(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 In(e){if(!Cv.test(e))throw new Error(`Invalid Native change name: ${e}`)}function hR(e){if(!Cv.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function xv(e,t){if(e.length===0||ni.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function mR(e,t){let i=_n(e,`spec_changes[${t}]`);if(Pv(i,lR,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(hR(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"&&xv(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"||!pu.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"||!pu.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 vR(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 mu(e,t){if(Pv(e,t,Ai),typeof e.name!="string")throw new Error("Native change name is required");if(In(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"||!uR.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&&!dR.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(mR),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"||!fR.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"&&xv(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!vR(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function rr(e){let t=_n(e,Ai);if(t.schema!==Rt)throw new Error(`Expected ${Rt}`);return{schema:Rt,...mu(t,sR)}}function An(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function fu(e,t,i){if(e===null)return null;let r=typeof e=="string"?pR.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 gR(e){if(e==null)return null;if(typeof e!="string"||!pu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function wR(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 nr(e){let t=_n(e,Ai);if(t.schema!==xt)throw new Error(`Expected ${xt}`);if(An(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${xt} minimum_runtime_version must be 2`);return{schema:xt,minimum_runtime_version:2,revision:An(t.revision,"Native v2 revision"),...mu(t,Ev)}}function ti(e){let t=_n(e,Ai);if(t.schema!==Pt){if(t.schema===Rt||t.schema===xt){let o=t.schema===Rt?rr(t):nr(t);throw new Go(o.name,o.schema)}throw new Ri(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=An(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Ri(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=An(t.revision,"Native revision"),n=mu(t,cR),a=gR(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pt,minimum_runtime_version:3,revision:r,verification_protocol:wR(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:fu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:fu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:fu(t.partial_allowance,"Native partial_allowance","allowances")}}function yR(e){let t=_n(e,Ai);if(t.schema===Rt){let n=rr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema===xt){let n=nr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema!==Pt){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 Ri(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=An(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Ri(t.schema,i).message};let r=ti(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function he(e,t){In(t);let i=ni.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Yo(e,t){let i=G(e,t),r=ni.join(i,"schema-migration.json");await W(L(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await kv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Rv(e,t){let i=G(e,t),r=ni.join(i,"checkpoint-journal.json");await W(L(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await kv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function NR(e,t=ni.dirname(e)){let i=ni.relative(t,e).split(ni.sep).join("/"),r=await ie({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,hu.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 vu(e,t){let i=ni.join(he(e,t),Ai);await W(e.nativeRoot,i);let r=yR(await NR(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Yo(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 bR(e,r.state),r)}async function bR(e,t){if(await Do(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function mt(e,t){let i=await vu(e,t);if(i.status==="migration-required")throw new Go(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Ri(i.schema,i.minimumRuntimeVersion);return await Nv(e,t),i.state}var _v=["outcome","scope","nonGoals","acceptanceExamples"],kR=[..._v,"constraints","decisions","openQuestions","verificationExpectations"],SR=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],Iv={maxFileBytes:sn};function Tv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
167
- `).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 ER(e,t){let i=Av.resolve(e,...t.split(/[\\/]/u));if(!L(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await gu.realpath(e),n=await gu.realpath(i);if(!L(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await gu.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Tn(e){return{valid:e.length===0,findings:e}}async function wu(e,t){let i=[],r;try{r=(await ie({root:e,ref:t,maxBytes:Iv.maxFileBytes})).text}catch(o){return Tn([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of Tv(r))n.set(ta(o)??o,s);for(let o of kR)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of _v)(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}),Tn(i)}async function yu(e,t){let i=[],r;try{r=(await ie({root:e,ref:t,maxBytes:Iv.maxFileBytes})).text}catch(a){return Tn([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Tv(r))n.set(Od(a)??a,o);for(let a of SR)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 Tn(i)}function Xo(e,t){return Av.join(e.specsDir,t,"spec.md")}async function jv(e,t){let i=[],r=he(e,t.name);for(let n of t.spec_changes){let a=Xo(e,n.capability),o=null;try{await W(e.nativeRoot,a),o=await Kl(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 ER(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Tn(i)}import $v from"node:path";var CR="comet.native.contract.v1",PR="comet.native.acceptance-set.v1",Ov=/^[a-f0-9]{64}$/u,jn={maxAcceptanceCriteria:mn.maxCriteria};function Hv(e,t){let i=$v.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})||$v.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 Dv(e){return B("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
168
- `))}function xR(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(Ov))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(Ov))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Hv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Dv(e.markdown)},markdown:e.markdown}}function RR(e,t){return Bv(e.id,t.id)}function Bv(e,t){return e<t?-1:e>t?1:0}function Lv(e){let t=Hv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(xR).sort((d,f)=>Bv(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=Ll(e.briefMarkdown,t,jn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Vl(f,d.source,jn.maxAcceptanceCriteria-a.length)),a.push(...um(f,d.source,jn.maxAcceptanceCriteria-a.length)));if(a.sort(RR),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>jn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${jn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Dv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=B(PR,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:B(CR,u)}}var Qo={maxSpecs:64,maxFileBytes:sn,maxTotalBytes:4*1024*1024};async function pr(e){if(e.specChanges.length>Qo.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ie({root:e.changeDir,ref:e.briefRef,maxBytes:Qo.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 ie({root:e.changeDir,ref:n.source,maxBytes:Qo.maxFileBytes});if(i+=a.size,i>Qo.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:Lv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{randomUUID as AR}from"crypto";import{promises as Zo}from"fs";import Fv from"path";var Nu="comet.selection.v2",_R=16*1024;function bu(e){return Fv.join(e,".comet","current-change.json")}function IR(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Vv(e){return e===null||typeof e=="string"}function Mv(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(!IR(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&&!Vv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Nu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Nu)throw new Error(`current change selection schema must be ${Nu}`);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(!Vv(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 qv(e){let t;try{let r=bu(e),{bytes:n}=await Si(r,_R,{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",...Mv(t)}}async function Wv(e,t){let i=Mv(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=bu(e),n=`${r}.${AR()}.tmp`;await Zo.mkdir(Fv.dirname(r),{recursive:!0});try{await Zo.writeFile(n,`${JSON.stringify(i.selection,null,2)}
169
- `,"utf8"),await Zo.rename(n,r)}catch(a){throw await Zo.rm(n,{force:!0}),a}}import{promises as SA}from"node:fs";import Tu from"node:path";var Ru=Rr(Ji(),1);import{promises as tg}from"node:fs";import Me from"node:path";import{execFileSync as TR}from"node:child_process";var jR=3e4,$R=8*1024*1024,ku=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 OR(e,t){try{return TR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:jR,maxBuffer:$R,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new ku(e,t,r)}}function es(e,t){return OR(e,t).trim()}import Eu from"node:path";import{promises as zv}from"node:fs";var ts=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Su="comet.native.supervisor.v2",DR=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function BR(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 LR(e,t){return Eu.join(Zt(e,t),"supervisor")}function Jv(e,t){return Eu.join(LR(e,t),"state.json")}function Gv(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!==Su)throw new Error(`Native Supervisor state schema must be ${Su}`);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($n(t.integration.targetCommit,"Native Supervisor target commit"),$n(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&&$n(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($n(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 On(e,t){try{let i=await zv.readFile(Jv(e,t),"utf8"),r=JSON.parse(i);return Gv(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Cu(e,t){Gv(t),await zv.mkdir(e.changesRuntimeDir,{recursive:!0}),await Xe(Jv(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function $n(e,t){if(!DR.test(e))throw new Error(`${t} must be a Git commit`)}function VR(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Uv(e){$n(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:Su,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 Pu(e){let t=BR(e.parent),i=Ni(e.paths.projectRoot,t);if(!i)return null;let r=Ni(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Ui(e.paths.projectRoot).map(o=>Eu.resolve(o)).find(o=>Se(o).currentBranch===t);if(!n)return null;let a=Uv({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 VR(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Kv(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 Yv="children.yaml",is="comet.native.children.v1",hr="comet.native.children.v2",FR=hr,MR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xv=new Set(["schema","children"]),qR=new Set(["schema","acceptance_index","children"]),WR=new Set(["name","depends_on","covers"]),zR=new Set(["name","summary","depends_on"]),JR=new Set(["name","depends_on","covers"]);function ns(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function rs(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 Qv(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 xu(e,t){let i=Me.normalize(Me.resolve(e)),r=Me.normalize(Me.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function GR(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 Zv(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 ig(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 UR(e){let t=ns(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=ns(n,`Native children acceptance_index.${r}`);if(rs(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 KR(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 YR(e,t,i={}){let r=(0,Ru.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=ns(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==is&&a!==hr)throw rs(n,Xv,"Native children contract"),new Error(`Native children schema must be ${is} or ${hr}`);let o=a===is?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(rs(n,o==="indexed-v2"?qR:Xv,"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((d,f)=>{let p=ns(d,`Native child ${f}`);if(rs(p,o==="indexed-v2"?JR:o==="summary-v2"?zR:WR,`Native ${s} child fields (child ${f})`),typeof p.name!="string"||!MR.test(p.name))throw new Error(`Native child ${f} name is invalid`);let v=o==="summary-v2";if(v){if(typeof p.summary!="string"||p.summary.trim().length===0)throw new Error(`Native child ${p.name} summary must be a non-empty string`);if(p.summary.length>2e3)throw new Error(`Native child ${p.name} summary exceeds 2000 characters`)}return{name:p.name,summary:v?p.summary:null,depends_on:Qv(p.depends_on,`Native child ${p.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Qv(p.covers,`Native child ${p.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let f=d.depends_on.filter(p=>!u.has(p));if(f.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${f.join(", ")}`)}if(GR(c),a===FR){if(o==="indexed-v2"){let d=UR(n.acceptance_index);KR(d,t,i);let f=Object.keys(d);return Zv(c,f,f),{schema:hr,acceptance_index:d,children:c}}return{schema:hr,children:c}}return t&&Zv(c,t),{schema:is,children:c}}async function rg(e){let t=Me.join(e.changeDir,Yv);try{await tg.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await ie({root:e.changeDir,ref:Yv});return{contract:YR(i.text,e.acceptanceIds,e.validation),size:i.size}}function XR(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 QR(e){let t=XR(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 ng(e){try{let t=await ie({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return QR(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ag(e){return B("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 ZR(e){let t=Ui(e.projectRoot);t.some(r=>xu(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Me.resolve(n)))]){let n=await _e(r);n&&i.push({projectRoot:r,paths:await Ei(r,n.native.artifact_root),parent:xu(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function eA(e,t){let i=Me.join(e.paths.changesDir,t,"comet-state.yaml");try{return await wn(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function tA(e,t){let i;try{i=await tg.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=Me.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await wn(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function iA(e,t,i){let r=Me.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Me.sep}`))return null;let n=r.split(Me.sep).join("/");try{let a=(0,Ru.parseDocument)(es(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:gn(a.toJS({mapAsMap:!1}))}catch{return null}}function rA(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 eg(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Au(e){let t=Me.join(e.paths.changesDir,e.state.name),i=await ng(t),r=await rg({changeDir:t,validation:ig(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{}});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=ag({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n;if(r.contract.schema===hr){let m=await On(e.paths,e.state.name);if(!m){let N=e.state.workspace.target_branch??e.state.workspace.change_branch;if(N){let k=await Pu({paths:e.paths,parent:e.state.name,targetBranch:N,contract:r.contract});k&&(m=k,await Cu(e.paths,k))}}if(m){let N=Kv(m);return e.state.children_contract_hash!==n?{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(k=>({...k,message:"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(N=>[N.name,N])),y=r.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:o&&N.depends_on.every(k=>r.contract.children.filter(({name:E})=>E!==N.name).every(({name:E})=>E!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let N of y){if(N.status!=="ready")continue;S.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let s=await ZR(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await tA(m,c)){let N={...y,source:m,committedState:iA(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],N])}for(let y of c){let N=await eA(m,y);N&&u.set(y,[...u.get(y)??[],{source:m,state:N}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:k,committedState:E})=>k.parent&&E?.name===m.name&&eg(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let N=u.get(m.name)??[];N.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):N[0]&&d.set(m.name,rA(N[0].state,N[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),k=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&k?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:$,committedState:T})=>xu($.projectRoot,E.projectRoot)&&T?.name===C&&eg(T,a))):[],P,g=E?.message??null;E?.kind==="done"?(P=k?"done":"blocked",k||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(P=k&&b.length===0?"active":"blocked",k?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?P="blocked":(P=o&&k?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:P,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var xL=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var nA=/\b(Bearer|Basic)\s+[^\s"']+/giu,aA=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,oA=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,sA=/\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,cA=/("(?:[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,lA=/(["'])((?:[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,uA=/\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 qe(e){return e.replace(nA,"$1 [REDACTED]").replace(aA,"[REDACTED PRIVATE KEY]").replace(oA,"$1[REDACTED]@").replace(sA,"[REDACTED TOKEN]").replace(cA,'$1"[REDACTED]"').replace(lA,"$1$2$1$3$4[REDACTED]$4").replace(uA,"$1$2[REDACTED]")}import{promises as vA}from"node:fs";import og from"node:path";function as(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function os(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 vt(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 sg(e,t){return e===null?null:vt(e,t)}function cs(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 gA(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 wA(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ss(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function _u(e,t){if(e===null)return null;let i=vt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function Iu(e,t){let i=vt(e,t);if(!og.isAbsolute(i))throw new Error(`${t} must be absolute`);return og.resolve(i)}function yA(e,t){let i=`Native local checks[${t}]`,r=as(e,i);if(os(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)=>vt(l,`${i}.argv[${u}]`,!0)),a=ss(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=_u(r.startedAt,`${i}.startedAt`),s=_u(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=cs(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:vt(r.id,`${i}.id`),name:vt(r.name,`${i}.name`),operationId:vt(r.operationId,`${i}.operationId`),status:a,repeatable:wA(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:cs(r.executionCount,`${i}.executionCount`),argv:n,cwd:Iu(r.cwd,`${i}.cwd`),exitCode:gA(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:vt(r.log,`${i}.log`)}}function NA(e){let t="Native local execution state",i=as(e,t);if(os(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==So)throw new Error(`Native local execution schema must be ${So}`);let r=as(i.workspace,"Native local workspace");os(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=as(i.execution,"Native local execution");os(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=_u(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:vt(o.operationId,"Native local execution.operationId"),stage:ss(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ss(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:sg(o.executionId,"Native local execution.executionId"),status:ss(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:cs(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(yA);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:So,change:vt(i.change,"Native local change"),basedOnStateVersion:cs(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Iu(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Iu(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:sg(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function cg(e){let t;try{t=await vA.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 NA(i)}var EA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CA="comet-state.yaml",PA="state.json",eV=ia("en");function lg(e,t){if(!EA.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Tu.join(e.changesDir,t);if(!L(e.changesDir,i))throw new Error("Native change path escaped");return i}function ug(e,t){return Tu.join(lg(e,t),CA)}function xA(e,t){return Tu.join(Zt(e,t),PA)}async function ls(e,t){try{let i=await SA.readFile(ug(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function ju(e,t){return wn(ug(e,t))}async function dg(e){let t=await ju(e.paths,e.name),i=xA(e.paths,e.name);try{let r=await cg(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 lV=16*1024;async function fg(e){let t=await qv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(In(t.selection.change),t.selection)}async function pg(e,t){return tt(e,`select change ${t}`,async()=>{In(t),await ls(e,t)?await ju(e,t):await mt(e,t),await Wv(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function hg(e,t){let i=[],r=G(e,t.name),n=ei(r,Fe.stateRef),a;try{a=await dr(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=ei(r,a.trajectoryRef),s=await uv(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 xi(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=ei(r,a.checkpointRef);try{let u=await qo(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import y_ from"path";import{isDeepStrictEqual as Zu}from"util";var mr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var RA=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function AA(e,t){return e<t?-1:e>t?1:0}function _A(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"||!RA.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(AA)}function $u(e=[]){return _A(e,"Native repair failed check IDs",mr.maxFailedCheckIds,!0)}function mg(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function IA(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:mg(e.failedAcceptanceIds,t.failedAcceptanceIds)&&mg(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ou(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(IA(r,a))break;i+=1,r=a}return i}import Og from"node:path";import{createHash as Sg}from"node:crypto";import vg from"path";var Hu="comet.native.implementation-scope.v2",Eg="comet.native.content-snapshot-projection.v1",Hn="comet.native.content-snapshot-projection.v1",Cg="comet.native.implementation-scope.v2",TA="comet.native.unresolved-scope-id.v1",jA="comet.native.scope-detail-overflow.v1",$A="comet.native.snapshot-projection-overflow.v2",Vu=/^[a-f0-9]{64}$/u,Ii=1024*1024,OA=128,HA=128;function me(e,t){return e<t?-1:e>t?1:0}function Du(e){if(!Vu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function DA(e,t){return e===t?0:e===null?-1:t===null?1:me(e,t)}function oi(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=vg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||vg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Pg(e,t){return e==="."?e:oi(e,t)}function vr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function BA(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:oi(e.path,`${t} path`),hash:e.hash,size:vr(e.size,`${t} size`),type:"file"}}function LA(e,t){return{path:Pg(e.path,`${t} path`),size:e.size===null?null:vr(e.size,`${t} size`),type:e.type,reason:e.reason}}function VA(e,t){return me(e.path,t.path)||me(e.hash,t.hash)||e.size-t.size}function FA(e,t){return me(e.path,t.path)||me(e.reason,t.reason)||me(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Bn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
170
- `,"utf8")}function ai(e,t,i){let r=`${t}
171
- ${hn(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function MA(e){if(Bn(e)<=Ii)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Sg("sha256");a.update(`${$A}
172
- `),e.omissionOverflow&&ai(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,ai(a,"omission",f)},s=f=>{r+=1,n+=1,ai(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Bn(u)>Ii;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function Bu(e){let t=Pi(e),i=t.entries.map((n,a)=>BA(n,`Snapshot entry ${a}`));if(i.sort(VA),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)=>LA(n,`Snapshot omission ${a}`));return r.sort(FA),MA({schema:Eg,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 Ln(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:oi(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)=>me(i.path,r.path)||me(i.kind,r.kind))}function Vn(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function gg(e){return e?{hash:e.hash,size:e.size}:null}function Fu(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:me(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:gg(c),after:gg(l)})}}function xg(e,t){return{...e,attributedTo:t.filter(i=>Vn(i,e.path))}}function Mu(e){let t=Ln(e.declaredArtifacts),i=[];return Fu(e.baseline,e.current,r=>{i.push(xg(r,t))}),i}function jt(e,t){return{id:`scope:${B(TA,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function qA(e,t){let i=t.omitted.map(r=>jt({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(jt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(jt({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 wg(e,t){return qA(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Lu(e,t){return me(e.kind,t.kind)||me(e.source,t.source)||DA(e.path,t.path)||me(e.id,t.id)}function WA(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Lu)}function Rg(e){return[...new Set(e.map((t,i)=>oi(t,`Git path ${i}`)))].sort(me)}function yg(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 zA(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 Ag(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Rg(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:yg(e.baseCommit,"Native external drift base commit"),targetBranch:zA(e.targetBranch,"Native external drift target branch"),targetCommit:yg(e.targetCommit,"Native external drift target commit"),paths:t}}function _g(e){if(typeof e.contractHash!="string"||!Vu.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Ln(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Rg(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Ag(e.externalDrift)}}}function JA(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 Fu(e,t,p=>{let v=i.some(h=>Vn(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<OA){let h=xg(p,i),m=Bn(h);l+m<=Ii?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Ig(e,t){return jt({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 GA(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:vr(Number(t[1]),"Scope overflow change count"),unresolved:vr(Number(t[2]),"Scope overflow unresolved count"),unattributed:vr(Number(t[3]),"Scope overflow unattributed count")},r=_i(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Ig(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function UA(e){let t=Sg("sha256");t.update(`${jA}
173
- `);let i=0;Fu(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){ai(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Vn(o,n.path)&&(a+=1,ai(t,"change-attribution",o));ai(t,"change-end",{attributionCount:a}),a===0&&ai(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&&ai(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Tg(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=JA(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let P=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some($=>Vn($,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(P.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=B(Hn,e),c=B(Hn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[P,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=HA)break;l.push(jt({kind:"snapshot-omission",source:P,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${P} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...wg("baseline",e),...wg("current",t),...o.totalChanges===0&&a===null?[jt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let P=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>P.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!P.has(g))}},v=P=>{let g=o.candidates.slice(0,P.detailedChangeCount),w=g.filter(Je=>Je.attributedTo.length===0&&!u.has(Je.path)),C=o.totalChanges-g.length,$=o.totalUnattributed-w.length,T=d-P.detailedOmissionCount,de=$+T,X=[...w.map(Je=>jt({kind:"unattributed-change",source:"implementation-scope",path:Je.path,evidence:{after:Je.after,before:Je.before,changeKind:Je.kind}},`Changed path is not covered by a declared artifact: ${Je.path}`)),...l.slice(0,P.detailedOmissionCount),...f,...de>0?[Ig(P.overflowHash,{changes:C,unattributed:$,unresolved:de})]:[]],J=WA(X),ct=P.includeGitAdvisory?p():void 0;return{schema:Hu,contractHash:r,baselineProjectionRef:Du(s),baselineProjectionHash:s,currentProjectionRef:Du(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:J,noCodeReason:a,...ct?{gitAdvisory:ct}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let P=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(Bn({...P,scopeHash:y})<=Ii)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>h||d>m?UA({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:k}),b={...E,scopeHash:B(Cg,E)};if(Bn(b)>Ii)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function qu(e){let t=Bu(e.baseline),i=Bu(e.current),r=_g(e);return{authority:r,baseline:t,current:i,scope:Tg(t,i,r)}}var KA=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function gt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wt(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 _i(e,t){if(typeof e!="string"||!Vu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ng(e,t,i){let r=Du(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function us(e,t){let i=gt(e,"Native snapshot projection");if(wt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Eg)throw new Error("Native snapshot projection schema is invalid");let r=Pi({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=Bu(r);if(B(Hn,i)!==B(Hn,n))throw new Error("Native snapshot projection is not canonical");let a=B(Hn,n);if(t!==void 0&&_i(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Wu(e,t){let i=gt(e,`Declared artifact ${t}`);if(wt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:oi(i.path,`Declared artifact ${t} path`),kind:i.kind}}function bg(e,t){if(e===null)return null;let i=gt(e,t);return wt(i,["hash","size"],[],t),{hash:_i(i.hash,`${t} hash`),size:vr(i.size,`${t} size`)}}function kg(e,t){let i=gt(e,`Implementation change ${t}`);if(wt(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(Wu),n=Ln(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=bg(i.before,`Implementation change ${t} before`),o=bg(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:oi(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function YA(e,t){let i=gt(e,`Unresolved scope ${t}`);wt(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"?Pg(i.path,`Unresolved scope ${t} path`):oi(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Dn(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)=>oi(n,`${t} ${a}`)),r=[...new Set(i)].sort(me);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function jg(e){let t=gt(e,"Native implementation external drift");if(wt(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=Dn(t.paths,"Native external drift paths");return Ag({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function ds(e){let t=gt(e,"Native implementation scope"),i=[...KA].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(wt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Hu)throw new Error("Native implementation scope schema is invalid");let r=_i(t.contractHash,"Implementation scope contractHash"),n=_i(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Ng(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=_i(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Ng(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(Wu);if(JSON.stringify(c)!==JSON.stringify(Ln(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(kg),u=[...l].sort((w,C)=>me(w.path,C.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(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>Vn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(kg),p=t.externalDrift===void 0?void 0:jg(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(YA),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:GA(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,k=[...h.map(w=>jt({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+(y?.changes??0)===0&&N===null?[jt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Lu))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(k.sort(Lu))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=gt(t.gitAdvisory,"Implementation scope Git advisory");if(wt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Dn(w.changedPaths,"Git changed paths"),$=Dn(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Dn(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),de=[...$,...T].sort(me);if(JSON.stringify(de)!==JSON.stringify(C)||T.some(X=>l.some(J=>J.path===X)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:$,pathsAbsentFromSnapshotChanges:T}}let P={schema:Hu,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=_i(t.scopeHash,"Implementation scope scopeHash");if(B(Cg,P)!==g)throw new Error("Implementation scope content hash mismatch");return{...P,scopeHash:g}}function XA(e){let t=gt(e,"Native implementation scope authority");if(wt(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(Wu);if(JSON.stringify(i)!==JSON.stringify(Ln(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=Dn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:jg(t.externalDrift),a=_g({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 Fn(e){let t=gt(e,"Native implementation scope bundle");wt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=XA(t.authority),r=us(t.baseline),n=us(t.current),a=ds(t.scope),o=Tg(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 $g(e){let t=ds(e.scope);return Fn({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})}var Dg=/^[a-f0-9]{64}$/u;var QA="comet.native.acceptance-trace.v2",ZA="comet.native.partial-allowance.v1",e_="comet.native.verification-evidence.v2";function $t(e,t){if(!Dg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Bg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Lg(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 zu(e,t,i=2e3){let r=qe(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Mn(e,t){let i=Og.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})||Og.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 t_(e,t,i){let r=Mn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=dt(r),a=r.toLowerCase(),o=i?Mn(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 Ju(e){let t=Mn(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 gr(e,t){return e<t?-1:e>t?1:0}function fs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ps(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 Vg(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 Hg(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 i_(e){let t=fs(e,"Native acceptance trace");if(ps(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"||!Dg.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=Mn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=fs(o,`Native acceptance trace entry ${s}`);if(ps(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=>Ju(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(gr))||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:Mn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:zu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>gr(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=$t(t.traceHash,"Native acceptance trace hash");if(B(QA,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Fg(e){let t=fs(e,"Native partial allowance");if(ps(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(gr))||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:Lg(t.change),scopeHash:$t(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:zu(t.reason,"Partial allowance reason"),confirmedSummary:zu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Bg(t.sourceRevision),confirmedAt:Vg(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=$t(t.allowanceHash,"Native partial allowance hash");if(B(ZA,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Gu(e){let t=fs(e,"Native verification evidence");if(ps(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=$t(t.implementationScopeHash,"Native verification implementation scope hash"),r=i_(t.acceptanceTrace),n=$t(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:$t(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Ju(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(gr)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(gr);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=>Ju(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(gr)))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:Lg(t.change),sourceRevision:Bg(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:$t(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Hg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:t_(t.reportRef,"Native verification report ref"),reportHash:$t(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Hg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Vg(t.createdAt,"Native verification timestamp")},d=$t(t.envelopeHash,"Native verification envelope hash");if(B(e_,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Uu(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 Mg="repairStagnation",je={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},n_=/^[a-f0-9]{64}$/u;var a_=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),o_=["data","runId","sequence","timestamp","type"],qg=["disposition","overrideSummaryHash","signatureHash"],s_=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Wg=12;function Yu(e,t){return e<t?-1:e>t?1:0}function zg(e,t,i){let r=Object.keys(e).sort(Yu);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function hs(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 qn(e,t){if(typeof e!="string"||!n_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function c_(e){if(!Array.isArray(e)||e.length>mr.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(Yu)}function Jg(e){if(typeof e!="string"||e.length===0||e.length>je.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 Ku(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>je.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>je.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>je.maxTextCharacters&&(!n||e.length>je.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>je.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>je.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Ku(s,t+1,i,`${r}[${c}]`));return}let a=hs(e,r),o=Object.keys(a);if(o.length>je.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>je.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>je.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Ku(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function l_(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 u_(e,t,i){let r=hs(e,`Native repair trajectory event ${t+1}`);if(zg(r,o_,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(l_(r.timestamp),typeof r.type!="string"||!a_.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(Jg(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 Ku(r.data,0,n,"Native trajectory event data"),hs(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Xu(e){let t=hs(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Yu),r=i.length===qg.length&&i.every((l,u)=>l===qg[u]);r||zg(t,s_,"Native repair trajectory projection");let n=qn(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:qn(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=qn(t.contractHash,"Native repair trajectory contract hash"),s=c_(t.failedAcceptanceIds),c=$u(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 d_(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 f_(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??Wg;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ou({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<mr.warningAtConsecutiveFailures?"continue":a<mr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function p_(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??Wg;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 Gg(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>je.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Jg(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=u_(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>je.maxTotalDataNodes||c>je.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?qn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?qn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Mg)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Xu(f[Mg]);if(d_(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),f_(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");p_(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>mr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function Ug(e){return Gg(e).history}function Kg(e){let t=Gg(e).latestProjection;return t?{...t}:null}var wr={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:[]},Qu=U("comet-native-runtime:v3:scope-reopen"),h_=[{skillVersion:"3",skillHash:U("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:U("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:U("comet-native-runtime:v1")}];function Yg(e){return e.skillVersion===wr.definition.metadata.version&&e.skillHash===Qu||h_.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function Xg(e){return U(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 iw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],N_=new Set(iw),rw=new Set([...iw,"minimum_runtime_version","revision"]),b_=new Set([...rw,"operation"]),k_=512*1024,ed=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),S_=new Set([...ed,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),td=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 rd(e,t){return y_.join(G(e,t),"transition.json")}function vs(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function nd(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 ms(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function id(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=>!S_.has(u)),a=[...ed].find(u=>!Object.hasOwn(i,u)),o=ed.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(Uu(i.summary,"Native transition journal event summary"),qe(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&&(Uu(i.noCodeReason,"Native transition journal event no-code reason"),qe(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")?Xu(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 E_(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 id({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return id(e,t)}function ad(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?E_(e.eventData,e.evidenceHash):id(e.eventData,e.evidenceHash),n=su(e.nextRun),a=e.previousRun===null?null:su(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function Qg(e,t,i=!1){if(e.skill!==wr.definition.metadata.name||(i?!Yg(e):e.skillVersion!==wr.definition.metadata.version||e.skillHash!==Qu)||e.orchestration!==wr.definition.orchestration.mode||e.pendingRef!==Fe.pendingRef||e.trajectoryRef!==Fe.trajectoryRef||e.contextRef!==Fe.contextRef||e.artifactsRef!==Fe.artifactsRef||e.checkpointRef!==Fe.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Zg(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 ew(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 od(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(Qg(o,"next Run",r||a!==null),ew(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(Qg(a,"previous Run",!0),ew(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(!Zu(Zg(a),Zg(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function C_(e,t,i){return U(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function nw(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function tw(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function sd(e,t,i,r,n=!1){let a=i.eventData,o=tw(e),s=tw(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&&Zu(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&&Zu(e.spec_changes,t.spec_changes),l=Xg({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=C_(e.name,a.summary,t.spec_changes),l=U(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!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 P_(e,t){let i=vs(e);if(nd(i,b_),i.schema!==tr)throw new Error(`Expected Native transition schema ${tr}`);let r=ms(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 ${tr} minimum_runtime_version must be ${3}`);let n=ms(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=ad(i,t),o=ti(i.previousState),s=ti(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(sd(o,s,a,i.operation),od(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:tr,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 x_(e,t){let i=vs(e);if(nd(i,N_),i.schema!==yn)throw new Error(`Expected Native transition schema ${yn}`);let r=ad(i,t,!0),n=rr(i.previousState),a=rr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return sd(n,a,r,nw(n,a,r.eventData),!0),od(n,a,r,!0),{schema:yn,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 R_(e,t){let i=vs(e);if(nd(i,rw),i.schema!==ir)throw new Error(`Expected Native transition schema ${ir}`);if(ms(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${ir} minimum_runtime_version must be 2`);let n=ms(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=ad(i,t,!0),o=nr(i.previousState),s=nr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(sd(o,s,a,nw(o,s,a.eventData),!0),od(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:ir,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 A_(e,t){let i=vs(e);if(i.schema===tr)return{status:"current",journal:P_(i,t)};if(i.schema===yn)return{status:"migration-required",journal:x_(i,t)};if(i.schema===ir)return{status:"migration-required",journal:R_(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function __(e,t){let i=rd(e,t),r=ce(e,i);await W(r,i);try{let n=await pt({root:r,file:i,maxBytes:k_,label:`Native transition journal ${t}`});return A_(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function aw(e,t){let i=await __(e,t);if(!i)return null;if(i.status==="migration-required")throw new td(t);return i.journal}var I_=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function T_(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function j_(e){return e?e.map(T_).join(" "):null}function $_(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 We(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 O_(e){return e.map(t=>We(t,[],null))}function H_(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[We("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(We("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(We("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),We("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(We("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(We("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),We("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ve(e,t){let i=t.commandArgs===void 0?$_(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?j_(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??O_(t.requiredInputs??[])}}function gs(e){let i=(e.findings??[]).filter(d=>!fr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||I_.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 ve(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ve(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[We("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ve(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ve(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ve(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ve(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[We("summary",["--summary"],"<summary>")]});if(n)return ve(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 ve(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[We("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ve(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ve(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ve(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ve(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"),ve(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[We("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ve(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ve(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=H_(e.state);return ve(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Wn from"path";var ow=8,D_={"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 B_(e){let t=D_[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"}:fr(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 L_(e,t,i){if(!i.path)return null;let r;if(Wn.isAbsolute(i.path)?r=Wn.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Wn.resolve(he(e,t.name),...i.path.split(/[\\/]/u)):r=Wn.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!L(e.projectRoot,r))return null;let n=Wn.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function V_(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 cd(e){return e.findings.map(t=>{let i=B_(t.code);return{code:t.code,message:t.message,severity:i.severity,path:L_(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:V_(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 ld(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,ow),truncated:t.length>ow}}import yr from"path";var ci={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Nr=/^[a-f0-9]{64}$/u;function ws(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ys(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 si(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 sw(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ud(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function F_(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||yr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=yr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function cw(e,t){return yr.join(G(e,t),"checkpoints","progress.json")}function zn(e,t){return yr.join(G(e,t),"checkpoint-journal.json")}function lw(e,t,i){if(!Nr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return yr.join(G(e,t),"checkpoints","manifests",`${i}.json`)}function M_(e){if(!Nr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function dd(e,t,i){let r=await pt({root:e,file:t,maxBytes:ci.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function q_(e,t){let i=ws(e,`checkpoint manifest artifact ${t}`);ys(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=F_(si(i.path,`checkpoint artifact ${t} path`,4096)),n=dt(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Nr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:ud(i.size,`checkpoint artifact ${t} size`)}}function fd(e,t){let i=ws(e,"Native checkpoint manifest");if(ys(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>ci.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(q_),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=ud(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>ci.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 uw(e){return U(JSON.stringify(fd(e,e.change)))}function dw(e,t){let i=ws(e,"Native progress checkpoint");if(ys(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=sw(i.previousRevision,"Native checkpoint previousRevision"),a=sw(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=si(i.manifestHash,"Native checkpoint manifestHash",64);if(!Nr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=M_(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=si(i.inputHash,"Native checkpoint inputHash",64);if(!Nr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=si(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=ud(i.artifactCount,"Native checkpoint artifactCount");if(u>ci.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=si(i.summary,"Native checkpoint summary"),f=si(i.nextAction,"Native checkpoint nextAction");if(qe(d)!==d||qe(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:si(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 W_(e,t){let i=ws(e,"Native checkpoint journal");if(ys(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=ti(i.previousState),n=ti(i.nextState),a=dw(i.checkpoint,t),o=fd(i.manifest,t),s=si(i.inputHash,"Native checkpoint journal inputHash",64),c=U(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Nr.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(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!==uw(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 z_(e,t,i){let r=yr.resolve(e.projectRoot,...t.split("/"));if(!L(e.projectRoot,r)||L(e.nativeRoot,r)||L(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=hl(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await pt({root:e.projectRoot,file:r,maxBytes:ci.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 J_(e,t){let i=cw(e,t),r=ce(e,i);await W(r,i);try{return dw(await dd(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function G_(e,t,i){let r=lw(e,t,i),n=ce(e,r);await W(n,r);let a=await dd(n,r,"Native checkpoint manifest"),o=fd(a,t);if(fw(e,o),uw(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function pd(e,t){let i=zn(e,t),r=ce(e,i);await W(r,i);try{let n=W_(await dd(r,i,"Native checkpoint journal"),t);return fw(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function fw(e,t){for(let i of t.artifacts){let r=hl(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function pw(e){let t;try{t=await J_(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:cw(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 G_(e.paths,e.name,t.manifestHash);let a=U(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 z_(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:lw(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var hw=240,mw=8,Ns=50;function vw(e){let t=Array.from(e);return t.length<=hw?e:`${t.slice(0,hw-1).join("")}…`}function U_(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function K_(e){let t=[...new Set(e.map(U_))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,mw),reasonCount:e.length,codesTruncated:t.length>mw};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Ns),reasonsTruncated:e.length>Ns}}}async function gw(e){let t=null;try{let s=await pd(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:zn(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:zn(e.paths,e.state.name)}}let i=await pw({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=K_(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ci.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:vw(i.checkpoint.summary),nextAction:vw(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:ci.maxArtifacts}}import{promises as HT}from"node:fs";import Xw from"node:path";import ww from"node:path";var Y_="comet.native.archive-preflight.v1",X_="comet.native.archive-preflight.v1",Q_="comet.native.archive-operation.v1",Z_=/^[a-f0-9]{64}$/u,yw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function bs(e,t){return e<t?-1:e>t?1:0}function tI(e,t){if(typeof e!="string"||!Z_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ot(e,t){return e===null?null:tI(e,t)}function iI(e,t){let i=ww.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||ww.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 rI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function nI(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 aI(e,t){if(!yw.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=Ot(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Ot(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Ot(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 oI(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:Ot(e.contractHash,"Native archive contract hash"),acceptanceHash:Ot(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ot(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ot(e.reportHash,"Native archive report hash"),envelopeHash:Ot(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ot(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 sI(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!eI.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(bs);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function cI(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(bs)}function Nw(e){if(!yw.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(aI).sort((l,u)=>bs(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:B(Q_,l)})),r=oI(e.evidence),n=nI(e.workspace),a=[...new Set([...sI(e.findingCodes??[]),...cI({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(bs),o=rI(e.revision),s=iI(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:Y_,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:B(X_,c)}}import{createHash as lI}from"node:crypto";import bw from"node:path";var uI="comet.native.conflict-radar.v1",Ce=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}),dI="comet.native.conflict-radar.v1",fI="comet.native.conflict-radar-signals.v1",pI=/^[a-f0-9]{64}$/u,Ew=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hI=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),mI=new Set(["capability","operation","baseHash"]),vI=new Set(["path","kind"]);function br(e,t){return e<t?-1:e>t?1:0}function hd(e){return Buffer.byteLength(e,"utf8")}function md(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 vd(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(hd(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function gI(e,t){let i=vd(e,t,Ce.maxArtifactPathBytes),r=bw.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)||bw.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 Cw(e,t){if(typeof e!="string"||!pI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function wI(e,t){let i=md(e,mI,t),r=vd(i.capability,`${t} capability`,Ce.maxCapabilityBytes);if(!Ew.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:Cw(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function yI(e,t){let i=md(e,vI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:gI(i.path,`${t} path`),kind:i.kind}}function NI(e,t){let i=md(e,hI,`Conflict radar change ${t}`),r=vd(i.name,`Conflict radar change ${t} name`,Ce.maxNameBytes);if(!Ew.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>Ce.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>Ce.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>wI(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>br(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>yI(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>br(c.path,l.path)||br(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:Cw(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function bI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Ce.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(NI).sort((n,a)=>br(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)>Ce.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Ce.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function kI(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 SI(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 EI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function CI(e,t){let i=[],r=lI("sha256").update(`${fI}
174
- [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(hn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Ce.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(kI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=SI(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:EI(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function kw(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function PI(e,t){return kw(e.classification)-kw(t.classification)||br(e.left,t.left)||br(e.right,t.right)}function Sw(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:uI,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 Pw(e){let t=bI(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(CI(t[s],t[c]));i.sort(PI);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=B(dI,{changes:t,relationships:r}),a=i.slice(0,Ce.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Sw(t,i,a,n);for(;a.length>0&&hd(JSON.stringify(o))>Ce.maxSerializedBytes;)a=a.slice(0,-1),o=Sw(t,i,a,n);if(hd(JSON.stringify(o))>Ce.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as aT}from"node:crypto";import{promises as st}from"node:fs";import yt from"node:path";import xw from"node:path";var Rw="comet.native.check-receipt.v1",xI="comet.native.check-receipt.v1",kr="scoped-text-safety",gd=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),RI=/^[a-f0-9]{64}$/u,AI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_I="comet.native.checker-policy.v1",II="comet.native.check-input.v1",TI=2048,Aw=B(_I,{policy:kr,version:gd,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),jI=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),_w=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Tw=["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"],$I=new Set(Tw);function li(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ui(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 Ht(e,t){if(typeof e!="string"||!RI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $e(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function jw(e,t){let i=$e(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Iw(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 OI(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>TI||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=xw.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||xw.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function HI(e){let t=li(e,"Native check receipt checker");ui(t,["policy","version","hash","limits"],"Native check receipt checker");let i=li(t.limits,"Native check receipt limits");if(ui(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==kr||t.version!==gd||t.hash!==Aw||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:kr,version:gd,hash:Aw,limits:{...Pe}}}function DI(e){let t=li(e,"Native check receipt contract");return ui(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Ht(t.expectedHash,"Native check expected contract hash"),beforeHash:Ht(t.beforeHash,"Native check before contract hash"),afterHash:Ht(t.afterHash,"Native check after contract hash")}}function BI(e){let t=li(e,"Native check receipt implementation");return ui(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Ht(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Ht(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Ht(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Ht(t.afterSnapshotHash,"Native check after snapshot hash")}}function LI(e,t){let i=li(e,`Native check batch ${t}`);ui(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:$e(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:$e(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:$e(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:$e(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:$e(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:$e(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Pe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Pe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function VI(e){let t=li(e,"Native check receipt counts");ui(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:$e(t.filesSelected,"Native check filesSelected"),filesScanned:$e(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:$e(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:$e(t.bytesScanned,"Native check bytesScanned"),issueCount:$e(t.issueCount,"Native check issueCount"),recordedIssueCount:$e(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(LI):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Pe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function FI(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||_w.indexOf(e.kind)-_w.indexOf(t.kind)}function MI(e){if(!Array.isArray(e)||e.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=li(r,`Native check issue ${n}`);if(ui(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!jI.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:OI(a.path,`Native check issue ${n} path`),line:jw(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(FI);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function qI(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!$I.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Tw.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 WI(e){return B(II,e)}function $w(e){let t=li(e,"Native check receipt");if(ui(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Rw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!AI.test(t.change))throw new Error("Native check receipt change name is invalid");let i=jw(t.sourceRevision,"Native check source revision"),r=HI(t.checker),n=DI(t.contract),a=BI(t.implementation),o=WI({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Ht(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=Iw(t.startedAt,"Native check receipt startedAt"),c=Iw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=VI(t.counts),u=MI(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=qI(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>Pe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Pe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:Rw,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=Ht(t.receiptHash,"Native check receipt content hash");if(B(xI,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var yd="comet.native.verification-receipt.v3",zI=yd,JI="comet.native.declared-artifacts.v1",GI=/^[a-f0-9]{64}$/u,UI=/^acceptance-[a-f0-9]{64}$/u,KI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,YI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,XI=4096,QI=256,ZI=1024;function Sr(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 di(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 Dt(e,t){if(typeof e!="string"||!GI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ot(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=qe(e).trim();if(!i||i.length>XI||i!==e.trim())throw new Error(`${t} is invalid`);return i}function wd(e,t){let i=ot(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 Jn(e,t,i=ot,r=!1,n=QI){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 eT(e,t){if(typeof e!="string"||!UI.test(e))throw new Error(`${t} is invalid`);return e}function tT(e){let t=Sr(e,"Native verification receipt bindings");if(di(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!KI.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:Dt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Dt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Dt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Dt(t.artifactHash,"Native verification receipt artifact hash")}}function iT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=YI.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function rT(e,t,i,r){let n=Sr(t,`Native ${e} evidence`);if(e==="automated-check"){if(di(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=wd(n.startedAt,"Native automated-check start time"),o=wd(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=Sr(n.worktree,"Native automated-check worktree");if(di(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=Sr(n.afterFence,"Native automated-check after fence");if(di(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:ot(n.executable,"Native automated-check executable"),args:Jn(n.args,"Native automated-check arguments",ot,!0),cwd:ot(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:ot(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Dt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Dt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Dt(n.outputHash,"Native automated-check output hash"),outputSummary:ot(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){di(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=iT(n.checkReceiptRef);if(Dt(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Jn(n.subjects,"Native static inspection subjects",ot,r==="required-check"),rule:ot(n.rule,"Native static inspection rule"),resultSummary:ot(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return di(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Jn(n.steps,"Native manual evidence steps"),observations:Jn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function nT(e){let t=Sr(e,"Native verification receipt");if(di(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=ot(t.actor,"Native verification receipt actor"),o=Jn(t.acceptanceIds,"Native receipt acceptance IDs",eT,r==="required-check",ZI).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:yd,kind:i,role:r,status:n,bindings:tT(t.bindings),acceptanceIds:o,actor:a,issuedAt:wd(t.issuedAt,"Native verification receipt issue time"),evidence:rT(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==kr||s.actor!==`native-runtime:${kr}`))throw new Error("Native required check policy identity is invalid");return s}function Ow(e){let t=Sr(e,"Native verification receipt");if(di(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==yd)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=nT(r),a=Dt(t.receiptHash,"Native verification receipt hash");if(B(zI,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Nd(e){return B(JI,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Lw=/^[a-f0-9]{64}$/u,Er=Ii,iM=3*Er;function bd(e,t){let i=yt.relative(e,t);return i===""||!yt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${yt.sep}`)}function oT(e,t){return F({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ks(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ae(i,r)?F(i,r):F(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Hw(e){let t=await st.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await st.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sT(e,t){let i=yt.resolve(e),r=yt.resolve(t);if(!bd(i,r))throw new Error("Native evidence path is outside its change");let n=[await Hw(i)],a=i;for(let o of yt.relative(i,r).split(yt.sep).filter(Boolean)){a=yt.join(a,o);let s=await Hw(a);if(!bd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Dw(e){for(let t of e){let i=await st.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!oT(t,i)||await st.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function cT(e,t,i={}){let r=await sT(t,yt.dirname(e));await i.afterParentChainCaptured?.();let n=await st.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await st.realpath(e);if(!bd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await st.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),st.lstat(e),st.realpath(e)]);if(await Dw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ks(s,n)||!ks(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Er)throw new Error(`Native evidence document exceeds ${Er} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=Er+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Er)throw new Error(`Native evidence document exceeds ${Er} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),st.lstat(e),st.realpath(e)]);if(await Dw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!ks(s,p)||!ks(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 Vw(e,t){if(!Lw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function lT(e,t,i,r,n){if(!Lw.test(i))throw new Error("Native report evidence hash is invalid");let a=await Ti({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"||aT("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 Cr(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 uT(e,t,i,r,n){let a=Vw(i,r);return n?yt.join(n,...a.split("/")):ei(G(e,t),a)}async function Ti(e){let t=uT(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??ce(e.paths,t);return await W(i,t),cT(t,i,e.hooks)}function Bw(e,t){return us(e,t)}function dT(e,t){let i=ds(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function fT(e,t,i){let r=Fg(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function pT(e,t,i){let r=Gu(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function hT(e,t,i,r=!1,n){let a=await Ss(e,t,i.implementationScopeRef,void 0,n);if(r&&await lT(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 Fw(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 Gn(e,t,i,r,n){let a=Cr(i,"scopes"),o=dT(await Ti({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Cr(o.baselineProjectionRef,"snapshots"),c=Cr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ti({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Bw(d,s)),Ti({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Bw(d,c))]);return $g({baseline:l,current:u,scope:o})}async function Ss(e,t,i,r,n){return(await Gn(e,t,i,r,n)).scope}async function Fw(e,t,i,r,n){let a=Cr(i,"allowances");return fT(await Ti({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Un(e,t,i,r,n){let a=Cr(i,"receipts"),o=Ow(await Ti({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 Pr(e,t,i,r,n){let a=Cr(i,"verifications"),o=pT(await Ti({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await hT(e,t,o,!1,n),o}var mT=4096;async function vT(e,t=Ce.maxChanges){try{let i=await Nn({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 Mw(e,t){let i=await mt(e,t),[r,n]=await Promise.all([i.implementation_scope?Ss(e,t,i.implementation_scope):null,Tt(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 Es(e,t,i={}){let n=(await vT(e,mT)).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 Mw(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await Mw(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Pw([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as xT}from"node:child_process";import{promisify as RT}from"node:util";import{constants as kd,promises as ze}from"node:fs";import xr from"node:path";var wT=/^[a-f0-9]{64}$/u,yT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Kn=512*1024;function NT(e,t){return F({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cs(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return Ae(i,r)?F(i,r):F(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bT(e,t){let i=xr.resolve(e),r=xr.resolve(t);if(!L(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...xr.relative(i,r).split(xr.sep).filter(Boolean)]){o&&(a=xr.join(a,o));let s=await ze.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await ze.realpath(a);if(n.length>0&&!L(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 Ww(e){for(let t of e){let i=await ze.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!NT(t,i)||await ze.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function kT(e){if(!wT.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function ST(e){let t=yT.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function ET(e,t,i){return ei(G(e,t),kT(i))}async function CT(e,t,i){let r=await bT(i,xr.dirname(e)),n=await ze.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Kn)throw new Error(`Native check receipt exceeds ${Kn} bytes`);let[a,o]=await Promise.all([ze.realpath(t),ze.realpath(e)]);if(!L(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":kd.O_RDONLY|kd.O_NOFOLLOW|kd.O_NONBLOCK,c=await ze.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(),ze.lstat(e),ze.realpath(e)]);if(await Ww(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Cs(n,l)||!Cs(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Kn+1-p,N=await c.read(v,0,Math.min(v.length,y),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>Kn)throw new Error(`Native check receipt exceeds ${Kn} bytes`);f.push(Buffer.from(v.subarray(0,N.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),ze.lstat(e),ze.realpath(e)]);if(await Ww(r),!m.isFile()||m.isSymbolicLink()||S!==o||!L(a,S)||!Cs(l,h)||!Cs(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function zw(e,t,i){let r=ST(i),n=G(e,t),a=ET(e,t,r),o=ce(e,a);await W(o,a);let s=$w(await CT(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var Yn=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var KM=64*1024;var YM=3600*1e3;var XM=RT(xT);var AT=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Jw(e,t){let i=[];for(let r of AT){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 Gw(e){if(e.receipt.kind!=="static-inspection")return null;let t=await zw(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 fi=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 _T(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 IT(e){let t=_T(e.bundle.baseline),i=await au(e.paths,t,{origin:"explicit",now:e.now});return qu({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 Kw(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Gn(e.paths,e.state.name,e.state.implementation_scope),i=await pr({changeDir:he(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await IT({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 Yw(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Kw(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 TT(e){let t=await ie({root:he(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:fm(t.text)}}function jT(e){let{receipt:t,implementationScope:i}=e,r=[],n=Mu({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 $T(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:Nd(e.implementationScope.scope.declaredArtifacts)}}async function Uw(e){let t=await Un(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Jw(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 fi([{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 Gw({paths:e.paths,state:e.state,receipt:t});if(n){let a=jT({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 OT(e){let t=$T({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Uw({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof fi)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 Uw({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof fi)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 fi(i)}function Sd(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Ed(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Sd(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Kw(e),Pr(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Sd(e.state.verification_result,"stale"),envelope:null};let r=await TT({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 OT({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:Sd(e.state.verification_result,"invalid"),envelope:null}}}function DT(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Qw(e){try{return await HT.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function BT(e,t){try{return(await ie({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function LT(e,t,i){let r=Xo(e,i.capability);if(!L(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Xw.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await BT(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ie({root:he(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 VT(e,t){return Qw(rd(e,t))}async function Cd(e){let t=e.now??new Date,i=await mt(e.paths,e.name),r=await Tt(e.paths,e.name),n=await _e(e.paths.projectRoot),a=DT(i.name,t),o=Xw.resolve(e.paths.nativeRoot,...a.split("/"));if(!L(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>LT(e.paths,i.name,v))),Ed({paths:e.paths,state:i,now:t}),Es(e.paths,i.name),Yo(e.paths,i.name),Rv(e.paths,i.name),VT(e.paths,i.name),Qw(o)]);return Nw({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function FT(e,t){let i=G(e,t.name),r=await dr(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 qo(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 xi(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function MT(e,t){let i=await FT(e,t);return{committed:i,latest:Kg(i),history:Ug(i)}}async function Zw(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await MT(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 aW=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function WT(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function zT(e){return(await fg(e))?.change??null}function JT(e,t,i=!1,r){return gs({state:e,archiveReady:t,evidenceRetreat:i}).command}async function GT(e,t){let i=he(e,t.name),r=[...(await wu(i,t.brief)).findings,...(await jv(e,t)).findings,...await hg(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Do(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 tv(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 pr({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 aw(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 yu(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 ey(e,t,i){let r=await zT(e)===t,n=await Al(e,t),a=await yv(e,t),o;try{let w=await vu(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},C=cd({paths:e,state:o,findings:[w]}),$=gs({state:o,findings:C});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:$.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:ld(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:$,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await gw({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await Zw(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 pr({changeDir:he(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let de=await Pr(e,o.name,o.verification_evidence);for(let X of de.acceptanceTrace.entries)C.set(X.acceptanceId,X.status==="failed"?"failed":X.status==="missing"?"missing":"satisfied")}let $=lm({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=$.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",$.nextCursor,"--project-root",e.projectRoot]:null;u={...$,...T?{nextPageCommand:WT(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await Es(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await Tt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await xn({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Jo({paths:e,identity:w});f.push(...C.findingCodes.map($=>({code:$,message:`Native workspace advisory changed: ${$} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await Yw({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Cd({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await GT(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,$)=>$.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=cd({paths:e,state:o,findings:S}),N=y.filter(w=>!fr(w.code)),k=o.phase==="archive"&&h?.ready===!0&&N.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),P=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.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:b||P?null:JT(o,k,E,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:ld(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:gs({state:o,findings:y,archiveReady:k,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Ns,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}import ZT from"node:path";function ji(e,t,i){return e.language==="zh-CN"?i:t}function UT(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});return t&&e.phase==="shape"&&e.status==="active"?{required:!0,message:ji(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:ji(e,"Reply A or B","回复 A 或 B"),agentInstruction:ji(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。")}:e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"?i(ji(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,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。")):e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"?i(ji(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 等机器状态。")):e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier")?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."}:e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable"?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."}:i(ji(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 xd(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ps(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ty(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function KT(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function YT(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function XT(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 Xn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:xd({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ps("summary","--summary"),ty(e.name,e.flag)]}}function Pd(e){return[Xn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Xn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function iy(e,t){let i=YT(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:UT(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:[Ps("summary","--summary")],commandAlternatives:[Xn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Pd({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:xd({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:[Ps("summary","--summary")],commandAlternatives:[Xn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Pd({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:[Ps("summary","--summary")],commandAlternatives:Pd({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?xd({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:XT({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?[KT("coordination-mode","--coordination-mode",pm)]:[],ty("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} ${ji(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:[Xn({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")}}function QT(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function ry(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:QT(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 ej(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function tj(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 ij(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:aj(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:oj(r,i)}))]:[]]}function rj(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 ny(e,t){let i=Se(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:ZT.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 nj(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 xs(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function aj(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:xs(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function oj(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:xs(e.summary,t)??""}}async function ay(e){let t=await dg(e),i=ry(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Au({paths:e.paths,state:t.state}),a=await On(e.paths,e.name),o=a?{...ny(e.paths,t.state),projectRoot:"."}:ny(e.paths,t.state),s=iy(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?nj(e.paths,a):[],u=a?(()=>{let p=a.children.filter(({status:N})=>N==="pending"||N==="ready").length,v=a.children.filter(({status:N})=>N==="active"||N==="verified").length,h=a.children.filter(({status:N})=>N==="integrated"||N==="archived").length,m=a.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,S=a.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:xs(N.blocker,l)})),y=a.children.flatMap(({blocker:N})=>{let k=xs(N,l);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:p,working:v,integrated:h,blocked:m,active:S,agents:{working:a.children.filter(({task:N})=>N!==null).length,completed:h},risks:y,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&h===a.children.length?"parent-verification":p>0?"dispatch-ready-child":m>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let p=a?.stateVersion??0,v=ij(t.state,a,l),h=tj(e.cursor,t.state.state_version,p),m=v.slice(h,h+32),S=h+m.length<v.length?ej(t.state.state_version,p,h+m.length):null;return{items:m,nextCursor:S,supervisorStateVersion:p}})():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:rj(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((p,v)=>({...p,[v.status]:(p[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}}:{}}}import Qn from"path";import{realpathSync as fj}from"fs";var _W={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var LW=16*1024*1024,VW=256*1024,FW=16*1024;var GW=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var j2=16*1024*1024,Rs=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"},As=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var oy=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],Ad=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:oy,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, 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>]
175
- 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]
176
- 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 Rd(e,t){return`${e}:
166
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Qo(p),p}async function jt(e,t){let i=await SR(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Qo(i),i)}async function Zo(e){Qo(e.identity);let t=await ER({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")),fu==="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 _n(e){if(Qo(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 Zo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=Ee(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 Cv(e,t){let i=await jt(e,t);if(i===null)return null;let r=await _n({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var Rv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],xR=new Set(Rv),Av=new Set([...Rv,"minimum_runtime_version","revision"]),PR=new Set([...Av,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),RR=new Set(["capability","operation","source","base_hash"]),AR=new Set(["shape","build","verify","archive"]),_R=new Set(["implicit","confirmed"]),IR=new Set(["pending","pass","fail"]),Ii="comet-state.yaml",mu=/^[a-f0-9]{64}$/u,_v=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,es=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"},_i=class extends Error{constructor(i,r){super(i!==Pt||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"},ts=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"},In=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"},is=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"},iB=oa("en");function jn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Iv(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 $n(e){if(!_v.test(e))throw new Error(`Invalid Native change name: ${e}`)}function jR(e){if(!_v.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Tv(e,t){if(e.length===0||oi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function $R(e,t){let i=jn(e,`spec_changes[${t}]`);if(Iv(i,RR,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(jR(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"&&Tv(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"||!mu.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"||!mu.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 OR(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 gu(e,t){if(Iv(e,t,Ii),typeof e.name!="string")throw new Error("Native change name is required");if($n(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"||!AR.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&&!_R.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($R),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"||!IR.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"&&Tv(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!OR(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 sr(e){let t=jn(e,Ii);if(t.schema!==At)throw new Error(`Expected ${At}`);return{schema:At,...gu(t,xR)}}function Tn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function hu(e,t,i){if(e===null)return null;let r=typeof e=="string"?TR.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 HR(e){if(e==null)return null;if(typeof e!="string"||!mu.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function DR(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 cr(e){let t=jn(e,Ii);if(t.schema!==Rt)throw new Error(`Expected ${Rt}`);if(Tn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Rt} minimum_runtime_version must be 2`);return{schema:Rt,minimum_runtime_version:2,revision:Tn(t.revision,"Native v2 revision"),...gu(t,Av)}}function ri(e){let t=jn(e,Ii);if(t.schema!==Pt){if(t.schema===At||t.schema===Rt){let o=t.schema===At?sr(t):cr(t);throw new es(o.name,o.schema)}throw new _i(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Tn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new _i(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=Tn(t.revision,"Native revision"),n=gu(t,PR),a=HR(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pt,minimum_runtime_version:3,revision:r,verification_protocol:DR(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:hu(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:hu(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:hu(t.partial_allowance,"Native partial_allowance","allowances")}}function LR(e){let t=jn(e,Ii);if(t.schema===At){let n=sr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema===Rt){let n=cr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Pt}`}}if(t.schema!==Pt){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 _i(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=Tn(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new _i(t.schema,i).message};let r=ri(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function me(e,t){$n(t);let i=oi.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}async function rs(e,t){let i=U(e,t),r=oi.join(i,"schema-migration.json");await z(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Pv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function jv(e,t){let i=U(e,t),r=oi.join(i,"checkpoint-journal.json");await z(V(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await Pv.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function BR(e,t=oi.dirname(e)){let i=oi.relative(t,e).split(oi.sep).join("/"),r=await re({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,vu.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 wu(e,t){let i=oi.join(me(e,t),Ii);await z(e.nativeRoot,i);let r=LR(await BR(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await rs(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 VR(e,r.state),r)}async function VR(e,t){if(await Wo(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function gt(e,t){let i=await wu(e,t);if(i.status==="migration-required")throw new es(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new _i(i.schema,i.minimumRuntimeVersion);return await Cv(e,t),i.state}var Ov=["outcome","scope","nonGoals","acceptanceExamples"],FR=[...Ov,"constraints","decisions","openQuestions","verificationExpectations"],MR=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],Hv={maxFileBytes:dn};function Dv(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
167
+ `).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 qR(e,t){let i=$v.resolve(e,...t.split(/[\\/]/u));if(!V(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await yu.realpath(e),n=await yu.realpath(i);if(!V(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await yu.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function On(e){return{valid:e.length===0,findings:e}}async function Nu(e,t){let i=[],r;try{r=(await re({root:e,ref:t,maxBytes:Hv.maxFileBytes})).text}catch(o){return On([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of Dv(r))n.set(aa(o)??o,s);for(let o of FR)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Ov)(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}),On(i)}async function bu(e,t){let i=[],r;try{r=(await re({root:e,ref:t,maxBytes:Hv.maxFileBytes})).text}catch(a){return On([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Dv(r))n.set(Vd(a)??a,o);for(let a of MR)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 On(i)}function ns(e,t){return $v.join(e.specsDir,t,"spec.md")}async function Lv(e,t){let i=[],r=me(e,t.name);for(let n of t.spec_changes){let a=ns(e,n.capability),o=null;try{await z(e.nativeRoot,a),o=await Xl(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 qR(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return On(i)}import Bv from"node:path";var WR="comet.native.contract.v1",zR="comet.native.acceptance-set.v1",Vv=/^[a-f0-9]{64}$/u,Hn={maxAcceptanceCriteria:wn.maxCriteria};function Fv(e,t){let i=Bv.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})||Bv.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 Mv(e){return L("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
168
+ `))}function JR(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(Vv))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(Vv))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Fv(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Mv(e.markdown)},markdown:e.markdown}}function GR(e,t){return qv(e.id,t.id)}function qv(e,t){return e<t?-1:e>t?1:0}function Wv(e){let t=Fv(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(JR).sort((d,f)=>qv(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=Fl(e.briefMarkdown,t,Hn.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Ml(f,d.source,Hn.maxAcceptanceCriteria-a.length)),a.push(...mm(f,d.source,Hn.maxAcceptanceCriteria-a.length)));if(a.sort(GR),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Hn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Hn.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:Mv(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=L(zR,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:L(WR,u)}}var as={maxSpecs:64,maxFileBytes:dn,maxTotalBytes:4*1024*1024};async function gr(e){if(e.specChanges.length>as.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:as.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 re({root:e.changeDir,ref:n.source,maxBytes:as.maxFileBytes});if(i+=a.size,i>as.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:Wv({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{randomUUID as UR}from"crypto";import{promises as os}from"fs";import Jv from"path";var ku="comet.selection.v2",KR=16*1024;function Su(e){return Jv.join(e,".comet","current-change.json")}function YR(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zv(e){return e===null||typeof e=="string"}function Gv(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(!YR(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&&!zv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ku,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==ku)throw new Error(`current change selection schema must be ${ku}`);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(!zv(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 Uv(e){let t;try{let r=Su(e),{bytes:n}=await Ci(r,KR,{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",...Gv(t)}}async function Kv(e,t){let i=Gv(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let r=Su(e),n=`${r}.${UR()}.tmp`;await os.mkdir(Jv.dirname(r),{recursive:!0});try{await os.writeFile(n,`${JSON.stringify(i.selection,null,2)}
169
+ `,"utf8"),await os.rename(n,r)}catch(a){throw await os.rm(n,{force:!0}),a}}import{promises as MA}from"node:fs";import $u from"node:path";var _u=Tr(Ki(),1);import{promises as cg}from"node:fs";import qe from"node:path";import{execFileSync as XR}from"node:child_process";var QR=3e4,ZR=8*1024*1024,Eu=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 eA(e,t){try{return XR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:QR,maxBuffer:ZR,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Eu(e,t,r)}}function ss(e,t){return eA(e,t).trim()}import xu from"node:path";import{promises as Yv}from"node:fs";var cs=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var Cu="comet.native.supervisor.v2",iA=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function rA(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 nA(e,t){return xu.join(ti(e,t),"supervisor")}function Xv(e,t){return xu.join(nA(e,t),"state.json")}function Qv(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!==Cu)throw new Error(`Native Supervisor state schema must be ${Cu}`);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(Dn(t.integration.targetCommit,"Native Supervisor target commit"),Dn(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&&Dn(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(Dn(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 Ln(e,t){try{let i=await Yv.readFile(Xv(e,t),"utf8"),r=JSON.parse(i);return Qv(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pu(e,t){Qv(t),await Yv.mkdir(e.changesRuntimeDir,{recursive:!0}),await Qe(Xv(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Dn(e,t){if(!iA.test(e))throw new Error(`${t} must be a Git commit`)}function aA(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Zv(e){Dn(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:Cu,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 Ru(e){let t=rA(e.parent),i=ki(e.paths.projectRoot,t);if(!i)return null;let r=ki(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Xi(e.paths.projectRoot).map(o=>xu.resolve(o)).find(o=>Ee(o).currentBranch===t);if(!n)return null;let a=Zv({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 aA(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function eg(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 tg="children.yaml",Bn="comet.native.children.v1",wr="comet.native.children.v2",lg=wr,oA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ig=new Set(["schema","children"]),sA=new Set(["schema","acceptance_index","children"]),cA=new Set(["name","depends_on","covers"]),lA=new Set(["name","summary","depends_on"]),uA=new Set(["name","depends_on","covers"]);function us(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function ls(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 rg(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 Au(e,t){let i=qe.normalize(qe.resolve(e)),r=qe.normalize(qe.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function dA(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 ng(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 fA(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===lg&&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=>!ag(e.children,l)),og(r)?r:null}if(e.schema===Bn&&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=>!ag(e.children,a)),og(r)?r:null}return null}function ag(e,t){return e.some(i=>i.covers.includes(t))}function og(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function ug(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 pA(e){let t=us(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=us(n,`Native children acceptance_index.${r}`);if(ls(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 hA(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(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function mA(e,t,i={}){let r=(0,_u.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=us(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Bn&&a!==wr)throw ls(n,ig,"Native children contract"),new Error(`Native children schema must be ${Bn} or ${wr}`);let o=a===Bn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(ls(n,o==="indexed-v2"?sA:ig,"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,p)=>{let v=us(f,`Native child ${p}`);if(ls(v,o==="indexed-v2"?uA:o==="summary-v2"?lA:cA,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!oA.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){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:h?v.summary:null,depends_on:rg(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?rg(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 p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}dA(c);let d=i.policy==="advisory";if(a===lg){if(o==="indexed-v2"){let f=pA(n.acceptance_index);d||hA(f,t,i);let p=Object.keys(f);return d||ng(c,p,p),{schema:wr,acceptance_index:f,children:c}}return{schema:wr,children:c}}return t&&!d&&ng(c,t),{schema:Bn,children:c}}async function dg(e){let t=qe.join(e.changeDir,tg);try{await cg.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await re({root:e.changeDir,ref:tg}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=mA(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?fA(a,e.acceptanceIds,e.validation??{}):null}}function vA(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 gA(e){let t=vA(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 fg(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return gA(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function pg(e){return L("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 wA(e){let t=Xi(e.projectRoot);t.some(r=>Au(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>qe.resolve(n)))]){let n=await Ie(r);n&&i.push({projectRoot:r,paths:await xi(r,n.native.artifact_root),parent:Au(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function yA(e,t){let i=qe.join(e.paths.changesDir,t,"comet-state.yaml");try{return await bn(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function NA(e,t){let i;try{i=await cg.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=qe.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await bn(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function bA(e,t,i){let r=qe.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${qe.sep}`))return null;let n=r.split(qe.sep).join("/");try{let a=(0,_u.parseDocument)(ss(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Nn(a.toJS({mapAsMap:!1}))}catch{return null}}function kA(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 sg(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Iu(e){let t=qe.join(e.paths.changesDir,e.state.name),i=await fg(t),r=await dg({changeDir:t,validation:ug(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:m})=>m)}:{},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=pg({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===wr){let m=await Ln(e.paths,e.state.name);if(!m){let N=e.state.workspace.target_branch??e.state.workspace.change_branch;if(N){let k=await Ru({paths:e.paths,parent:e.state.name,targetBranch:N,contract:r.contract});k&&(m=k,await Pu(e.paths,k))}}if(m){let N=eg(m);return e.state.children_contract_hash!==n||r.drift?{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(k=>({...k,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let S=new Map(r.contract.children.map(N=>[N.name,N])),y=r.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:o&&N.depends_on.every(k=>r.contract.children.filter(({name:E})=>E!==N.name).every(({name:E})=>E!==k))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let N of y){if(N.status!=="ready")continue;S.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:y,readyChildren:y.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let s=await wA(e.paths),c=new Set(r.contract.children.map(({name:m})=>m)),l=new Map,u=new Map;for(let m of s){let S=m.parent&&a?`refs/heads/${a}`:"HEAD";for(let y of await NA(m,c)){let N={...y,source:m,committedState:bA(m,y.file,S)};l.set(y.state.name,[...l.get(y.state.name)??[],N])}for(let y of c){let N=await yA(m,y);N&&u.set(y,[...u.get(y)??[],{source:m,state:N}])}}let d=new Map;for(let m of r.contract.children){let S=(l.get(m.name)??[]).find(({source:k,committedState:E})=>k.parent&&E?.name===m.name&&sg(E,a));if(S){d.set(m.name,{kind:"done",phase:S.state.phase,projectRoot:S.source.projectRoot,message:null});continue}let y=l.get(m.name)?.[0];if(y){d.set(m.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${m.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let N=u.get(m.name)??[];N.length>1?d.set(m.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${m.name} has multiple active workspace owners`}):N[0]&&d.set(m.name,kA(N[0].state,N[0].source,a))}let f=new Map(r.contract.children.map(m=>[m.name,m])),p=new Map,v=m=>{let S=p.get(m);if(S)return S;let y=f.get(m),k=y.depends_on.map(v).every(({status:C})=>C==="done"),E=d.get(m),b=E?.kind==="active"&&k?y.depends_on.filter(C=>!(l.get(C)??[]).some(({source:$,committedState:T})=>Au($.projectRoot,E.projectRoot)&&T?.name===C&&sg(T,a))):[],x,g=E?.message??null;E?.kind==="done"?(x=k?"done":"blocked",k||(g=`Native child ${m} was merged before its dependencies`)):E?.kind==="active"?(x=k&&b.length===0?"active":"blocked",k?b.length>0&&(g=`Native child ${m} does not include merged dependencies: ${b.join(", ")}`):g=`Native child ${m} started before its dependencies merged`):E?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(g="Parent Shape confirmation is required"));let w={name:m,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:x,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:g};return p.set(m,w),w},h=r.contract.children.map(({name:m})=>v(m));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:m})=>m==="ready").map(({name:m})=>m),allDone:h.every(({status:m})=>m==="done")}}var aV=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var SA=/\b(Bearer|Basic)\s+[^\s"']+/giu,EA=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,CA=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,xA=/\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,PA=/("(?:[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,RA=/(["'])((?:[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,AA=/\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 We(e){return e.replace(SA,"$1 [REDACTED]").replace(EA,"[REDACTED PRIVATE KEY]").replace(CA,"$1[REDACTED]@").replace(xA,"[REDACTED TOKEN]").replace(PA,'$1"[REDACTED]"').replace(RA,"$1$2$1$3$4[REDACTED]$4").replace(AA,"$1$2[REDACTED]")}import{promises as OA}from"node:fs";import hg from"node:path";function ds(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fs(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 wt(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 mg(e,t){return e===null?null:wt(e,t)}function hs(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 HA(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 DA(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ps(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function Tu(e,t){if(e===null)return null;let i=wt(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function ju(e,t){let i=wt(e,t);if(!hg.isAbsolute(i))throw new Error(`${t} must be absolute`);return hg.resolve(i)}function LA(e,t){let i=`Native local checks[${t}]`,r=ds(e,i);if(fs(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)=>wt(l,`${i}.argv[${u}]`,!0)),a=ps(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=Tu(r.startedAt,`${i}.startedAt`),s=Tu(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=hs(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:wt(r.id,`${i}.id`),name:wt(r.name,`${i}.name`),operationId:wt(r.operationId,`${i}.operationId`),status:a,repeatable:DA(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:hs(r.executionCount,`${i}.executionCount`),argv:n,cwd:ju(r.cwd,`${i}.cwd`),exitCode:HA(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:wt(r.log,`${i}.log`)}}function BA(e){let t="Native local execution state",i=ds(e,t);if(fs(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==_o)throw new Error(`Native local execution schema must be ${_o}`);let r=ds(i.workspace,"Native local workspace");fs(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=ds(i.execution,"Native local execution");fs(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Tu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:wt(o.operationId,"Native local execution.operationId"),stage:ps(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ps(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:mg(o.executionId,"Native local execution.executionId"),status:ps(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:hs(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(LA);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:_o,change:wt(i.change,"Native local change"),basedOnStateVersion:hs(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:ju(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ju(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:mg(r.branch,"Native local workspace.branch")},execution:n,checks:a}}async function vg(e){let t;try{t=await OA.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 BA(i)}var qA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WA="comet-state.yaml",zA="state.json",HF=oa("en");function gg(e,t){if(!qA.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=$u.join(e.changesDir,t);if(!V(e.changesDir,i))throw new Error("Native change path escaped");return i}function wg(e,t){return $u.join(gg(e,t),WA)}function JA(e,t){return $u.join(ti(e,t),zA)}async function ms(e,t){try{let i=await MA.readFile(wg(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Ou(e,t){return bn(wg(e,t))}async function yg(e){let t=await Ou(e.paths,e.name),i=JA(e.paths,e.name);try{let r=await vg(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 zF=16*1024;async function Ng(e){let t=await Uv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:($n(t.selection.change),t.selection)}async function bg(e,t){return it(e,`select change ${t}`,async()=>{$n(t),await ms(e,t)?await Ou(e,t):await gt(e,t),await Kv(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function kg(e,t){let i=[],r=U(e,t.name),n=ii(r,Me.stateRef),a;try{a=await mr(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=ii(r,a.trajectoryRef),s=await mv(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 Ai(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=ii(r,a.checkpointRef);try{let u=await Yo(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import L_ from"path";import{isDeepStrictEqual as td}from"util";var yr={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var GA=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function UA(e,t){return e<t?-1:e>t?1:0}function KA(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"||!GA.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(UA)}function Hu(e=[]){return KA(e,"Native repair failed check IDs",yr.maxFailedCheckIds,!0)}function Sg(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function YA(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:Sg(e.failedAcceptanceIds,t.failedAcceptanceIds)&&Sg(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Du(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(YA(r,a))break;i+=1,r=a}return i}import qg from"node:path";import{createHash as Ig}from"node:crypto";import Eg from"path";var Lu="comet.native.implementation-scope.v2",Tg="comet.native.content-snapshot-projection.v1",Vn="comet.native.content-snapshot-projection.v1",jg="comet.native.implementation-scope.v2",XA="comet.native.unresolved-scope-id.v1",QA="comet.native.scope-detail-overflow.v1",ZA="comet.native.snapshot-projection-overflow.v2",Mu=/^[a-f0-9]{64}$/u,ji=1024*1024,e_=128,t_=128;function ve(e,t){return e<t?-1:e>t?1:0}function Bu(e){if(!Mu.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function i_(e,t){return e===t?0:e===null?-1:t===null?1:ve(e,t)}function ci(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=Eg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Eg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function $g(e,t){return e==="."?e:ci(e,t)}function Nr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function r_(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:ci(e.path,`${t} path`),hash:e.hash,size:Nr(e.size,`${t} size`),type:"file"}}function n_(e,t){return{path:$g(e.path,`${t} path`),size:e.size===null?null:Nr(e.size,`${t} size`),type:e.type,reason:e.reason}}function a_(e,t){return ve(e.path,t.path)||ve(e.hash,t.hash)||e.size-t.size}function o_(e,t){return ve(e.path,t.path)||ve(e.reason,t.reason)||ve(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Mn(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
170
+ `,"utf8")}function si(e,t,i){let r=`${t}
171
+ ${gn(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function s_(e){if(Mn(e)<=ji)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=Ig("sha256");a.update(`${ZA}
172
+ `),e.omissionOverflow&&si(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(r+=1),n+=1,si(a,"omission",f)},s=f=>{r+=1,n+=1,si(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Mn(u)>ji;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function Vu(e){let t=Ri(e),i=t.entries.map((n,a)=>r_(n,`Snapshot entry ${a}`));if(i.sort(a_),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)=>n_(n,`Snapshot omission ${a}`));return r.sort(o_),s_({schema:Tg,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 qn(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:ci(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>ve(i.path,r.path)||ve(i.kind,r.kind))}function Wn(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Cg(e){return e?{hash:e.hash,size:e.size}:null}function qu(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:ve(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Cg(c),after:Cg(l)})}}function Og(e,t){return{...e,attributedTo:t.filter(i=>Wn(i,e.path))}}function Wu(e){let t=qn(e.declaredArtifacts),i=[];return qu(e.baseline,e.current,r=>{i.push(Og(r,t))}),i}function $t(e,t){return{id:`scope:${L(XA,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function c_(e,t){let i=t.omitted.map(r=>$t({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($t({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push($t({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 xg(e,t){return c_(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Fu(e,t){return ve(e.kind,t.kind)||ve(e.source,t.source)||i_(e.path,t.path)||ve(e.id,t.id)}function l_(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Fu)}function Hg(e){return[...new Set(e.map((t,i)=>ci(t,`Git path ${i}`)))].sort(ve)}function Pg(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 u_(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 Dg(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Hg(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Pg(e.baseCommit,"Native external drift base commit"),targetBranch:u_(e.targetBranch,"Native external drift target branch"),targetCommit:Pg(e.targetCommit,"Native external drift target commit"),paths:t}}function Lg(e){if(typeof e.contractHash!="string"||!Mu.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:qn(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Hg(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Dg(e.externalDrift)}}}function d_(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 qu(e,t,p=>{let v=i.some(h=>Wn(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<e_){let h=Og(p,i),m=Mn(h);l+m<=ji?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Bg(e,t){return $t({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 f_(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:Nr(Number(t[1]),"Scope overflow change count"),unresolved:Nr(Number(t[2]),"Scope overflow unresolved count"),unattributed:Nr(Number(t[3]),"Scope overflow unattributed count")},r=Ti(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Bg(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function p_(e){let t=Ig("sha256");t.update(`${QA}
173
+ `);let i=0;qu(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){si(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Wn(o,n.path)&&(a+=1,si(t,"change-attribution",o));si(t,"change-end",{attributionCount:a}),a===0&&si(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&&si(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Vg(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=d_(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let x=new Set(i.externalDrift.paths),g=new Set(o.changePaths),w=i.externalDrift.paths.filter(C=>!g.has(C)||n.some($=>Wn($,C)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(x.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=L(Vn,e),c=L(Vn,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[x,g]of[["baseline",e],["current",t]])for(let w of g.omitted){if(l.length>=t_)break;l.push($t({kind:"snapshot-omission",source:x,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${x} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...xg("baseline",e),...xg("current",t),...o.totalChanges===0&&a===null?[$t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(i.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(g=>x.has(g)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(g=>!x.has(g))}},v=x=>{let g=o.candidates.slice(0,x.detailedChangeCount),w=g.filter(Ge=>Ge.attributedTo.length===0&&!u.has(Ge.path)),C=o.totalChanges-g.length,$=o.totalUnattributed-w.length,T=d-x.detailedOmissionCount,pe=$+T,Q=[...w.map(Ge=>$t({kind:"unattributed-change",source:"implementation-scope",path:Ge.path,evidence:{after:Ge.after,before:Ge.before,changeKind:Ge.kind}},`Changed path is not covered by a declared artifact: ${Ge.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...pe>0?[Bg(x.overflowHash,{changes:C,unattributed:$,unresolved:pe})]:[]],G=l_(Q),lt=x.includeGitAdvisory?p():void 0;return{schema:Lu,contractHash:r,baselineProjectionRef:Bu(s),baselineProjectionHash:s,currentProjectionRef:Bu(c),currentProjectionHash:c,complete:G.length===0,declaredArtifacts:n,changes:g,unattributed:w,unresolvedScopes:G,noCodeReason:a,...lt?{gitAdvisory:lt}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},h=o.candidates.length,m=l.length,S=i.gitChangedPaths!==void 0,y="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:y});if(Mn({...x,scopeHash:y})<=ji)break;if(S){S=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let k=o.totalChanges>h||d>m?p_({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):y,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:S,overflowHash:k}),b={...E,scopeHash:L(jg,E)};if(Mn(b)>ji)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function zu(e){let t=Vu(e.baseline),i=Vu(e.current),r=Lg(e);return{authority:r,baseline:t,current:i,scope:Vg(t,i,r)}}var h_=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function yt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Nt(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 Ti(e,t){if(typeof e!="string"||!Mu.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Rg(e,t,i){let r=Bu(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function vs(e,t){let i=yt(e,"Native snapshot projection");if(Nt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Tg)throw new Error("Native snapshot projection schema is invalid");let r=Ri({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=Vu(r);if(L(Vn,i)!==L(Vn,n))throw new Error("Native snapshot projection is not canonical");let a=L(Vn,n);if(t!==void 0&&Ti(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Ju(e,t){let i=yt(e,`Declared artifact ${t}`);if(Nt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:ci(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Ag(e,t){if(e===null)return null;let i=yt(e,t);return Nt(i,["hash","size"],[],t),{hash:Ti(i.hash,`${t} hash`),size:Nr(i.size,`${t} size`)}}function _g(e,t){let i=yt(e,`Implementation change ${t}`);if(Nt(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(Ju),n=qn(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Ag(i.before,`Implementation change ${t} before`),o=Ag(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:ci(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function m_(e,t){let i=yt(e,`Unresolved scope ${t}`);Nt(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"?$g(i.path,`Unresolved scope ${t} path`):ci(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function Fn(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)=>ci(n,`${t} ${a}`)),r=[...new Set(i)].sort(ve);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Fg(e){let t=yt(e,"Native implementation external drift");if(Nt(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=Fn(t.paths,"Native external drift paths");return Dg({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function gs(e){let t=yt(e,"Native implementation scope"),i=[...h_].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(Nt(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Lu)throw new Error("Native implementation scope schema is invalid");let r=Ti(t.contractHash,"Implementation scope contractHash"),n=Ti(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Rg(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ti(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Rg(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(Ju);if(JSON.stringify(c)!==JSON.stringify(qn(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(_g),u=[...l].sort((w,C)=>ve(w.path,C.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(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(C=>Wn(C,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(_g),p=t.externalDrift===void 0?void 0:Fg(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(m_),S=m.filter(w=>w.kind==="scope-detail-overflow");if(S.length>1)throw new Error("Implementation scope has multiple detail overflow records");let y=S[0]===void 0?null:f_(S[0]);if(y&&(y.changes+y.unresolved===0||y.unattributed>y.changes||y.unattributed>y.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,k=[...h.map(w=>$t({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+(y?.changes??0)===0&&N===null?[$t({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Fu))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(k.sort(Fu))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let w=yt(t.gitAdvisory,"Implementation scope Git advisory");if(Nt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Fn(w.changedPaths,"Git changed paths"),$=Fn(w.pathsPresentInSnapshotChanges,"Git present paths"),T=Fn(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),pe=[...$,...T].sort(ve);if(JSON.stringify(pe)!==JSON.stringify(C)||T.some(Q=>l.some(G=>G.path===Q)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:$,pathsAbsentFromSnapshotChanges:T}}let x={schema:Lu,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...b?{gitAdvisory:b}:{},...p?{externalDrift:p}:{}},g=Ti(t.scopeHash,"Implementation scope scopeHash");if(L(jg,x)!==g)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:g}}function v_(e){let t=yt(e,"Native implementation scope authority");if(Nt(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(Ju);if(JSON.stringify(i)!==JSON.stringify(qn(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=Fn(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Fg(t.externalDrift),a=Lg({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 zn(e){let t=yt(e,"Native implementation scope bundle");Nt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=v_(t.authority),r=vs(t.baseline),n=vs(t.current),a=gs(t.scope),o=Vg(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 Mg(e){let t=gs(e.scope);return zn({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})}var zg=/^[a-f0-9]{64}$/u;var g_="comet.native.acceptance-trace.v2",w_="comet.native.partial-allowance.v1",y_="comet.native.verification-evidence.v2";function Ot(e,t){if(!zg.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Jg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Gg(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 Gu(e,t,i=2e3){let r=We(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function Jn(e,t){let i=qg.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})||qg.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function N_(e,t,i){let r=Jn(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ft(r),a=r.toLowerCase(),o=i?Jn(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 Uu(e){let t=Jn(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 br(e,t){return e<t?-1:e>t?1:0}function ws(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ys(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 Ug(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 Wg(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 b_(e){let t=ws(e,"Native acceptance trace");if(ys(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"||!zg.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=Jn(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=ws(o,`Native acceptance trace entry ${s}`);if(ys(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=>Uu(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(br))||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:Jn(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Gu(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>br(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=Ot(t.traceHash,"Native acceptance trace hash");if(L(g_,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Kg(e){let t=ws(e,"Native partial allowance");if(ys(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(br))||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:Gg(t.change),scopeHash:Ot(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Gu(t.reason,"Partial allowance reason"),confirmedSummary:Gu(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Jg(t.sourceRevision),confirmedAt:Ug(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=Ot(t.allowanceHash,"Native partial allowance hash");if(L(w_,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function Ku(e){let t=ws(e,"Native verification evidence");if(ys(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Ot(t.implementationScopeHash,"Native verification implementation scope hash"),r=b_(t.acceptanceTrace),n=Ot(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:Ot(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Uu(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(br)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(br);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=>Uu(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(br)))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:Gg(t.change),sourceRevision:Jg(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Ot(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Wg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:N_(t.reportRef,"Native verification report ref"),reportHash:Ot(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Wg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Ug(t.createdAt,"Native verification timestamp")},d=Ot(t.envelopeHash,"Native verification envelope hash");if(L(y_,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}function Yu(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 Yg="repairStagnation",$e={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},S_=/^[a-f0-9]{64}$/u;var E_=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),C_=["data","runId","sequence","timestamp","type"],Xg=["disposition","overrideSummaryHash","signatureHash"],x_=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Qg=12;function Qu(e,t){return e<t?-1:e>t?1:0}function Zg(e,t,i){let r=Object.keys(e).sort(Qu);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function Ns(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 Gn(e,t){if(typeof e!="string"||!S_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function P_(e){if(!Array.isArray(e)||e.length>yr.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(Qu)}function ew(e){if(typeof e!="string"||e.length===0||e.length>$e.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 Xu(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>$e.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>$e.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>$e.maxTextCharacters&&(!n||e.length>$e.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>$e.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>$e.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Xu(s,t+1,i,`${r}[${c}]`));return}let a=Ns(e,r),o=Object.keys(a);if(o.length>$e.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>$e.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>$e.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Xu(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function R_(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 A_(e,t,i){let r=Ns(e,`Native repair trajectory event ${t+1}`);if(Zg(r,C_,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(R_(r.timestamp),typeof r.type!="string"||!E_.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(ew(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 Xu(r.data,0,n,"Native trajectory event data"),Ns(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Zu(e){let t=Ns(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Qu),r=i.length===Xg.length&&i.every((l,u)=>l===Xg[u]);r||Zg(t,x_,"Native repair trajectory projection");let n=Gn(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:Gn(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=Gn(t.contractHash,"Native repair trajectory contract hash"),s=P_(t.failedAcceptanceIds),c=Hu(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 __(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 I_(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??Qg;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Du({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<yr.warningAtConsecutiveFailures?"continue":a<yr.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function T_(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??Qg;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 tw(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>$e.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=ew(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=A_(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>$e.maxTotalDataNodes||c>$e.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Gn(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Gn(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Yg)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Zu(f[Yg]);if(__(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(i.length=0,o=0),p!==null&&(n=p),I_(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");T_(v,i,r);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>yr.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function iw(e){return tw(e).history}function rw(e){let t=tw(e).latestProjection;return t?{...t}:null}var kr={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:[]},ed=K("comet-native-runtime:v3:scope-reopen"),j_=[{skillVersion:"3",skillHash:K("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:K("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:K("comet-native-runtime:v1")}];function nw(e){return e.skillVersion===kr.definition.metadata.version&&e.skillHash===ed||j_.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}function aw(e){return K(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 uw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],B_=new Set(uw),dw=new Set([...uw,"minimum_runtime_version","revision"]),V_=new Set([...dw,"operation"]),F_=512*1024,id=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),M_=new Set([...id,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),rd=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 ad(e,t){return L_.join(U(e,t),"transition.json")}function ks(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function od(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 bs(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function nd(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=>!M_.has(u)),a=[...id].find(u=>!Object.hasOwn(i,u)),o=id.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(Yu(i.summary,"Native transition journal event summary"),We(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&&(Yu(i.noCodeReason,"Native transition journal event no-code reason"),We(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")?Zu(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 q_(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 nd({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return nd(e,t)}function sd(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?q_(e.eventData,e.evidenceHash):nd(e.eventData,e.evidenceHash),n=lu(e.nextRun),a=e.previousRun===null?null:lu(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function ow(e,t,i=!1){if(e.skill!==kr.definition.metadata.name||(i?!nw(e):e.skillVersion!==kr.definition.metadata.version||e.skillHash!==ed)||e.orchestration!==kr.definition.orchestration.mode||e.pendingRef!==Me.pendingRef||e.trajectoryRef!==Me.trajectoryRef||e.contextRef!==Me.contextRef||e.artifactsRef!==Me.artifactsRef||e.checkpointRef!==Me.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function sw(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 cw(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 cd(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(ow(o,"next Run",r||a!==null),cw(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(ow(a,"previous Run",!0),cw(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(!td(sw(a),sw(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function W_(e,t,i){return K(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function fw(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function lw(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function ld(e,t,i,r,n=!1){let a=i.eventData,o=lw(e),s=lw(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&&td(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&&td(e.spec_changes,t.spec_changes),l=aw({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=W_(e.name,a.summary,t.spec_changes),l=K(`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 z_(e,t){let i=ks(e);if(od(i,V_),i.schema!==ar)throw new Error(`Expected Native transition schema ${ar}`);let r=bs(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${ar} minimum_runtime_version must be ${3}`);let n=bs(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=sd(i,t),o=ri(i.previousState),s=ri(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(ld(o,s,a,i.operation),cd(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ar,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function J_(e,t){let i=ks(e);if(od(i,B_),i.schema!==kn)throw new Error(`Expected Native transition schema ${kn}`);let r=sd(i,t,!0),n=sr(i.previousState),a=sr(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return ld(n,a,r,fw(n,a,r.eventData),!0),cd(n,a,r,!0),{schema:kn,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 G_(e,t){let i=ks(e);if(od(i,dw),i.schema!==or)throw new Error(`Expected Native transition schema ${or}`);if(bs(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${or} minimum_runtime_version must be 2`);let n=bs(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=sd(i,t,!0),o=cr(i.previousState),s=cr(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(ld(o,s,a,fw(o,s,a.eventData),!0),cd(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:or,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 U_(e,t){let i=ks(e);if(i.schema===ar)return{status:"current",journal:z_(i,t)};if(i.schema===kn)return{status:"migration-required",journal:J_(i,t)};if(i.schema===or)return{status:"migration-required",journal:G_(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function K_(e,t){let i=ad(e,t),r=ue(e,i);await z(r,i);try{let n=await mt({root:r,file:i,maxBytes:F_,label:`Native transition journal ${t}`});return U_(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function pw(e,t){let i=await K_(e,t);if(!i)return null;if(i.status==="migration-required")throw new rd(t);return i.journal}var Y_=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function X_(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function Q_(e){return e?e.map(X_).join(" "):null}function Z_(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 ze(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 eI(e){return e.map(t=>ze(t,[],null))}function tI(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[ze("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(ze("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(ze("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),ze("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(ze("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(ze("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),ze("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ge(e,t){let i=t.commandArgs===void 0?Z_(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?Q_(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??eI(t.requiredInputs??[])}}function Ss(e){let i=(e.findings??[]).filter(d=>!vr(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||Y_.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 ge(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[ze("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return ge(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ge(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[ze("summary",["--summary"],"<summary>")]});if(n)return ge(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 ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[ze("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?ge(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ge(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ge(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"),ge(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[ze("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ge(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ge(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=tI(e.state);return ge(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import Un from"path";var hw=8,iI={"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 rI(e){let t=iI[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"}:vr(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 nI(e,t,i){if(!i.path)return null;let r;if(Un.isAbsolute(i.path)?r=Un.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=Un.resolve(me(e,t.name),...i.path.split(/[\\/]/u)):r=Un.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!V(e.projectRoot,r))return null;let n=Un.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function aI(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 ud(e){return e.findings.map(t=>{let i=rI(t.code);return{code:t.code,message:t.message,severity:i.severity,path:nI(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:aI(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 dd(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,hw),truncated:t.length>hw}}import Sr from"path";var ui={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Er=/^[a-f0-9]{64}$/u;function Es(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Cs(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 li(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 mw(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function fd(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function oI(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Sr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Sr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function vw(e,t){return Sr.join(U(e,t),"checkpoints","progress.json")}function Kn(e,t){return Sr.join(U(e,t),"checkpoint-journal.json")}function gw(e,t,i){if(!Er.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Sr.join(U(e,t),"checkpoints","manifests",`${i}.json`)}function sI(e){if(!Er.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function pd(e,t,i){let r=await mt({root:e,file:t,maxBytes:ui.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function cI(e,t){let i=Es(e,`checkpoint manifest artifact ${t}`);Cs(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=oI(li(i.path,`checkpoint artifact ${t} path`,4096)),n=ft(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Er.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:fd(i.size,`checkpoint artifact ${t} size`)}}function hd(e,t){let i=Es(e,"Native checkpoint manifest");if(Cs(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>ui.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(cI),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=fd(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>ui.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 ww(e){return K(JSON.stringify(hd(e,e.change)))}function yw(e,t){let i=Es(e,"Native progress checkpoint");if(Cs(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=mw(i.previousRevision,"Native checkpoint previousRevision"),a=mw(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=li(i.manifestHash,"Native checkpoint manifestHash",64);if(!Er.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=sI(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=li(i.inputHash,"Native checkpoint inputHash",64);if(!Er.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=li(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=fd(i.artifactCount,"Native checkpoint artifactCount");if(u>ui.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=li(i.summary,"Native checkpoint summary"),f=li(i.nextAction,"Native checkpoint nextAction");if(We(d)!==d||We(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:li(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 lI(e,t){let i=Es(e,"Native checkpoint journal");if(Cs(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=ri(i.previousState),n=ri(i.nextState),a=yw(i.checkpoint,t),o=hd(i.manifest,t),s=li(i.inputHash,"Native checkpoint journal inputHash",64),c=K(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Er.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!==ww(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 uI(e,t,i){let r=Sr.resolve(e.projectRoot,...t.split("/"));if(!V(e.projectRoot,r)||V(e.nativeRoot,r)||V(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=yl(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await mt({root:e.projectRoot,file:r,maxBytes:ui.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 dI(e,t){let i=vw(e,t),r=ue(e,i);await z(r,i);try{return yw(await pd(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function fI(e,t,i){let r=gw(e,t,i),n=ue(e,r);await z(n,r);let a=await pd(n,r,"Native checkpoint manifest"),o=hd(a,t);if(Nw(e,o),ww(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function md(e,t){let i=Kn(e,t),r=ue(e,i);await z(r,i);try{let n=lI(await pd(r,i,"Native checkpoint journal"),t);return Nw(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Nw(e,t){for(let i of t.artifacts){let r=yl(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function bw(e){let t;try{t=await dI(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:vw(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 fI(e.paths,e.name,t.manifestHash);let a=K(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 uI(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:gw(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}var kw=240,Sw=8,xs=50;function Ew(e){let t=Array.from(e);return t.length<=kw?e:`${t.slice(0,kw-1).join("")}…`}function pI(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function hI(e){let t=[...new Set(e.map(pI))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Sw),reasonCount:e.length,codesTruncated:t.length>Sw};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,xs),reasonsTruncated:e.length>xs}}}async function Cw(e){let t=null;try{let s=await md(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Kn(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:Kn(e.paths,e.state.name)}}let i=await bw({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=hI(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:ui.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Ew(i.checkpoint.summary),nextAction:Ew(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:ui.maxArtifacts}}import{promises as tj}from"node:fs";import ay from"node:path";import xw from"node:path";var mI="comet.native.archive-preflight.v1",vI="comet.native.archive-preflight.v1",gI="comet.native.archive-operation.v1",wI=/^[a-f0-9]{64}$/u,Pw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Ps(e,t){return e<t?-1:e>t?1:0}function NI(e,t){if(typeof e!="string"||!wI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ht(e,t){return e===null?null:NI(e,t)}function bI(e,t){let i=xw.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||xw.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 kI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function SI(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 EI(e,t){if(!Pw.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=Ht(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=Ht(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Ht(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 CI(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:Ht(e.contractHash,"Native archive contract hash"),acceptanceHash:Ht(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ht(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ht(e.reportHash,"Native archive report hash"),envelopeHash:Ht(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ht(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 xI(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!yI.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(Ps);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function PI(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(Ps)}function Rw(e){if(!Pw.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(EI).sort((l,u)=>Ps(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:L(gI,l)})),r=CI(e.evidence),n=SI(e.workspace),a=[...new Set([...xI(e.findingCodes??[]),...PI({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(Ps),o=kI(e.revision),s=bI(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:mI,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:L(vI,c)}}import{createHash as RI}from"node:crypto";import Aw from"node:path";var AI="comet.native.conflict-radar.v1",xe=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}),_I="comet.native.conflict-radar.v1",II="comet.native.conflict-radar-signals.v1",TI=/^[a-f0-9]{64}$/u,Tw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jI=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),$I=new Set(["capability","operation","baseHash"]),OI=new Set(["path","kind"]);function Cr(e,t){return e<t?-1:e>t?1:0}function vd(e){return Buffer.byteLength(e,"utf8")}function gd(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 wd(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(vd(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function HI(e,t){let i=wd(e,t,xe.maxArtifactPathBytes),r=Aw.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)||Aw.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 jw(e,t){if(typeof e!="string"||!TI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function DI(e,t){let i=gd(e,$I,t),r=wd(i.capability,`${t} capability`,xe.maxCapabilityBytes);if(!Tw.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:jw(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 LI(e,t){let i=gd(e,OI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:HI(i.path,`${t} path`),kind:i.kind}}function BI(e,t){let i=gd(e,jI,`Conflict radar change ${t}`),r=wd(i.name,`Conflict radar change ${t} name`,xe.maxNameBytes);if(!Tw.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>xe.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>xe.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>DI(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>Cr(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)=>LI(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>Cr(c.path,l.path)||Cr(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:jw(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function VI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>xe.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(BI).sort((n,a)=>Cr(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)>xe.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>xe.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function FI(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 MI(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 qI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function WI(e,t){let i=[],r=RI("sha256").update(`${II}
174
+ [`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(gn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<xe.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(FI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=MI(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:qI(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function _w(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function zI(e,t){return _w(e.classification)-_w(t.classification)||Cr(e.left,t.left)||Cr(e.right,t.right)}function Iw(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:AI,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 $w(e){let t=VI(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(WI(t[s],t[c]));i.sort(zI);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=L(_I,{changes:t,relationships:r}),a=i.slice(0,xe.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Iw(t,i,a,n);for(;a.length>0&&vd(JSON.stringify(o))>xe.maxSerializedBytes;)a=a.slice(0,-1),o=Iw(t,i,a,n);if(vd(JSON.stringify(o))>xe.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as ET}from"node:crypto";import{promises as ct}from"node:fs";import bt from"node:path";import Ow from"node:path";var Hw="comet.native.check-receipt.v1",JI="comet.native.check-receipt.v1",xr="scoped-text-safety",yd=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),GI=/^[a-f0-9]{64}$/u,UI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,KI="comet.native.checker-policy.v1",YI="comet.native.check-input.v1",XI=2048,Dw=L(KI,{policy:xr,version:yd,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),QI=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Lw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Vw=["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"],ZI=new Set(Vw);function di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fi(e,t,i,r=[]){let n=new Set([...t,...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 Dt(e,t){if(typeof e!="string"||!GI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Oe(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Fw(e,t){let i=Oe(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Bw(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function eT(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>XI||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=Ow.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Ow.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function tT(e){let t=di(e,"Native check receipt checker");fi(t,["policy","version","hash","limits"],"Native check receipt checker");let i=di(t.limits,"Native check receipt limits");if(fi(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==xr||t.version!==yd||t.hash!==Dw||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:xr,version:yd,hash:Dw,limits:{...Pe}}}function iT(e){let t=di(e,"Native check receipt contract");return fi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Dt(t.expectedHash,"Native check expected contract hash"),beforeHash:Dt(t.beforeHash,"Native check before contract hash"),afterHash:Dt(t.afterHash,"Native check after contract hash")}}function rT(e){let t=di(e,"Native check receipt implementation");return fi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Dt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Dt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Dt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Dt(t.afterSnapshotHash,"Native check after snapshot hash")}}function nT(e,t){let i=di(e,`Native check batch ${t}`);fi(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:Oe(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Oe(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Oe(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Oe(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Oe(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Oe(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>Pe.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>Pe.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function aT(e){let t=di(e,"Native check receipt counts");fi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:Oe(t.filesSelected,"Native check filesSelected"),filesScanned:Oe(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Oe(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Oe(t.bytesScanned,"Native check bytesScanned"),issueCount:Oe(t.issueCount,"Native check issueCount"),recordedIssueCount:Oe(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(nT):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Pe.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function oT(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Lw.indexOf(e.kind)-Lw.indexOf(t.kind)}function sT(e){if(!Array.isArray(e)||e.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=di(r,`Native check issue ${n}`);if(fi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!QI.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:eT(a.path,`Native check issue ${n} path`),line:Fw(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(oT);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function cT(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!ZI.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Vw.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 lT(e){return L(YI,e)}function Mw(e){let t=di(e,"Native check receipt");if(fi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Hw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!UI.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Fw(t.sourceRevision,"Native check source revision"),r=tT(t.checker),n=iT(t.contract),a=rT(t.implementation),o=lT({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Dt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=Bw(t.startedAt,"Native check receipt startedAt"),c=Bw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=aT(t.counts),u=sT(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=cT(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>Pe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Pe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:Hw,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=Dt(t.receiptHash,"Native check receipt content hash");if(L(JI,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var bd="comet.native.verification-receipt.v3",uT=bd,dT="comet.native.declared-artifacts.v1",fT=/^[a-f0-9]{64}$/u,pT=/^acceptance-[a-f0-9]{64}$/u,hT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,vT=4096,gT=256,wT=1024;function Pr(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 pi(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 Lt(e,t){if(typeof e!="string"||!fT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function st(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=We(e).trim();if(!i||i.length>vT||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Nd(e,t){let i=st(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 Yn(e,t,i=st,r=!1,n=gT){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 yT(e,t){if(typeof e!="string"||!pT.test(e))throw new Error(`${t} is invalid`);return e}function NT(e){let t=Pr(e,"Native verification receipt bindings");if(pi(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!hT.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Lt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Lt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Lt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Lt(t.artifactHash,"Native verification receipt artifact hash")}}function bT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=mT.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function kT(e,t,i,r){let n=Pr(t,`Native ${e} evidence`);if(e==="automated-check"){if(pi(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=Nd(n.startedAt,"Native automated-check start time"),o=Nd(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=Pr(n.worktree,"Native automated-check worktree");if(pi(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=Pr(n.afterFence,"Native automated-check after fence");if(pi(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:st(n.executable,"Native automated-check executable"),args:Yn(n.args,"Native automated-check arguments",st,!0),cwd:st(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:st(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Lt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Lt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Lt(n.outputHash,"Native automated-check output hash"),outputSummary:st(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){pi(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=bT(n.checkReceiptRef);if(Lt(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Yn(n.subjects,"Native static inspection subjects",st,r==="required-check"),rule:st(n.rule,"Native static inspection rule"),resultSummary:st(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return pi(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Yn(n.steps,"Native manual evidence steps"),observations:Yn(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function ST(e){let t=Pr(e,"Native verification receipt");if(pi(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=st(t.actor,"Native verification receipt actor"),o=Yn(t.acceptanceIds,"Native receipt acceptance IDs",yT,r==="required-check",wT).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:bd,kind:i,role:r,status:n,bindings:NT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Nd(t.issuedAt,"Native verification receipt issue time"),evidence:kT(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==xr||s.actor!==`native-runtime:${xr}`))throw new Error("Native required check policy identity is invalid");return s}function qw(e){let t=Pr(e,"Native verification receipt");if(pi(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==bd)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=ST(r),a=Lt(t.receiptHash,"Native verification receipt hash");if(L(uT,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function kd(e){return L(dT,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var Gw=/^[a-f0-9]{64}$/u,Rr=ji,LM=3*Rr;function Sd(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function CT(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Rs(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ww(e){let t=await ct.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ct.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function xT(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Sd(i,r))throw new Error("Native evidence path is outside its change");let n=[await Ww(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s=await Ww(a);if(!Sd(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function zw(e){for(let t of e){let i=await ct.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!CT(t,i)||await ct.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function PT(e,t,i={}){let r=await xT(t,bt.dirname(e));await i.afterParentChainCaptured?.();let n=await ct.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ct.realpath(e);if(!Sd(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ct.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ct.lstat(e),ct.realpath(e)]);if(await zw(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Rs(s,n)||!Rs(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Rr)throw new Error(`Native evidence document exceeds ${Rr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=Rr+1-d,S=await o.read(f,0,Math.min(f.length,m),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>Rr)throw new Error(`Native evidence document exceeds ${Rr} bytes`);u.push(Buffer.from(f.subarray(0,S.bytesRead)))}await i.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),ct.lstat(e),ct.realpath(e)]);if(await zw(r),!v.isFile()||v.isSymbolicLink()||h!==a||!Rs(s,p)||!Rs(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 Uw(e,t){if(!Gw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function RT(e,t,i,r,n){if(!Gw.test(i))throw new Error("Native report evidence hash is invalid");let a=await $i({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"||ET("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 Ar(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 AT(e,t,i,r,n){let a=Uw(i,r);return n?bt.join(n,...a.split("/")):ii(U(e,t),a)}async function $i(e){let t=AT(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??ue(e.paths,t);return await z(i,t),PT(t,i,e.hooks)}function Jw(e,t){return vs(e,t)}function _T(e,t){let i=gs(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function IT(e,t,i){let r=Kg(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function TT(e,t,i){let r=Ku(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function jT(e,t,i,r=!1,n){let a=await As(e,t,i.implementationScopeRef,void 0,n);if(r&&await RT(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 Kw(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 Xn(e,t,i,r,n){let a=Ar(i,"scopes"),o=_T(await $i({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Ar(o.baselineProjectionRef,"snapshots"),c=Ar(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([$i({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>Jw(d,s)),$i({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>Jw(d,c))]);return Mg({baseline:l,current:u,scope:o})}async function As(e,t,i,r,n){return(await Xn(e,t,i,r,n)).scope}async function Kw(e,t,i,r,n){let a=Ar(i,"allowances");return IT(await $i({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function Qn(e,t,i,r,n){let a=Ar(i,"receipts"),o=qw(await $i({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 _r(e,t,i,r,n){let a=Ar(i,"verifications"),o=TT(await $i({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await jT(e,t,o,!1,n),o}var $T=4096;async function OT(e,t=xe.maxChanges){try{let i=await Sn({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 Yw(e,t){let i=await gt(e,t),[r,n]=await Promise.all([i.implementation_scope?As(e,t,i.implementation_scope):null,jt(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 _s(e,t,i={}){let n=(await OT(e,$T)).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 Yw(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await Yw(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=$w([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{execFile as JT}from"node:child_process";import{promisify as GT}from"node:util";import{constants as Ed,promises as Je}from"node:fs";import Ir from"node:path";var DT=/^[a-f0-9]{64}$/u,LT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Zn=512*1024;function BT(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Is(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return _e(i,r)?M(i,r):M(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function VT(e,t){let i=Ir.resolve(e),r=Ir.resolve(t);if(!V(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...Ir.relative(i,r).split(Ir.sep).filter(Boolean)]){o&&(a=Ir.join(a,o));let s=await Je.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Je.realpath(a);if(n.length>0&&!V(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 Qw(e){for(let t of e){let i=await Je.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!BT(t,i)||await Je.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function FT(e){if(!DT.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function MT(e){let t=LT.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function qT(e,t,i){return ii(U(e,t),FT(i))}async function WT(e,t,i){let r=await VT(i,Ir.dirname(e)),n=await Je.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Zn)throw new Error(`Native check receipt exceeds ${Zn} bytes`);let[a,o]=await Promise.all([Je.realpath(t),Je.realpath(e)]);if(!V(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Ed.O_RDONLY|Ed.O_NOFOLLOW|Ed.O_NONBLOCK,c=await Je.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(),Je.lstat(e),Je.realpath(e)]);if(await Qw(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Is(n,l)||!Is(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let y=Zn+1-p,N=await c.read(v,0,Math.min(v.length,y),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>Zn)throw new Error(`Native check receipt exceeds ${Zn} bytes`);f.push(Buffer.from(v.subarray(0,N.bytesRead)))}let[h,m,S]=await Promise.all([c.stat(),Je.lstat(e),Je.realpath(e)]);if(await Qw(r),!m.isFile()||m.isSymbolicLink()||S!==o||!V(a,S)||!Is(l,h)||!Is(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function Zw(e,t,i){let r=MT(i),n=U(e,t),a=qT(e,t,r),o=ue(e,a);await z(o,a);let s=Mw(await WT(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var ea=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var Iq=64*1024;var Tq=3600*1e3;var jq=GT(JT);var UT=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function ey(e,t){let i=[];for(let r of UT){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 ty(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Zw(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 hi=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 KT(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 YT(e){let t=KT(e.bundle.baseline),i=await su(e.paths,t,{origin:"explicit",now:e.now});return zu({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 ry(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Xn(e.paths,e.state.name,e.state.implementation_scope),i=await gr({changeDir:me(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await YT({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 ny(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await ry(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 XT(e){let t=await re({root:me(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:gm(t.text)}}function QT(e){let{receipt:t,implementationScope:i}=e,r=[],n=Wu({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 ZT(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:kd(e.implementationScope.scope.declaredArtifacts)}}async function iy(e){let t=await Qn(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=ey(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 hi([{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 ty({paths:e.paths,state:e.state,receipt:t});if(n){let a=QT({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 ej(e){let t=ZT({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await iy({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof hi)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 iy({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof hi)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 hi(i)}function Cd(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function xd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Cd(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([ry(e),_r(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:Cd(e.state.verification_result,"stale"),envelope:null};let r=await XT({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 ej({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:Cd(e.state.verification_result,"invalid"),envelope:null}}}function ij(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function oy(e){try{return await tj.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function rj(e,t){try{return(await re({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function nj(e,t,i){let r=ns(e,i.capability);if(!V(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=ay.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await rj(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await re({root:me(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 aj(e,t){return oy(ad(e,t))}async function Pd(e){let t=e.now??new Date,i=await gt(e.paths,e.name),r=await jt(e.paths,e.name),n=await Ie(e.paths.projectRoot),a=ij(i.name,t),o=ay.resolve(e.paths.nativeRoot,...a.split("/"));if(!V(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(i.spec_changes.map(v=>nj(e.paths,i.name,v))),xd({paths:e.paths,state:i,now:t}),_s(e.paths,i.name),rs(e.paths,i.name),jv(e.paths,i.name),aj(e.paths,i.name),oy(o)]);return Rw({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}async function oj(e,t){let i=U(e,t.name),r=await mr(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 Yo(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 Ai(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function sj(e,t){let i=await oj(e,t);return{committed:i,latest:rw(i),history:iw(i)}}async function sy(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await sj(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 FW=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function lj(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function uj(e){return(await Ng(e))?.change??null}function dj(e,t,i=!1,r){return Ss({state:e,archiveReady:t,evidenceRetreat:i}).command}async function fj(e,t){let i=me(e,t.name),r=[...(await Nu(i,t.brief)).findings,...(await Lv(e,t)).findings,...await kg(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Wo(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 ov(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 gr({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 pw(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 bu(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 cy(e,t,i){let r=await uj(e)===t,n=await Tl(e,t),a=await Ev(e,t),o;try{let w=await wu(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},C=ud({paths:e,state:o,findings:[w]}),$=Ss({state:o,findings:C});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:$.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:dd(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:$,workspace:a,runtime:n,...i?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await Cw({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await sy(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 gr({changeDir:me(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let pe=await _r(e,o.name,o.verification_evidence);for(let Q of pe.acceptanceTrace.entries)C.set(Q.acceptanceId,Q.status==="failed"?"failed":Q.status==="missing"?"missing":"satisfied")}let $=hm({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),T=$.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",$.nextCursor,"--project-root",e.projectRoot]:null;u={...$,...T?{nextPageCommand:lj(T),nextPageArgs:T}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await _s(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await jt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let C=await _n({paths:e,identity:w});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await Zo({paths:e,identity:w});f.push(...C.findingCodes.map($=>({code:$,message:`Native workspace advisory changed: ${$} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let w=await ny({paths:e,state:o});v=w.freshness!=="fresh",p.push(...w.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Pd({paths:e,name:o.name}),m.push(...h.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let S=[...await fj(e,o),...s.findings,...d,...f,...p,...l,...m].filter((w,C,$)=>$.findIndex(T=>T.code===w.code&&T.path===w.path)===C),y=ud({paths:e,state:o,findings:S}),N=y.filter(w=>!vr(w.code)),k=o.phase==="archive"&&h?.ready===!0&&N.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),b=y.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",g=y.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:b||x?null:dj(o,k,E,i?.clarificationMode),archiveReady:k,inspection:s.inspection,findingSummary:dd(y),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Ss({state:o,findings:y,archiveReady:k,evidenceRetreat:E,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:y.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:xs,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:y.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...g?{error:g.message}:{}}}import wj from"node:path";function Oi(e,t,i){return e.language==="zh-CN"?i:t}function pj(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:Oi(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:Oi(e,"Reply A or B","回复 A 或 B"),agentInstruction:Oi(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"&&e.loop.next_action!=="await-verifier-result")return i(Oi(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(Oi(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(Oi(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 ly(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ta(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function uy(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function hj(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function mj(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function vj(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 Hi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:ly({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ta("summary","--summary"),uy(e.name,e.flag)]}}function Rd(e){return[Hi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Hi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function dy(e,t){let i=mj(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:pj(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:[ta("summary","--summary")],commandAlternatives:[Hi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Rd({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:null,requiredInputs:["summary","user-decision"],inputOptions:[ta("summary","--summary")],commandAlternatives:[Hi({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Hi({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],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:[ta("summary","--summary")],commandAlternatives:[Hi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Rd({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:[ta("summary","--summary")],commandAlternatives:Rd({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?ly({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:vj({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?[hj("coordination-mode","--coordination-mode",wm)]:[],uy("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} ${Oi(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:[Hi({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")}}function gj(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function fy(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:gj(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 yj(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function Nj(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 bj(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:Ej(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:Cj(r,i)}))]:[]]}function kj(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 py(e,t){let i=Ee(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:wj.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 Sj(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 Ts(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function Ej(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:Ts(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function Cj(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Ts(e.summary,t)??""}}async function hy(e){let t=await yg(e),i=fy(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Iu({paths:e.paths,state:t.state}),a=await Ln(e.paths,e.name),o=a?{...py(e.paths,t.state),projectRoot:"."}:py(e.paths,t.state),s=dy(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?Sj(e.paths,a):[],u=a?(()=>{let p=a.children.filter(({status:N})=>N==="pending"||N==="ready").length,v=a.children.filter(({status:N})=>N==="active"||N==="verified").length,h=a.children.filter(({status:N})=>N==="integrated"||N==="archived").length,m=a.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,S=a.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:Ts(N.blocker,l)})),y=a.children.flatMap(({blocker:N})=>{let k=Ts(N,l);return k?[k]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:p,working:v,integrated:h,blocked:m,active:S,agents:{working:a.children.filter(({task:N})=>N!==null).length,completed:h},risks:y,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&h===a.children.length?"parent-verification":p>0?"dispatch-ready-child":m>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let p=a?.stateVersion??0,v=bj(t.state,a,l),h=Nj(e.cursor,t.state.state_version,p),m=v.slice(h,h+32),S=h+m.length<v.length?yj(t.state.state_version,p,h+m.length):null;return{items:m,nextCursor:S,supervisorStateVersion:p}})():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:kj(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((p,v)=>({...p,[v.status]:(p[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}}:{}}}import ia from"path";import{realpathSync as Mj}from"fs";var Bt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function my(e){return e?e.command?`${Bt.next} ${e.command}`:e.ask_user?`${Bt.next} ${e.ask_user}`:null:null}function vy(e,t){let i=[e.summary],r=my(e.next);return r&&i.push(r),e.user_message&&i.push("",Bt.relay,e.user_message),t!==void 0&&i.push("",Bt.details,JSON.stringify(t,null,2)),`${i.join(`
175
+ `)}
176
+ `}function gy(e,t,i){let r=[e.summary],n=my(e.next);return n&&r.push(n),e.user_message&&r.push("",Bt.relay,e.user_message),r.push("",`${Bt.detail} ${t}`),i!==void 0&&r.push("",Bt.details,JSON.stringify(i,null,2)),r.join(`
177
+ `)}var p2={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var k2=16*1024*1024,S2=256*1024,E2=16*1024;var _2=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var vz=16*1024*1024,js=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"},$s=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 B(e,t,i){return e==="zh-CN"?i:t}var Ad={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function wy(e,t){return typeof e=="string"&&Ad[e]?B(t,Ad[e].en,Ad[e].zh):typeof e=="string"?e:""}function _d(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 Rj(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 yy(e,t){let i=[];e.failed>0&&i.push(B(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(B(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(B(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=B(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function Ny(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 Id(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function Aj(e,t,i){return e==="done"?B(i,"complete","已完成"):e==="await-user"?B(i,"waiting for a user decision","等待用户决定"):e==="blocked"?B(i,"paused: needs attention","已暂停,需要处理"):t?B(i,"waiting for a user decision","等待用户决定"):B(i,"ready to continue","可继续推进")}function _j(e,t,i){let r=Id(e),n=[];i&&n.push(i);let a=B(r,`Change ${e.change}`,`需求 ${e.change}`),o=wy(e.phase,r),s=Aj(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(yy(t,r));let c=e.userCommunication,l=by(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function by(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:B(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:B(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:B(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function Ij(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function Tj(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=wy(e.phase,t),n=e.status==="await-user"?B(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?B(t,"paused","已暂停"):e.status==="done"?B(t,"complete","已完成"):B(t,"in progress","进行中"),a=_d(e.acceptance)?`${B(t,", ",",")}${yy(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function jj(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 $j(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 Oj(e){if(e.healthy){let r=e.repaired?B("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):B("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=Hj(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:B("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:B("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function Hj(e){return Ny(e)?by(e,Id(e)):void 0}function ky(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if($j(t))return Oj(t);if(Ij(t)){let r=jj(t.items);return{summary:[t.total===t.items.length?B(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):B(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>Tj(a,r))].join(`
178
+ `)}}let i=t.continuation;if(Ny(i))return _j(i,Dj(t),Lj(t,Id(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:B(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 Dj(e){if(_d(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(_d(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return Rj(i.acceptance)}return null}function Lj(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return B(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?B(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Sy(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:B("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:B("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:B("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:B("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:B("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:B("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:B("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:B("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:B("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Ey=["--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."],jd=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:Ey,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>]
179
+ 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 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','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]
180
+ 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 Td(e,t){return`${e}:
177
181
  ${t.map(i=>` ${i}`).join(`
178
- `)}`}function lj(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Ad[i]||t.length>1&&Ad[t[0]]?.subcommands?i:t[0]}function uj(e=[]){let t=lj(e),i=Ad[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Rd("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...oy];return n&&n.length>0&&r.push("",Rd("Options",n)),r.push("",`Output:
179
- ${i.output}`),i.examples&&r.push("",Rd("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
182
+ `)}`}function Bj(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return jd[i]||t.length>1&&jd[t[0]]?.subcommands?i:t[0]}function Vj(e=[]){let t=Bj(e),i=jd[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Td("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...Ey];return n&&n.length>0&&r.push("",Td("Options",n)),r.push("",`Output:
183
+ ${i.output}`),i.examples&&r.push("",Td("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
180
184
  `)}
181
- `}}var dj=uj().usage;var K2=10*1024*1024,pi=class extends Error{};function cy(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new pi(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function ly(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new pi(`${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 pi(`${t} requires a value`);return e.splice(r,2),n}function uy(e){if(e.length>0)throw new pi(`Unexpected argument: ${e[0]}`)}function dy(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new pi(`${t} is required`);return i}function _d(e,t){let i=Qn.normalize(sy(e)),r=Qn.normalize(sy(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function sy(e){let t=Qn.resolve(e);try{return fj.native(t)}catch{return t}}function pj(e){let t=Qn.resolve(e),i=Se(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Se(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!_d(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||_d(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:_d(process.cwd(),i.currentWorktreeRoot)?Qn.resolve(process.cwd()):i.currentWorktreeRoot}async function fy(e){return e?pj(e):mo(process.cwd())}async function py(e){let t=await Wh({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function hy(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
182
- `}}function my(e,t){if(t instanceof pi)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Rs)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 As)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Uo)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 Rn)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 ts)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ko)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 fi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Yn)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 vy(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
183
- `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function gy(e,t){let i=dy(e,"change name");uy(e);let{config:r,paths:n}=await py(t);await pg(n,i);let a=await ls(n,i)?await ay({paths:n,name:i}):await ey(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return hy("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
184
- `)}function hj(e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
185
- `}}async function wy(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s,c;try{cy(n,"--json"),s=ly(n,"--project-root");let u=[...n,...a],d=await fy(s);c=await t(u,d)}catch(u){c=my(e,u)}let l=o?hj(c):vy(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
185
+ `}}var Fj=Vj().usage;var Oz=10*1024*1024,mi=class extends Error{};function Od(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new mi(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function xy(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new mi(`${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 mi(`${t} requires a value`);return e.splice(r,2),n}function Py(e){if(e.length>0)throw new mi(`Unexpected argument: ${e[0]}`)}function Ry(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new mi(`${t} is required`);return i}function $d(e,t){let i=ia.normalize(Cy(e)),r=ia.normalize(Cy(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function Cy(e){let t=ia.resolve(e);try{return Mj.native(t)}catch{return t}}function qj(e){let t=ia.resolve(e),i=Ee(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=Ee(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!$d(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||$d(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:$d(process.cwd(),i.currentWorktreeRoot)?ia.resolve(process.cwd()):i.currentWorktreeRoot}async function Ay(e){return e?qj(e):bo(process.cwd())}async function _y(e){let t=await Kh({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Iy(e){return JSON.stringify(e,null,2)+`
186
+ `}function Ty(e,t,i){return{command:e,exitCode:0,data:t,text:i??Iy(t)}}function Wj(e,t){if(t instanceof mi)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof js)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 $s)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof ts)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 In)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 cs)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof is)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 hi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ea)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 jy(e,t){let i=Wj(e,t),r=i.error;if(!r)return i;let n=Sy({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function $y(e,t,i=!1){let r=e.envelope??ky(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}})+`
187
+ `}:e.error?{exitCode:e.exitCode,stderr:r?gy(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:vy(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==Iy(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
188
+ ${Bt.details}
189
+ ${JSON.stringify(e.data,null,2)}
190
+ `}:{exitCode:e.exitCode,stdout:e.text}}async function Oy(e,t){let i=Ry(e,"change name");Py(e);let{config:r,paths:n}=await _y(t);await bg(n,i);let a=await ms(n,i)?await hy({paths:n,name:i}):await cy(n,i,{clarificationMode:r.native.clarification_mode,maxVerifyFailures:r.native.max_verify_failures});return Ty("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
191
+ `)}async function Hy(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{Od(n,"--json"),Od(n,"--verbose"),c=xy(n,"--project-root");let d=[...n,...a],f=await Ay(c);l=await t(d,f)}catch(d){l=jy(e,d)}let u=$y(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
186
192
  `)?"":`
187
- `)),l.exitCode}process.exitCode=await wy("select",gy);
193
+ `)),u.exitCode}process.exitCode=await Hy("select",Oy);